From 8c1c269916c01f3781c2a6d02cf917f1b6a96737 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 16 Jul 2026 22:08:14 +0800 Subject: [PATCH 01/10] feat(core): NL assistant, app-state/dashboards, cold-tier hardening Rust-side landing of the natural-language assistant and the app-state (conversations + dashboards) subsystem, plus supporting FFI and storage work: - sequins-assistant: tool-injecting Rig CompletionModel + MCP/Responses surfaces over a shared tool registry (list_tables, describe_schema, column_profile, time_range, sample, explain, run_sql, validate_seql, run_seql), with SeQL grounding. - sequins-metadata: AppStateStore for conversations + dashboards, JSON-backed in the object store and projected into DataFusion tables. - datafusion-backend: app_state SessionContext + execute_app_state_sql; RelRoot.names alias honoring so output columns use SeQL aliases. - ffi: assistant + dashboard C API; app-state SeQL query entry point; panic-containment on the spawned query task. - cold-tier: UnsupportedForCold error + is_unsupported_for_cold(); cold-flush callback evicts un-encodable (Map-column) batches instead of retaining them (fixes unbounded hot-tier growth / OOM under load). Co-Authored-By: Claude Opus 4.8 (1M context) --- Cargo.lock | 724 +++++++++++- Cargo.toml | 12 + crates/seql-substrait/src/compiler.rs | 10 +- crates/sequins-assistant/Cargo.toml | 59 + crates/sequins-assistant/README.md | 73 ++ crates/sequins-assistant/src/config.rs | 273 +++++ crates/sequins-assistant/src/lib.rs | 25 + crates/sequins-assistant/src/mcp.rs | 133 +++ crates/sequins-assistant/src/model.rs | 398 +++++++ crates/sequins-assistant/src/responses.rs | 1036 +++++++++++++++++ crates/sequins-assistant/src/serve.rs | 470 ++++++++ crates/sequins-assistant/src/tools/mod.rs | 8 + crates/sequins-assistant/src/tools/ops.rs | 660 +++++++++++ .../sequins-assistant/src/tools/registry.rs | 145 +++ crates/sequins-assistant/tests/agent_loop.rs | 510 ++++++++ crates/sequins-client/Cargo.toml | 2 + crates/sequins-client/src/lib.rs | 136 ++- crates/sequins-cold-tier/src/error.rs | 15 + crates/sequins-cold-tier/src/record_batch.rs | 59 +- crates/sequins-datafusion-backend/Cargo.toml | 2 + .../src/app_state.rs | 320 +++++ .../src/execution.rs | 143 ++- crates/sequins-datafusion-backend/src/lib.rs | 66 ++ .../src/trait_impls.rs | 8 + .../tests/alias_columns.rs | 74 ++ .../tests/app_state_sql.rs | 77 ++ crates/sequins-ffi/Cargo.toml | 3 + crates/sequins-ffi/include/sequins.h | 202 ++++ crates/sequins-ffi/src/assistant.rs | 321 +++++ crates/sequins-ffi/src/dashboard.rs | 226 ++++ crates/sequins-ffi/src/data_source.rs | 7 +- crates/sequins-ffi/src/lib.rs | 2 + crates/sequins-ffi/src/seql.rs | 349 +++++- crates/sequins-metadata/Cargo.toml | 21 + crates/sequins-metadata/src/error.rs | 15 + crates/sequins-metadata/src/lib.rs | 18 + crates/sequins-metadata/src/store.rs | 393 +++++++ crates/sequins-metadata/src/types.rs | 182 +++ crates/sequins-storage/Cargo.toml | 1 + .../sequins-storage/src/storage/accessors.rs | 7 + .../sequins-storage/src/storage/app_state.rs | 26 + .../src/storage/constructor.rs | 36 +- crates/sequins-storage/src/storage/mod.rs | 5 + crates/sequins-traits/src/query.rs | 21 + 44 files changed, 7208 insertions(+), 65 deletions(-) create mode 100644 crates/sequins-assistant/Cargo.toml create mode 100644 crates/sequins-assistant/README.md create mode 100644 crates/sequins-assistant/src/config.rs create mode 100644 crates/sequins-assistant/src/lib.rs create mode 100644 crates/sequins-assistant/src/mcp.rs create mode 100644 crates/sequins-assistant/src/model.rs create mode 100644 crates/sequins-assistant/src/responses.rs create mode 100644 crates/sequins-assistant/src/serve.rs create mode 100644 crates/sequins-assistant/src/tools/mod.rs create mode 100644 crates/sequins-assistant/src/tools/ops.rs create mode 100644 crates/sequins-assistant/src/tools/registry.rs create mode 100644 crates/sequins-assistant/tests/agent_loop.rs create mode 100644 crates/sequins-datafusion-backend/src/app_state.rs create mode 100644 crates/sequins-datafusion-backend/tests/alias_columns.rs create mode 100644 crates/sequins-datafusion-backend/tests/app_state_sql.rs create mode 100644 crates/sequins-ffi/src/assistant.rs create mode 100644 crates/sequins-ffi/src/dashboard.rs create mode 100644 crates/sequins-metadata/Cargo.toml create mode 100644 crates/sequins-metadata/src/error.rs create mode 100644 crates/sequins-metadata/src/lib.rs create mode 100644 crates/sequins-metadata/src/store.rs create mode 100644 crates/sequins-metadata/src/types.rs create mode 100644 crates/sequins-storage/src/storage/app_state.rs diff --git a/Cargo.lock b/Cargo.lock index fae12381..936b770d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -415,6 +415,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "as-any" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0f477b951e452a0b6b4a10b53ccd569042d1d01729b519e02074a9c0958a063" + [[package]] name = "async-channel" version = "2.5.0" @@ -622,6 +628,29 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4342d8937fc7e5dd9b1c60292261c0670c882a2cd1719cfc11b1af41731e32ad" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9ceb1da931507a12f4fccea479dccd00da1943e1b4ae72d8e502d707361444" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "axum" version = "0.7.9" @@ -1222,12 +1251,31 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "colorchoice" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "comfy-table" version = "7.2.2" @@ -1318,6 +1366,15 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +[[package]] +name = "convert_case" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -1517,6 +1574,12 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "data-encoding" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" + [[package]] name = "datafusion" version = "54.0.0" @@ -2234,6 +2297,47 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "deluxe" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed332aaf752b459088acf3dd4eca323e3ef4b83c70a84ca48fb0ec5305f1488" +dependencies = [ + "deluxe-core", + "deluxe-macros", + "once_cell", + "proc-macro2", + "syn 2.0.118", +] + +[[package]] +name = "deluxe-core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddada51c8576df9d6a8450c351ff63042b092c9458b8ac7d20f89cbd0ffd313" +dependencies = [ + "arrayvec", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 2.0.118", +] + +[[package]] +name = "deluxe-macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87546d9c837f0b7557e47b8bd6eae52c3c223141b76aa233c345c9ab41d9117" +dependencies = [ + "deluxe-core", + "heck 0.4.1", + "if_chain", + "proc-macro-crate 1.3.1", + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "deranged" version = "0.5.8" @@ -2288,6 +2392,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab23e69df104e2fd85ee63a533a22d2132ef5975dc6b36f9f3e5a7305e4a8ed7" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.20" @@ -2366,6 +2476,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "eventsource-stream" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" +dependencies = [ + "futures-core", + "nom", + "pin-project-lite", +] + [[package]] name = "ext-trait" version = "1.0.1" @@ -2554,6 +2675,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "fsst-rs" version = "0.5.11" @@ -2653,6 +2780,16 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" +dependencies = [ + "gloo-timers", + "send_wrapper", +] + [[package]] name = "futures-util" version = "0.3.32" @@ -2840,7 +2977,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8084af62f09475a3f529b1629c10c429d7600ee1398ae12dd3bf175d74e7145" dependencies = [ "heck 0.5.0", - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.118", @@ -2862,6 +2999,18 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +[[package]] +name = "gloo-timers" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "482ce8a491a501da4cd806bd190275363d674f2845005c6ddbd5d3e1dd54495d" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "gobject-sys" version = "0.20.10" @@ -2954,7 +3103,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ed1786c4703dd196baf7e103525ce0cf579b3a63a0570fe653b7ee6bac33999" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 2.0.118", @@ -3401,6 +3550,12 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "if_chain" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" + [[package]] name = "indexmap" version = "1.9.3" @@ -3423,6 +3578,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + [[package]] name = "integer-encoding" version = "3.0.4" @@ -3525,6 +3689,55 @@ dependencies = [ "jiff-tzdb", ] +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.118", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.118", +] + [[package]] name = "jobserver" version = "0.1.34" @@ -3902,6 +4115,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3961,6 +4184,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" +[[package]] +name = "nanoid" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" +dependencies = [ + "rand 0.8.6", +] + [[package]] name = "nanorand" version = "0.7.0" @@ -4143,7 +4375,7 @@ dependencies = [ "percent-encoding", "quick-xml", "rand 0.10.2", - "reqwest", + "reqwest 0.12.28", "ring", "rustls-pki-types", "serde", @@ -4283,6 +4515,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ordered-float" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e" +dependencies = [ + "num-traits", +] + [[package]] name = "os_str_bytes" version = "6.6.1" @@ -4393,6 +4634,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbjson" version = "0.8.0" @@ -4634,13 +4881,23 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit", + "toml_edit 0.25.12+spec-1.1.0", ] [[package]] @@ -4879,6 +5136,7 @@ version = "0.11.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" dependencies = [ + "aws-lc-rs", "bytes", "getrandom 0.4.3", "lru-slab", @@ -5107,6 +5365,26 @@ dependencies = [ "bitflags 2.13.0", ] +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "regex" version = "1.12.4" @@ -5224,10 +5502,106 @@ dependencies = [ "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams", + "wasm-streams 0.4.2", + "web-sys", +] + +[[package]] +name = "reqwest" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.5.0", "web-sys", ] +[[package]] +name = "rig-core" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80a4bc7a93b329c4e1a66d5fd211d79990e7331e3c701f057c29f135f548686d" +dependencies = [ + "as-any", + "async-stream", + "base64", + "bytes", + "eventsource-stream", + "fastrand", + "futures", + "futures-timer", + "glob", + "http", + "indexmap 2.14.0", + "mime", + "mime_guess", + "nanoid", + "ordered-float 5.3.0", + "pin-project-lite", + "reqwest 0.13.4", + "rig-derive", + "rmcp", + "schemars 1.2.1", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tokio-tungstenite", + "tracing", + "tracing-futures", + "url", +] + +[[package]] +name = "rig-derive" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5531bfa887b371eab658a92de7db35003370bbeee208ff5e68bbb81a5ae92d3d" +dependencies = [ + "convert_case", + "deluxe", + "indoc", + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "serde_json", + "syn 2.0.118", +] + [[package]] name = "ring" version = "0.17.14" @@ -5242,6 +5616,51 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1f571c72940a19d9532fe52dbea8bc9912bf1d766c2970bb824056b86f3f59" +dependencies = [ + "async-trait", + "base64", + "bytes", + "chrono", + "futures", + "http", + "http-body", + "http-body-util", + "pastey", + "pin-project-lite", + "rand 0.10.2", + "reqwest 0.13.4", + "rmcp-macros", + "schemars 1.2.1", + "serde", + "serde_json", + "sse-stream", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", + "tracing", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aad0035b69380782d78ea95b508327e6deaa2235909053e596eea8f27b5e1d5" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 2.0.118", +] + [[package]] name = "roaring" version = "0.11.4" @@ -5302,6 +5721,7 @@ version = "0.23.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ + "aws-lc-rs", "once_cell", "ring", "rustls-pki-types", @@ -5332,12 +5752,40 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + [[package]] name = "rustls-webpki" version = "0.103.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -5392,7 +5840,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" dependencies = [ "dyn-clone", - "schemars_derive", + "schemars_derive 0.8.22", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +dependencies = [ + "chrono", + "dyn-clone", + "ref-cast", + "schemars_derive 1.2.1", "serde", "serde_json", ] @@ -5409,6 +5871,18 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "schemars_derive" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.118", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -5454,6 +5928,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + [[package]] name = "seq-macro" version = "0.3.6" @@ -5520,6 +6000,42 @@ dependencies = [ "vortex", ] +[[package]] +name = "sequins-assistant" +version = "0.4.0" +dependencies = [ + "arrow", + "async-stream", + "async-trait", + "axum 0.7.9", + "datafusion", + "eventsource-stream", + "futures", + "indexmap 2.14.0", + "object_store", + "reqwest 0.13.4", + "rig-core", + "rmcp", + "schemars 1.2.1", + "seql-ast", + "seql-parser", + "sequins-arrow-schema", + "sequins-datafusion-backend", + "sequins-flight", + "sequins-metadata", + "sequins-storage", + "sequins-traits", + "serde", + "serde_json", + "serde_yaml", + "tempfile", + "thiserror 1.0.69", + "tokio", + "tokio-stream", + "tower", + "tracing", +] + [[package]] name = "sequins-attribute-codec" version = "0.4.0" @@ -5557,7 +6073,7 @@ dependencies = [ "opentelemetry-proto", "prost 0.14.4", "rand 0.8.6", - "reqwest", + "reqwest 0.12.28", "seql-ast", "seql-substrait", "sequins-client", @@ -5588,9 +6104,11 @@ dependencies = [ "datafusion", "futures", "prost 0.14.4", + "reqwest 0.12.28", "seql-ast", "seql-parser", "seql-substrait", + "sequins-metadata", "sequins-traits", "serde", "serde_json", @@ -5671,9 +6189,11 @@ dependencies = [ "sequins-flight", "sequins-hot-tier", "sequins-live-query", + "sequins-metadata", "sequins-storage", "sequins-traits", "sequins-types", + "serde_json", "tempfile", "tokio", "tracing", @@ -5693,14 +6213,17 @@ dependencies = [ "parking_lot", "seql-ast", "seql-parser", + "sequins-assistant", "sequins-client", "sequins-datafusion-backend", "sequins-flight", + "sequins-metadata", "sequins-server", "sequins-storage", "sequins-traits", "sequins-types", "sequins-view", + "serde", "serde_json", "tempfile", "thiserror 1.0.69", @@ -5791,6 +6314,21 @@ dependencies = [ "uuid", ] +[[package]] +name = "sequins-metadata" +version = "0.4.0" +dependencies = [ + "async-trait", + "futures", + "object_store", + "serde", + "serde_json", + "tempfile", + "thiserror 1.0.69", + "tokio", + "tracing", +] + [[package]] name = "sequins-otlp" version = "0.4.0" @@ -5884,6 +6422,7 @@ dependencies = [ "sequins-cold-tier", "sequins-hot-tier", "sequins-live-query", + "sequins-metadata", "sequins-otlp", "sequins-traits", "sequins-types", @@ -6097,6 +6636,17 @@ dependencies = [ "unsafe-libyaml", ] +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -6162,6 +6712,16 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd_cesu8" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -6265,6 +6825,19 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "sse-stream" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a" +dependencies = [ + "bytes", + "futures-util", + "http-body", + "http-body-util", + "pin-project-lite", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -6318,7 +6891,7 @@ dependencies = [ "prost-build 0.14.4", "prost-types 0.14.4", "regress", - "schemars", + "schemars 0.8.22", "semver", "serde", "serde_json", @@ -6693,7 +7266,7 @@ checksum = "7e54bc85fc7faa8bc175c4bab5b92ba8d9a3ce893d0e9f42cc455c8ab16a9e09" dependencies = [ "byteorder", "integer-encoding", - "ordered-float", + "ordered-float 2.10.1", ] [[package]] @@ -6820,6 +7393,22 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "tokio-tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + [[package]] name = "tokio-util" version = "0.7.18" @@ -6851,12 +7440,18 @@ dependencies = [ "indexmap 2.14.0", "serde_core", "serde_spanned", - "toml_datetime", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", "toml_writer", "winnow 1.0.3", ] +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" + [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -6866,6 +7461,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.14.0", + "toml_datetime 0.6.11", + "winnow 0.5.40", +] + [[package]] name = "toml_edit" version = "0.25.12+spec-1.1.0" @@ -6873,7 +7479,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" dependencies = [ "indexmap 2.14.0", - "toml_datetime", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", "winnow 1.0.3", ] @@ -7030,6 +7636,18 @@ dependencies = [ "valuable", ] +[[package]] +name = "tracing-futures" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" +dependencies = [ + "futures", + "futures-task", + "pin-project", + "tracing", +] + [[package]] name = "tracing-log" version = "0.2.0" @@ -7078,6 +7696,25 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.4", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 2.0.18", + "utf-8", +] + [[package]] name = "turmoil" version = "0.6.6" @@ -7126,7 +7763,7 @@ dependencies = [ "proc-macro2", "quote", "regress", - "schemars", + "schemars 0.8.22", "semver", "serde", "serde_json", @@ -7143,7 +7780,7 @@ checksum = "911c32f3c8514b048c1b228361bebb5e6d73aeec01696e8cc0e82e2ffef8ab7a" dependencies = [ "proc-macro2", "quote", - "schemars", + "schemars 0.8.22", "semver", "serde", "serde_json", @@ -7158,6 +7795,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -7200,6 +7843,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "utf8-ranges" version = "1.0.5" @@ -7992,6 +8641,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.103" @@ -8012,6 +8674,33 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.8", +] + +[[package]] +name = "webpki-roots" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi" version = "0.3.9" @@ -8204,6 +8893,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "0.6.26" diff --git a/Cargo.toml b/Cargo.toml index 35f3d8ba..cbce53a2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,9 +21,11 @@ members = [ "crates/sequins-cold-tier", "crates/sequins-storage", "crates/sequins-datafusion-backend", + "crates/sequins-metadata", "crates/sequins-view", "crates/sequins-client", "crates/sequins-server", + "crates/sequins-assistant", "crates/sequins-ffi", "crates/sequins-cli", "apps/linux", @@ -60,9 +62,11 @@ sequins-hot-tier = { path = "crates/sequins-hot-tier" } sequins-cold-tier = { path = "crates/sequins-cold-tier" } sequins-storage = { path = "crates/sequins-storage" } sequins-datafusion-backend = { path = "crates/sequins-datafusion-backend" } +sequins-metadata = { path = "crates/sequins-metadata" } sequins-view = { path = "crates/sequins-view" } sequins-client = { path = "crates/sequins-client" } sequins-server = { path = "crates/sequins-server" } +sequins-assistant = { path = "crates/sequins-assistant" } sequins-ffi = { path = "crates/sequins-ffi" } # OpenTelemetry @@ -150,6 +154,14 @@ tracing-appender = "0.2" winnow = "0.6" indexmap = { version = "2", features = ["serde"] } +# AI assistant — Rig agent framework + Model Context Protocol. +# Imported as `rig` (rig-core's lib name is `rig_core`) to match Rig's docs. +# rmcp/schemars versions are pinned to what `rig-core`'s `rmcp` feature resolves, +# so MCP tool types line up across the Rig ↔ rmcp boundary. +rig = { version = "0.39", package = "rig-core", features = ["rmcp"] } +rmcp = { version = "1.8", features = ["client", "server", "macros", "transport-streamable-http-server", "transport-streamable-http-client-reqwest"] } +schemars = "1" + # CLI clap = { version = "4", features = ["derive"] } diff --git a/crates/seql-substrait/src/compiler.rs b/crates/seql-substrait/src/compiler.rs index 6ab644b4..9563e0df 100644 --- a/crates/seql-substrait/src/compiler.rs +++ b/crates/seql-substrait/src/compiler.rs @@ -5,6 +5,7 @@ //! embedded in `advanced_extensions.enhancement`. use arrow::datatypes::DataType as ArrowDataType; +use arrow::datatypes::TimeUnit as ArrowTimeUnit; use datafusion::datasource::provider_as_source; use datafusion::execution::context::SessionContext; use datafusion::execution::FunctionRegistry; @@ -1453,7 +1454,14 @@ fn group_expr_to_df_expr( // E.g., for 5-minute bins: (cast(ts, Int64) / 300_000_000_000) * 300_000_000_000 let bin_lit = lit(bin_ns as i64); let int_expr = cast(expr, ArrowDataType::Int64); - (int_expr.clone() / bin_lit.clone()) * bin_lit + let binned = (int_expr.clone() / bin_lit.clone()) * bin_lit; + // Wrap the binned epoch-nanoseconds back into a Timestamp so the bucket column is + // a real temporal type: clients render a proper time axis (Arrow Timestamp → + // Swift `Date`) instead of a giant integer, and downstream keeps time semantics. + cast( + binned, + ArrowDataType::Timestamp(ArrowTimeUnit::Nanosecond, None), + ) } else { expr }; diff --git a/crates/sequins-assistant/Cargo.toml b/crates/sequins-assistant/Cargo.toml new file mode 100644 index 00000000..656c6229 --- /dev/null +++ b/crates/sequins-assistant/Cargo.toml @@ -0,0 +1,59 @@ +[package] +name = "sequins-assistant" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "In-engine AI assistant for Sequins — a tool-injecting Rig CompletionModel + MCP server over DataFusion" + +[dependencies] +# Sequins engine + query language +sequins-datafusion-backend = { workspace = true } +sequins-flight = { workspace = true } +sequins-traits = { workspace = true } +sequins-arrow-schema = { workspace = true } +sequins-metadata = { workspace = true } +seql-parser = { workspace = true } +seql-ast = { workspace = true } + +# Arrow / DataFusion — `prettyprint` renders RecordBatches as LLM-legible tables +arrow = { workspace = true, features = ["prettyprint"] } +datafusion = { workspace = true } + +# Agent framework + Model Context Protocol +rig = { workspace = true } +rmcp = { workspace = true } + +# HTTP server (OpenAI-compatible endpoint) + client (names the backing model type). +# reqwest is pinned to rig-core 0.39's version (0.13) so the backing model's +# HTTP-client type matches rig's `HttpClientExt` impl — the workspace's 0.12 is a +# different `reqwest::Client` and would not satisfy the bound. +axum = { workspace = true } +reqwest = "0.13" + +# Async +tokio = { workspace = true } +tokio-stream = { workspace = true } +futures = { workspace = true } +async-stream = { workspace = true } +async-trait = { workspace = true } +# SSE framing for the remote assistant stream (already compiled transitively via rig). +eventsource-stream = "0.2" + +# Serialization + JSON schema for tool parameters +serde = { workspace = true } +serde_json = { workspace = true } +schemars = { workspace = true } +indexmap = { workspace = true } + +# Error handling + logging +thiserror = { workspace = true } +tracing = { workspace = true } + +[dev-dependencies] +sequins-storage = { workspace = true, features = ["test-utils"] } +tempfile = { workspace = true } +tower = { workspace = true } +serde_yaml = { workspace = true } +object_store = { workspace = true } diff --git a/crates/sequins-assistant/README.md b/crates/sequins-assistant/README.md new file mode 100644 index 00000000..d691369d --- /dev/null +++ b/crates/sequins-assistant/README.md @@ -0,0 +1,73 @@ +# sequins-assistant + +An in-engine AI assistant for Sequins: a tool-injecting [Rig](https://github.com/0xPlaygrounds/rig) +`CompletionModel` that runs an agentic loop **in-process** over a `DataFusionBackend` — exploring +telemetry and emitting SeQL — plus a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) +server exposing the same tools to bring-your-own-model clients. + +## Purpose + +Ask a question about your observability data; the agent explores it (schema, cardinality, time +range, ad-hoc read-only SQL), writes a SeQL query, validates and runs it, and hands the query back +to the app to render. It ships as an OpenAI-compatible endpoint so anything that speaks OpenAI (the +Sequins app, `curl`, OpenCode, Cursor) can drive it, and as an MCP server so external agents can use +the tools with their own model. + +## Architecture + +- **`CompletionModel` is the seam.** `SequinsAssistantModel` wraps a real backing model `B`, + injects our tool set + SeQL grounding into every request, and runs the tool loop in-process: + when the model calls **our** tools it executes them against DataFusion and loops; when it calls + the **caller's** own tools (or returns text) it hands the response straight back. Our own tool + calls are stripped from returned responses, so a caller only ever sees its own tools. +- **One tool set, three surfaces.** [`tools::ops`] is the single operation layer; [`tools::registry`] + exposes it as Rig tools (for the agent) and the [`mcp`] module exposes the same via `rmcp`. + - **`/v1/chat/completions`** ([`serve::completion_model_router`]) — OpenAI Chat Completions over + an `IndexMap` model registry (+ `/v1/models`). Server-side tool activity is *hidden*: the caller + sees only the final text or its own (forwarded) tool calls. + - **`/v1/responses`** ([`responses::responses_router`]) — the OpenAI **Responses API**, which + streams typed output items. Every server-executed tool call is surfaced as a resolved + `sequins.tool_result` item (name + arguments + rendered output), so a client can *render* the + exploration it didn't drive. Client tools still appear as `function_call` items to execute. + - **`/mcp`** ([`mcp`]) — MCP tools for bring-your-own-model clients. + + The middleware's [`model::AgentEvent`] trace is the seam: the chat path ignores `ServerTool` + events; the Responses path emits them. + +## Tools + +**Explore** (read-only, over the backend's `SessionContext`): `list_tables`, `describe_schema`, +`column_profile`, `time_range`, `sample`, `explain`, `run_sql`. +**Present** (the SeQL path): `validate_seql`, `run_seql`. + +Visualizations are **not** an in-process tool — the app declares its own `render_visualization` +tool, which the model calls and which is forwarded back for the app to draw. + +## Usage + +The daemon mounts both surfaces from an `assistant:` config (see `sequins-pro-daemon --assistant-config`). +Programmatically: + +```rust +use sequins_assistant::{build_registry, completion_model_router, mcp_router, AssistantConfig, Tools}; + +let tools = Tools::new(backend); // Arc +let registry = build_registry(&config, tools.clone())?; // OpenAI-compatible providers +let app = completion_model_router(registry).merge(mcp_router(tools)); +axum::serve(listener, app).await?; +``` + +API keys come from the environment (default `SEQUINS_ASSISTANT_API_KEY`), never from config. + +## Testing + +```bash +cargo test -p sequins-assistant +``` + +Tests cover the tool operation layer (against seeded storage), the middleware tool-routing loop +(with a fake backing model — no network), the OpenAI `/v1` surface, and the MCP tool dispatch. + +## License + +MIT OR Apache-2.0. diff --git a/crates/sequins-assistant/src/config.rs b/crates/sequins-assistant/src/config.rs new file mode 100644 index 00000000..8fb47f58 --- /dev/null +++ b/crates/sequins-assistant/src/config.rs @@ -0,0 +1,273 @@ +//! Assistant configuration and the model-registry builder the daemon mounts. +//! +//! An `assistant:` config section lists zero or more OpenAI-compatible providers. +//! Each becomes a named [`SequinsAssistantModel`] entry in the registry served by +//! [`crate::serve::completion_model_router`]. An empty `models` list is valid: the +//! `/v1/models` endpoint then lists nothing and clients bring their own model, +//! driving the tools over MCP instead. +//! +//! API keys are read from the environment (never stored in config). + +use indexmap::IndexMap; +use rig::client::{CompletionClient, ProviderClient}; +use rig::providers::openai; +use serde::Deserialize; + +use crate::model::SequinsAssistantModel; +use crate::tools::Tools; + +/// The backing model each registry entry wraps — an OpenAI Chat Completions model +/// (compatible with OpenAI, OpenRouter, vLLM, Ollama, … via `base_url`). +pub type BackingModel = openai::completion::CompletionModel; + +/// The named registry of assistant models served over `/v1`. +pub type ModelRegistry = IndexMap>; + +/// Default environment variable holding an explicit provider's API key. +pub const DEFAULT_API_KEY_ENV: &str = "SEQUINS_ASSISTANT_API_KEY"; + +/// Env var Rig's OpenAI provider reads for `from_env` auto-config (the key's +/// presence is what enables the auto `default` model). `OPENAI_BASE_URL` (also read +/// by Rig) points it at any OpenAI-compatible endpoint. +const OPENAI_API_KEY_ENV: &str = "OPENAI_API_KEY"; +/// Id of the model auto-registered from the environment. +const DEFAULT_MODEL_ID: &str = "default"; + +/// The `assistant:` config section. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AssistantConfig { + /// Configured providers/models. May be empty (then only MCP is useful). + #[serde(default)] + pub models: Vec, + /// Optional override for the SeQL system grounding. + #[serde(default)] + pub grounding: Option, + /// Auto-register a `default` model from the environment (Rig's `from_env`: + /// `OPENAI_API_KEY` + optional `OPENAI_BASE_URL`; model name from `OPENAI_MODEL`, + /// else `gpt-4o`) when the key is present. Explicit `models` — including one with + /// id `default` — take precedence. Defaults to `true`. + #[serde(default = "default_true")] + pub auto_from_env: bool, +} + +impl Default for AssistantConfig { + fn default() -> Self { + Self { + models: Vec::new(), + grounding: None, + auto_from_env: true, + } + } +} + +fn default_true() -> bool { + true +} + +/// The backing model name for the env-auto-configured `default` model. +fn default_model_name() -> String { + std::env::var("OPENAI_MODEL") + .ok() + .or_else(|| std::env::var("SEQUINS_ASSISTANT_MODEL").ok()) + .unwrap_or_else(|| "gpt-4o".to_string()) +} + +/// A single OpenAI-compatible provider entry. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ModelConfig { + /// Public model id exposed via `/v1/models` and selected by the client. + pub id: String, + /// OpenAI-compatible base URL. Omit for api.openai.com. + #[serde(default)] + pub base_url: Option, + /// Backing model name to request from the provider (e.g. `gpt-4o`). + pub model: String, + /// Environment variable holding the API key (default `SEQUINS_ASSISTANT_API_KEY`). + #[serde(default)] + pub api_key_env: Option, + /// Optional sampling temperature (reserved for future per-model defaults). + #[serde(default)] + pub temperature: Option, +} + +/// Errors building the model registry. +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("model '{id}': API key env var '{env}' is not set")] + MissingApiKey { id: String, env: String }, + #[error("model '{id}': failed to build provider client: {reason}")] + Client { id: String, reason: String }, +} + +/// Build a single OpenAI-compatible backing model from explicit connection +/// parameters (used by the FFI's local assistant, where the config comes from the +/// app's connection profile). `base_url` omitted ⇒ api.openai.com. +pub fn build_backing_model( + base_url: Option<&str>, + model: &str, + api_key: &str, +) -> Result { + let mut builder = openai::Client::builder().api_key(api_key); + if let Some(base) = base_url { + builder = builder.base_url(base); + } + let client = builder.build().map_err(|e| ConfigError::Client { + id: model.to_string(), + reason: e.to_string(), + })?; + Ok(client.completions_api().completion_model(model)) +} + +/// Build the named model registry from the config, wrapping each configured +/// provider in a [`SequinsAssistantModel`] over the shared tool set. +pub fn build_registry( + config: &AssistantConfig, + tools: Tools, +) -> Result { + let mut registry = ModelRegistry::new(); + + // Explicit config entries first, so they win over any env auto-config. + for m in &config.models { + let env = m + .api_key_env + .clone() + .unwrap_or_else(|| DEFAULT_API_KEY_ENV.to_string()); + let api_key = std::env::var(&env).map_err(|_| ConfigError::MissingApiKey { + id: m.id.clone(), + env: env.clone(), + })?; + + let mut builder = openai::Client::builder().api_key(&api_key); + if let Some(base) = &m.base_url { + builder = builder.base_url(base); + } + let client = builder.build().map_err(|e| ConfigError::Client { + id: m.id.clone(), + reason: e.to_string(), + })?; + let backing = client.completions_api().completion_model(&m.model); + tracing::info!( + id = %m.id, + base_url = %m.base_url.as_deref().unwrap_or("https://api.openai.com/v1 (default)"), + backing_model = %m.model, + api_key_env = %env, + "assistant model registered" + ); + registry.insert(m.id.clone(), wrap(backing, config, &tools)); + } + + // Env auto-config: register a `default` model from `OPENAI_API_KEY` (+ optional + // `OPENAI_BASE_URL`) via Rig's `from_env`, unless config already defined `default`. + if config.auto_from_env + && std::env::var(OPENAI_API_KEY_ENV).is_ok() + && !registry.contains_key(DEFAULT_MODEL_ID) + { + let client = openai::Client::from_env().map_err(|e| ConfigError::Client { + id: DEFAULT_MODEL_ID.to_string(), + reason: e.to_string(), + })?; + let backing_model = default_model_name(); + tracing::info!( + id = %DEFAULT_MODEL_ID, + base_url = %std::env::var("OPENAI_BASE_URL") + .unwrap_or_else(|_| "https://api.openai.com/v1 (default)".to_string()), + backing_model = %backing_model, + api_key_env = %OPENAI_API_KEY_ENV, + "assistant model registered (env auto-config)" + ); + let backing = client.completions_api().completion_model(backing_model); + registry.insert(DEFAULT_MODEL_ID.to_string(), wrap(backing, config, &tools)); + } + + Ok(registry) +} + +/// Wrap a backing model in the middleware, applying the config's grounding override. +fn wrap( + backing: BackingModel, + config: &AssistantConfig, + tools: &Tools, +) -> SequinsAssistantModel { + let mut model = SequinsAssistantModel::new(backing, tools.clone()); + if let Some(grounding) = &config.grounding { + model = model.with_grounding(grounding.clone()); + } + model +} + +#[cfg(test)] +mod tests { + use super::*; + use sequins_datafusion_backend::DataFusionBackend; + use sequins_storage::test_fixtures::TestStorageBuilder; + use std::sync::Arc; + + async fn tools() -> (Tools, tempfile::TempDir) { + let (storage, temp) = TestStorageBuilder::new().build().await; + let backend = Arc::new(DataFusionBackend::new(Arc::new(storage))); + (Tools::new(backend), temp) + } + + #[tokio::test] + async fn empty_config_yields_empty_registry() { + let (tools, _t) = tools().await; + // Disable env auto-config so the result doesn't depend on the ambient + // `OPENAI_API_KEY` (which may be set in the developer/CI environment). + let config = AssistantConfig { + auto_from_env: false, + ..Default::default() + }; + let registry = build_registry(&config, tools).unwrap(); + assert!(registry.is_empty()); + } + + #[tokio::test] + async fn missing_api_key_is_reported() { + let (tools, _t) = tools().await; + let config = AssistantConfig { + models: vec![ModelConfig { + id: "x".into(), + base_url: None, + model: "gpt-4o".into(), + api_key_env: Some("SEQUINS_ASSISTANT_KEY_DEFINITELY_UNSET".into()), + temperature: None, + }], + grounding: None, + auto_from_env: false, + }; + let result = build_registry(&config, tools); + assert!(matches!(result, Err(ConfigError::MissingApiKey { .. }))); + } + + #[test] + fn parses_yaml() { + let yaml = r#" +models: + - id: default + base_url: http://localhost:11434/v1 + model: llama3.1 +"#; + let cfg: AssistantConfig = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(cfg.models.len(), 1); + assert_eq!(cfg.models[0].id, "default"); + assert_eq!( + cfg.models[0].base_url.as_deref(), + Some("http://localhost:11434/v1") + ); + // Missing field defaults to enabled. + assert!(cfg.auto_from_env); + } + + #[tokio::test] + async fn env_autoconfig_registers_default_model() { + let (tools, _t) = tools().await; + // This test mutates a process-global env var; it is the only test that + // reads `OPENAI_API_KEY` (the others set `auto_from_env: false`). + std::env::set_var(OPENAI_API_KEY_ENV, "test-key"); + let registry = build_registry(&AssistantConfig::default(), tools).unwrap(); + std::env::remove_var(OPENAI_API_KEY_ENV); + assert!(registry.contains_key(DEFAULT_MODEL_ID)); + } +} diff --git a/crates/sequins-assistant/src/lib.rs b/crates/sequins-assistant/src/lib.rs new file mode 100644 index 00000000..d1581d3c --- /dev/null +++ b/crates/sequins-assistant/src/lib.rs @@ -0,0 +1,25 @@ +//! In-engine AI assistant for Sequins. +//! +//! A tool-injecting Rig [`CompletionModel`](rig::completion::CompletionModel) that runs an +//! agentic loop **in-process** over a `DataFusionBackend` — exploring telemetry and emitting +//! SeQL — plus a Model Context Protocol (MCP) server exposing the same tools to +//! bring-your-own-model clients. Both surfaces share one operation layer ([`tools::ops`]). +//! +//! See the crate design plan for the full architecture (opaque model/tools axes, the +//! `/v1/chat/completions` OpenAI-compatible endpoint, and how it mounts into the daemon). + +pub mod config; +pub mod mcp; +pub mod model; +pub mod responses; +pub mod serve; +pub mod tools; + +pub use config::{ + build_backing_model, build_registry, AssistantConfig, BackingModel, ModelConfig, ModelRegistry, +}; +pub use mcp::{mcp_router, mcp_service, SequinsMcpServer}; +pub use model::{AgentEvent, SequinsAssistantModel}; +pub use responses::{responses_router, Assistant, ChatEvent}; +pub use serve::completion_model_router; +pub use tools::{OpError, Tools}; diff --git a/crates/sequins-assistant/src/mcp.rs b/crates/sequins-assistant/src/mcp.rs new file mode 100644 index 00000000..8d3d42b1 --- /dev/null +++ b/crates/sequins-assistant/src/mcp.rs @@ -0,0 +1,133 @@ +//! MCP server surface — exposes the **same** [`crate::tools`] operation layer over +//! the Model Context Protocol (streamable HTTP), so bring-your-own-model clients +//! (Claude Desktop, Cursor, …) can drive the Sequins tools with their own model. +//! +//! Tool metadata and dispatch both come from [`crate::tools::registry`], so the MCP +//! surface can never drift from what the in-process Rig agent exposes. + +use std::sync::Arc; + +use rmcp::handler::server::ServerHandler; +use rmcp::model::{ + CallToolRequestParams, CallToolResult, Content, InitializeResult, ListToolsResult, + PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool, +}; +use rmcp::service::{RequestContext, RoleServer}; +use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; +use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; +use rmcp::ErrorData as McpError; + +use crate::tools::{registry, Tools}; + +/// An MCP [`ServerHandler`] backed by the Sequins tool operation layer. +#[derive(Clone)] +pub struct SequinsMcpServer { + tools: Tools, +} + +impl SequinsMcpServer { + /// Build the MCP handler over the given tools. + pub fn new(tools: Tools) -> Self { + Self { tools } + } +} + +impl ServerHandler for SequinsMcpServer { + fn get_info(&self) -> ServerInfo { + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) + .with_instructions( + "Sequins telemetry tools: explore signal tables (spans, logs, metrics, profiles) and \ + run read-only SQL or SeQL over your observability data.", + ) + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + let tools = registry::specs() + .into_iter() + .map(|spec| { + let schema = spec.parameters.as_object().cloned().unwrap_or_default(); + Tool::new(spec.name, spec.description, Arc::new(schema)) + }) + .collect(); + Ok(ListToolsResult::with_all_items(tools)) + } + + async fn call_tool( + &self, + request: CallToolRequestParams, + _context: RequestContext, + ) -> Result { + let name = request.name.to_string(); + let args = request + .arguments + .map(serde_json::Value::Object) + .unwrap_or(serde_json::Value::Null); + + // A tool-level failure is returned as a readable error result (not a + // protocol error), so the caller's model sees the message and can retry. + match registry::invoke(&self.tools, &name, args).await { + Ok(text) => Ok(CallToolResult::success(vec![Content::text(text)])), + Err(message) => Ok(CallToolResult::error(vec![Content::text(message)])), + } + } +} + +/// The MCP streamable-HTTP tower service over the Sequins tools. Mount it into an +/// HTTP server (the daemon nests it under a path); it handles the MCP protocol. +pub fn mcp_service(tools: Tools) -> StreamableHttpService { + StreamableHttpService::new( + move || Ok(SequinsMcpServer::new(tools.clone())), + Arc::new(LocalSessionManager::default()), + StreamableHttpServerConfig::default(), + ) +} + +/// An axum router serving the MCP endpoint under `/mcp`. +pub fn mcp_router(tools: Tools) -> axum::Router { + axum::Router::new().nest_service("/mcp", mcp_service(tools)) +} + +#[cfg(test)] +mod tests { + use super::*; + use sequins_datafusion_backend::DataFusionBackend; + use sequins_storage::test_fixtures::{make_test_otlp_traces, TestStorageBuilder}; + use sequins_traits::OtlpIngest; + + async fn seeded_server() -> (SequinsMcpServer, tempfile::TempDir) { + let (storage, temp) = TestStorageBuilder::new().build().await; + storage + .ingest_traces(make_test_otlp_traces(1, 4)) + .await + .unwrap(); + let backend = Arc::new(DataFusionBackend::new(Arc::new(storage))); + (SequinsMcpServer::new(Tools::new(backend)), temp) + } + + #[test] + fn tools_list_matches_registry() { + // The MCP tool list is built from the same registry the agent uses. + let names: Vec<&str> = registry::specs().iter().map(|s| s.name).collect(); + assert!(names.contains(&"run_sql")); + assert!(names.contains(&"run_seql")); + assert_eq!(names.len(), registry::TOOL_NAMES.len()); + } + + #[tokio::test] + async fn call_tool_run_sql_hits_ops() { + let (server, _t) = seeded_server().await; + let mut args = serde_json::Map::new(); + args.insert( + "sql".to_string(), + serde_json::Value::String("SELECT count(*) AS c FROM spans".to_string()), + ); + let result = registry::invoke(&server.tools, "run_sql", serde_json::Value::Object(args)) + .await + .unwrap(); + assert!(result.contains("row(s)")); + } +} diff --git a/crates/sequins-assistant/src/model.rs b/crates/sequins-assistant/src/model.rs new file mode 100644 index 00000000..cc9e4aae --- /dev/null +++ b/crates/sequins-assistant/src/model.rs @@ -0,0 +1,398 @@ +//! [`SequinsAssistantModel`] — a tool-injecting middleware [`CompletionModel`]. +//! +//! It wraps a real *backing* model and, on every request, injects our in-process +//! tool set + SeQL grounding, then runs the agentic loop **in-process**: +//! +//! - the backing model calls one of **our** tools → we execute it against DataFusion, +//! append the result, and loop; +//! - the backing model calls one of the **caller's** tools (or returns text) → we hand +//! the response straight back for the caller's own agent to run. +//! +//! Because it *is* a `CompletionModel`, it drops into any Rig `Agent` and is served +//! over the OpenAI-compatible endpoint by [`crate::serve`]. Its own tool calls are +//! stripped from returned responses so a caller only ever sees its own tools. + +use rig::completion::{ + CompletionError, CompletionModel, CompletionRequest, CompletionResponse, GetTokenUsage, Usage, +}; +use rig::message::{ + AssistantContent, Message, Text, ToolCall, ToolResult, ToolResultContent, UserContent, +}; +use rig::streaming::{RawStreamingChoice, RawStreamingToolCall, StreamingCompletionResponse}; +use rig::OneOrMany; +use serde::{Deserialize, Serialize}; + +use crate::tools::{registry, Tools}; + +/// Default cap on in-process tool-call rounds before we force a final text answer. +const DEFAULT_MAX_TOOL_TURNS: usize = 16; + +/// A tool-injecting middleware model over a backing [`CompletionModel`] `B`. +#[derive(Clone)] +pub struct SequinsAssistantModel { + backing: B, + tools: Tools, + grounding: std::sync::Arc, + max_tool_turns: usize, +} + +impl SequinsAssistantModel { + /// Wrap `backing` with the Sequins tool set over `tools`. + pub fn new(backing: B, tools: Tools) -> Self { + Self { + backing, + tools, + grounding: std::sync::Arc::from(default_grounding()), + max_tool_turns: DEFAULT_MAX_TOOL_TURNS, + } + } + + /// Override the SeQL system grounding prepended to every request. + pub fn with_grounding(mut self, grounding: impl Into) -> Self { + self.grounding = std::sync::Arc::from(grounding.into()); + self + } + + /// Override the in-process tool-call round cap. + pub fn with_max_tool_turns(mut self, turns: usize) -> Self { + self.max_tool_turns = turns.max(1); + self + } + + /// Inject our grounding into the preamble and our tool defs into the request, + /// without dropping anything the caller supplied. + fn inject(&self, request: &mut CompletionRequest) { + // The caller's `model` is our *public* registry id (e.g. "default"), not the + // backing provider's model name. Clear it so the backing model uses the name + // it was built with — otherwise Rig forwards "default" as a model override and + // the real provider 404s with "model does not exist / no access". + request.model = None; + request.preamble = Some(match request.preamble.take() { + Some(p) if !p.trim().is_empty() => format!("{}\n\n---\n\n{}", self.grounding, p), + _ => self.grounding.to_string(), + }); + for def in registry::tool_definitions() { + if !request.tools.iter().any(|t| t.name == def.name) { + request.tools.push(def); + } + } + } + + /// The core agentic loop, emitting an [`AgentEvent`] for every step: interim + /// text, each **server** tool call *with its result* (executed in-process), and + /// each **client** tool call (foreign, for the caller to run). Returns the + /// terminal backing response (text + client tool calls, with our tools stripped) + /// so the chat-completions path can preserve provider usage. + /// + /// - `completion()` drives this with a no-op sink → server tools stay hidden. + /// - [`run_events`](Self::run_events) drives it with a channel → the Responses + /// endpoint surfaces every server tool call and result to the client. + async fn run_loop( + &self, + mut request: CompletionRequest, + mut emit: impl FnMut(AgentEvent), + ) -> Result, CompletionError> { + self.inject(&mut request); + + for _ in 0..self.max_tool_turns { + let response = self.backing.completion(request.clone()).await?; + + let mut our_calls: Vec = Vec::new(); + let mut has_foreign = false; + for content in response.choice.iter() { + if let AssistantContent::ToolCall(tc) = content { + if registry::is_ours(&tc.function.name) { + our_calls.push(tc.clone()); + } else { + has_foreign = true; + } + } + } + + // Terminal turn: a client tool call (or plain text) ends the loop. + if has_foreign || our_calls.is_empty() { + for content in response.choice.iter() { + match content { + AssistantContent::Text(t) if !t.text.is_empty() => { + emit(AgentEvent::Text(t.text.clone())); + } + AssistantContent::ToolCall(tc) if !registry::is_ours(&tc.function.name) => { + emit(AgentEvent::ClientTool { + id: tc.id.clone(), + name: tc.function.name.clone(), + arguments: tc.function.arguments.clone(), + }); + } + _ => {} + } + } + return Ok(strip_our_tool_calls(response)); + } + + // Otherwise surface any interim text, execute our tools, and continue. + for content in response.choice.iter() { + if let AssistantContent::Text(t) = content { + if !t.text.is_empty() { + emit(AgentEvent::Text(t.text.clone())); + } + } + } + let assistant_content: Vec = our_calls + .iter() + .cloned() + .map(AssistantContent::ToolCall) + .collect(); + request.chat_history.push(Message::Assistant { + id: response_id(&response), + content: OneOrMany::many(assistant_content) + .expect("our_calls is non-empty in this branch"), + }); + for call in &our_calls { + let rendered = registry::invoke( + &self.tools, + &call.function.name, + call.function.arguments.clone(), + ) + .await + .unwrap_or_else(|e| format!("Error: {e}")); + emit(AgentEvent::ServerTool { + id: call.id.clone(), + name: call.function.name.clone(), + arguments: call.function.arguments.clone(), + output: rendered.clone(), + }); + request.chat_history.push(Message::User { + content: OneOrMany::one(UserContent::ToolResult(ToolResult { + id: call.id.clone(), + call_id: call.call_id.clone(), + content: OneOrMany::one(ToolResultContent::Text(Text::new(rendered))), + })), + }); + } + } + + // Exhausted the tool-turn budget: one final call with no tools, forcing text. + request.tools.clear(); + let response = self.backing.completion(request).await?; + for content in response.choice.iter() { + if let AssistantContent::Text(t) = content { + if !t.text.is_empty() { + emit(AgentEvent::Text(t.text.clone())); + } + } + } + Ok(response) + } + + /// Run the agentic loop as a live [`AgentEvent`] stream — used by the Responses + /// endpoint to surface server-side tool activity to the client as it happens. + pub fn run_events( + &self, + request: CompletionRequest, + ) -> impl futures::Stream + Send + 'static + where + B: 'static, + { + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let this = self.clone(); + tokio::spawn(async move { + let events = tx.clone(); + let result = this + .run_loop(request, move |event| { + let _ = events.send(event); + }) + .await; + if let Err(err) = result { + let _ = tx.send(AgentEvent::Error(err.to_string())); + } + }); + tokio_stream::wrappers::UnboundedReceiverStream::new(rx) + } +} + +/// A step in the assistant's agentic loop, surfaced to Responses-API clients so +/// they can render server-executed tool activity they didn't drive themselves. +#[derive(Debug, Clone)] +pub enum AgentEvent { + /// Assistant text (interim or final). + Text(String), + /// A tool the **server** executed in-process, with its rendered result. + ServerTool { + id: String, + name: String, + arguments: serde_json::Value, + output: String, + }, + /// A tool the **client** must execute (foreign / caller-provided). + ClientTool { + id: String, + name: String, + arguments: serde_json::Value, + }, + /// The loop failed; carries the error message. + Error(String), +} + +impl CompletionModel for SequinsAssistantModel { + type Response = B::Response; + type StreamingResponse = MiddlewareStreamResponse; + type Client = (); + + /// Not constructible from a bare client — [`SequinsAssistantModel`] wraps an + /// already-built backing model, so use [`SequinsAssistantModel::new`] instead. + fn make(_client: &Self::Client, _model: impl Into) -> Self { + unreachable!("SequinsAssistantModel is built via `new`, not `CompletionModel::make`") + } + + async fn completion( + &self, + request: CompletionRequest, + ) -> Result, CompletionError> { + // The chat-completions path hides server-side tool activity (ignores events). + self.run_loop(request, |_| {}).await + } + + async fn stream( + &self, + request: CompletionRequest, + ) -> Result, CompletionError> { + // Run the full (non-streamed) middleware loop, then replay the final choice + // as streaming chunks. Token-by-token streaming is a later refinement. + let response = self.completion(request).await?; + let mut chunks: Vec, CompletionError>> = + Vec::new(); + for content in response.choice.iter() { + match content { + AssistantContent::Text(t) => { + chunks.push(Ok(RawStreamingChoice::Message(t.text.clone()))); + } + AssistantContent::ToolCall(tc) => { + chunks.push(Ok(RawStreamingChoice::ToolCall(RawStreamingToolCall::new( + tc.id.clone(), + tc.function.name.clone(), + tc.function.arguments.clone(), + )))); + } + _ => {} + } + } + let stream = futures::stream::iter(chunks); + Ok(StreamingCompletionResponse::stream(Box::pin(stream))) + } +} + +/// The streaming "raw response" for [`SequinsAssistantModel`]. Carries no provider +/// usage of its own (the middleware aggregates the backing model's rounds). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct MiddlewareStreamResponse; + +impl GetTokenUsage for MiddlewareStreamResponse { + fn token_usage(&self) -> Usage { + Usage::new() + } +} + +/// Return a copy of `response` with any of *our* tool calls removed from its choice, +/// so a caller only ever sees text and its own tool calls. +fn strip_our_tool_calls(response: CompletionResponse) -> CompletionResponse { + let kept: Vec = response + .choice + .iter() + .filter(|c| { + !matches!(c, AssistantContent::ToolCall(tc) if registry::is_ours(&tc.function.name)) + }) + .cloned() + .collect(); + let choice = OneOrMany::many(kept) + .unwrap_or_else(|_| OneOrMany::one(AssistantContent::Text(Text::new(String::new())))); + CompletionResponse { + choice, + usage: response.usage, + raw_response: response.raw_response, + message_id: response.message_id, + } +} + +/// Best-effort assistant message id (providers don't always supply one). +fn response_id(_response: &CompletionResponse) -> Option { + None +} + +/// The default SeQL system grounding. Includes a compact SeQL syntax cheatsheet with +/// worked examples so a backing model unfamiliar with this DSL writes valid queries on +/// the first try instead of looping on `validate_seql`. The daemon can override it with +/// a fuller prompt seeded from the SeQL spec. +fn default_grounding() -> String { + r#"You are the Sequins telemetry assistant. You explore an observability database +(spans, logs, metrics, profiles) and answer questions using **SeQL**, a pipeline query +language (NOT SQL). Do not write SQL in SeQL queries. + +## SeQL syntax (follow exactly) + +Every query begins with a signal and a mandatory time scope, then optional `|` stages: + + [ | ]* + +- Signals: `spans`, `logs`, `metrics`, `datapoints`, `histograms`, `profiles`, + `samples`, `resources`, `scopes`, `span_links`, `span_events`. +- Time scope (required, right after the signal): `last ` | `today` | `yesterday` | + `between(, )`. Durations are a single integer + unit + (`ms`,`s`,`m`,`h`,`d`) — e.g. `15m`, `1h`, `7d`. NO compound durations like `1h30m`. +- Stages (chained with `|`): + - `where ` — e.g. `where status == 2`, `where severity_number >= 9`, + `where attr.http_status_code >= 500`. Combine with `and`/`or`. + - `group by { } { }` — aggregation. Empty keys `{}` = one scalar + row. Aggregations: `count()`, `avg()`, `sum()`, `min`, `max`, `p50/p90/p99()`, + each aliased `as `; a conditional count is `count() where as `. + - For a **time series** (line chart over time), bucket time in the group keys with + `ts() bin as bucket`. + - `take ` — limit rows. `select ` — project columns. + +## Examples + +- Recent errored spans: `spans last 1h | where status == 2 | take 100` +- Total + error count (scalar): `spans last 1h | group by {} { count() as total, count() where status == 2 as errors }` +- Count by service: `spans last 1h | group by { service_name } { count() as n }` +- Spans per minute (timeseries):`spans last 15m | group by { ts() bin 1m as bucket } { count() as span_count }` +- Avg latency over time: `spans last 1h | group by { ts() bin 1m as bucket } { avg(duration_ns) as avg_ns }` +- Error logs per minute: `logs last 1h | where severity_number >= 17 | group by { ts() bin 1m as bucket } { count() as errors }` + +## Workflow + +Ground names with `list_tables` / `describe_schema` only if unsure. Write ONE SeQL query +using the rules above. If `validate_seql` fails, read `error.message`/`offset`, FIX the +query per the syntax above, and validate AT MOST once or twice more — do not loop. + +Client tools for showing results (call with the final SeQL `query`, a short `title`, and +an optional `chart_type` like `line`/`bar`/`stat`/`table`): +- `render_visualization` — show a chart INLINE in the chat. Use for a one-off answer. +- `add_to_dashboard` — SAVE a chart to a dashboard given a `dashboard` NAME (created if it + doesn't exist). Use when the user asks to add a chart to, or build/populate, a dashboard. + +The app re-runs the query to render it."# + .to_string() +} + +#[cfg(test)] +mod grounding_tests { + /// Every SeQL example embedded in [`super::default_grounding`] must parse, so we + /// never teach the backing model invalid syntax (the original cause of a + /// `validate_seql` retry loop). + #[test] + fn grounding_example_queries_parse() { + let examples = [ + "spans last 1h | where status == 2 | take 100", + "spans last 1h | group by {} { count() as total, count() where status == 2 as errors }", + "spans last 1h | group by { service_name } { count() as n }", + "spans last 15m | group by { ts() bin 1m as bucket } { count() as span_count }", + "spans last 1h | group by { ts() bin 1m as bucket } { avg(duration_ns) as avg_ns }", + "logs last 1h | where severity_number >= 17 | group by { ts() bin 1m as bucket } { count() as errors }", + ]; + for q in examples { + assert!( + seql_parser::parse(q).is_ok(), + "grounding example must parse: {q}" + ); + } + } +} diff --git a/crates/sequins-assistant/src/responses.rs b/crates/sequins-assistant/src/responses.rs new file mode 100644 index 00000000..cd375246 --- /dev/null +++ b/crates/sequins-assistant/src/responses.rs @@ -0,0 +1,1036 @@ +//! OpenAI **Responses API** endpoint (`POST /v1/responses`). +//! +//! Unlike Chat Completions, the Responses API streams a sequence of typed *output +//! items*. That lets us surface **server-executed** tool activity to the client: +//! each in-process tool call (`run_sql`, `column_profile`, …) appears as a resolved +//! item the client can render even though it didn't drive the tool. Client-provided +//! tools still appear as `function_call` items for the client to execute and answer +//! (via a `function_call_output` input item on the next turn). +//! +//! Server-executed tools use a custom `sequins.tool_result` item type — OpenAI only +//! defines dedicated item types for its own built-in tools (`web_search`, …), so a +//! generic server tool needs a custom type. First-party clients render it; others +//! ignore unknown item types. + +use std::convert::Infallible; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::extract::State; +use axum::http::StatusCode; +use axum::response::sse::{Event, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::post; +use axum::{Json, Router}; +use futures::{Stream, StreamExt}; +use indexmap::IndexMap; +use rig::completion::{CompletionModel, CompletionRequest, ToolDefinition}; +use rig::message::{ + AssistantContent, Message, Text, ToolCall, ToolFunction, ToolResult, ToolResultContent, + UserContent, +}; +use rig::OneOrMany; +use sequins_metadata::{AppStateStore, ConversationItem}; +use serde::Deserialize; +use serde_json::json; + +use crate::model::{AgentEvent, SequinsAssistantModel}; + +/// Router state: the model registry plus the optional app-state store that +/// persists conversations (when `store` is set on the request). +struct ResponsesState { + models: IndexMap>, + store: Option>, +} + +/// Router serving `POST /v1/responses` over the model registry, persisting +/// conversations to `store` (when provided) so history is queryable. +pub fn responses_router( + models: IndexMap>, + store: Option>, +) -> Router +where + B: CompletionModel + Send + Sync + 'static, +{ + Router::new() + .route("/v1/responses", post(create_response::)) + .with_state(Arc::new(ResponsesState { models, store })) +} + +async fn create_response( + State(state): State>>, + Json(req): Json, +) -> Response +where + B: CompletionModel + Send + Sync + 'static, +{ + let Some(model) = state.models.get(&req.model).cloned() else { + return model_not_found(&req.model).into_response(); + }; + + let response_id = new_id("resp"); + let store = state.store.clone(); + let do_store = req.store.unwrap_or(true) && store.is_some(); + + // Resolve the conversation this turn belongs to (existing) — a new one is + // created at persist time if none is referenced. + let conversation_id = resolve_conversation(store.as_deref(), &req).await; + + let mut completion_req = match build_completion_request(&req) { + Ok(r) => r, + Err(msg) => return bad_request(&msg).into_response(), + }; + // Server-side conversation state: prepend the prior visible exchange so the + // client only needs to send the new input (previous_response_id semantics). + if let (Some(store), Some(cid)) = (store.as_deref(), conversation_id.as_deref()) { + if let Some(conv) = store.get_conversation(cid).await { + prepend_history(&mut completion_req, &conv); + } + } + + let model_id = req.model.clone(); + let persist = do_store.then(|| PersistTurn { + store: store.clone().unwrap(), + conversation_id: conversation_id.clone(), + title: derive_title(&req), + input_items: input_conversation_items(&req), + response_id: response_id.clone(), + }); + + if req.stream { + stream_response( + model, + model_id, + completion_req, + response_id, + conversation_id, + persist, + ) + .into_response() + } else { + let events: Vec = model.run_events(completion_req).collect().await; + let conversation_id = match persist { + Some(p) => p.run(&events).await.or(conversation_id), + None => conversation_id, + }; + Json(build_response_object( + &model_id, + &response_id, + conversation_id.as_deref(), + &events, + )) + .into_response() + } +} + +/// Everything needed to persist a completed turn to the app-state store. +struct PersistTurn { + store: Arc, + conversation_id: Option, + title: Option, + input_items: Vec, + response_id: String, +} + +impl PersistTurn { + /// Persist the turn; returns the (possibly newly created) conversation id. + async fn run(self, events: &[AgentEvent]) -> Option { + let output_items: Vec = events + .iter() + .filter_map(|e| event_to_conversation_item(e, &self.response_id)) + .collect(); + match self + .store + .append_response( + self.conversation_id, + self.title, + self.input_items, + output_items, + self.response_id, + ) + .await + { + Ok(cid) => Some(cid), + Err(e) => { + tracing::warn!(error = %e, "failed to persist conversation turn"); + None + } + } + } +} + +/// Resolve the conversation for this request from an explicit `conversation` id or +/// a `previous_response_id`. +async fn resolve_conversation( + store: Option<&AppStateStore>, + req: &ResponsesRequest, +) -> Option { + if let Some(cid) = &req.conversation { + return Some(cid.clone()); + } + let (Some(store), Some(prev)) = (store, &req.previous_response_id) else { + return None; + }; + store.conversation_by_response(prev).await +} + +/// Prepend a conversation's prior **visible** exchange (user + assistant text) to +/// the request so the model has context. Internal tool items are omitted — the +/// model re-explores as needed, avoiding malformed tool-call/result pairing. +fn prepend_history(request: &mut CompletionRequest, conv: &sequins_metadata::Conversation) { + let mut prior: Vec = Vec::new(); + for item in &conv.items { + if item.item_type != "message" { + continue; + } + let text = item.text.clone().unwrap_or_default(); + match item.role.as_str() { + "assistant" => prior.push(Message::assistant(text)), + "system" | "developer" => prior.push(Message::System { content: text }), + _ => prior.push(Message::User { + content: OneOrMany::one(UserContent::Text(Text::new(text))), + }), + } + } + if prior.is_empty() { + return; + } + prior.extend(request.chat_history.iter().cloned()); + request.chat_history = + OneOrMany::many(prior).unwrap_or_else(|_| OneOrMany::one(Message::user(""))); +} + +/// Convert this turn's request input into conversation items (pre-turn, so no +/// `response_id`). +fn input_conversation_items(req: &ResponsesRequest) -> Vec { + let mut items = Vec::new(); + match &req.input { + ResponsesInput::Text(s) => items.push(text_item("user", "message", s.clone(), None)), + ResponsesInput::Items(list) => { + for item in list { + match item { + InputItem::Message { role, content } => { + items.push(text_item(role, "message", content.text(), None)); + } + InputItem::FunctionCall { + name, arguments, .. + } => items.push(ConversationItem { + tool_name: Some(name.clone()), + tool_arguments: Some(arguments.clone()), + ..text_item("assistant", "function_call", String::new(), None) + }), + InputItem::FunctionCallOutput { output, .. } => { + items.push(text_item( + "tool", + "function_call_output", + output.clone(), + None, + )); + } + InputItem::Other => {} + } + } + } + } + items +} + +/// Convert an `AgentEvent` into a persisted conversation item. +fn event_to_conversation_item(event: &AgentEvent, response_id: &str) -> Option { + match event { + AgentEvent::Text(text) => Some(text_item( + "assistant", + "message", + text.clone(), + Some(response_id), + )), + AgentEvent::ServerTool { + name, + arguments, + output, + .. + } => Some(ConversationItem { + tool_name: Some(name.clone()), + tool_arguments: Some(arguments.to_string()), + tool_output: Some(output.clone()), + ..text_item( + "tool", + "sequins.tool_result", + String::new(), + Some(response_id), + ) + }), + AgentEvent::ClientTool { + name, arguments, .. + } => Some(ConversationItem { + tool_name: Some(name.clone()), + tool_arguments: Some(arguments.to_string()), + ..text_item( + "assistant", + "function_call", + String::new(), + Some(response_id), + ) + }), + AgentEvent::Error(_) => None, + } +} + +fn text_item( + role: &str, + item_type: &str, + text: String, + response_id: Option<&str>, +) -> ConversationItem { + ConversationItem { + response_id: response_id.map(str::to_string), + position: 0, + role: role.to_string(), + item_type: item_type.to_string(), + text: (!text.is_empty()).then_some(text), + tool_name: None, + tool_arguments: None, + tool_output: None, + created_at_ns: 0, + } +} + +/// A short title for a new conversation, from the first user input line. +fn derive_title(req: &ResponsesRequest) -> Option { + let first = match &req.input { + ResponsesInput::Text(s) => Some(s.clone()), + ResponsesInput::Items(list) => list.iter().find_map(|i| match i { + InputItem::Message { role, content } if role != "system" && role != "developer" => { + Some(content.text()) + } + _ => None, + }), + }?; + let title: String = first.trim().chars().take(80).collect(); + (!title.is_empty()).then_some(title) +} + +/// Translate a Responses request into a Rig [`CompletionRequest`]. `instructions` +/// becomes the preamble (the middleware merges it with the SeQL grounding). +fn build_completion_request(req: &ResponsesRequest) -> Result { + let mut history: Vec = Vec::new(); + match &req.input { + ResponsesInput::Text(s) => history.push(Message::user(s.clone())), + ResponsesInput::Items(items) => { + for item in items { + match item { + InputItem::Message { role, content } => { + let text = content.text(); + match role.as_str() { + "assistant" => history.push(Message::assistant(text)), + "system" | "developer" => { + history.push(Message::System { content: text }) + } + _ => history.push(Message::User { + content: OneOrMany::one(UserContent::Text(Text::new(text))), + }), + } + } + InputItem::FunctionCall { + call_id, + name, + arguments, + } => history.push(Message::Assistant { + id: None, + content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new( + call_id.clone(), + ToolFunction::new(name.clone(), parse_arguments(arguments)), + ))), + }), + InputItem::FunctionCallOutput { call_id, output } => { + history.push(Message::User { + content: OneOrMany::one(UserContent::ToolResult(ToolResult { + id: call_id.clone(), + call_id: None, + content: OneOrMany::one(ToolResultContent::Text(Text::new( + output.clone(), + ))), + })), + }) + } + InputItem::Other => {} + } + } + } + } + + let chat_history = OneOrMany::many(history) + .map_err(|_| "input must contain at least one message".to_string())?; + let tools: Vec = req + .tools + .iter() + .filter_map(ResponsesTool::as_definition) + .collect(); + + Ok(CompletionRequest { + model: None, + preamble: req.instructions.clone(), + chat_history, + documents: Vec::new(), + tools, + temperature: None, + max_tokens: None, + tool_choice: None, + additional_params: None, + output_schema: None, + }) +} + +/// Stream the agentic loop as Responses-API SSE events, surfacing every server tool +/// call and result as its own output item. +#[allow(clippy::too_many_arguments)] +fn stream_response( + model: SequinsAssistantModel, + model_id: String, + request: CompletionRequest, + response_id: String, + conversation_id: Option, + persist: Option, +) -> Sse>> +where + B: CompletionModel + Send + Sync + 'static, +{ + let events = model.run_events(request); + let body = async_stream::stream! { + yield sse( + "response.created", + json!({ "type": "response.created", "response": response_object(&model_id, &response_id, conversation_id.as_deref(), "in_progress", &[], None) }), + ); + + let mut output: Vec = Vec::new(); + let mut collected: Vec = Vec::new(); + let mut failed: Option = None; + futures::pin_mut!(events); + while let Some(event) = events.next().await { + if let AgentEvent::Error(msg) = &event { + failed = Some(msg.clone()); + collected.push(event); + continue; + } + let Some(item) = event_to_item(&event, output.len()) else { collected.push(event); continue }; + let index = output.len(); + yield sse( + "response.output_item.added", + json!({ "type": "response.output_item.added", "output_index": index, "item": item }), + ); + if let AgentEvent::Text(text) = &event { + yield sse( + "response.output_text.delta", + json!({ "type": "response.output_text.delta", "item_id": item["id"], "output_index": index, "delta": text }), + ); + } + yield sse( + "response.output_item.done", + json!({ "type": "response.output_item.done", "output_index": index, "item": item }), + ); + output.push(item); + collected.push(event); + } + + // Persist the completed turn; the (possibly new) conversation id goes on the + // terminal event so the client can continue via `previous_response_id`. + let final_conversation = match persist { + Some(p) => p.run(&collected).await.or(conversation_id), + None => conversation_id, + }; + + if let Some(msg) = failed { + let resp = response_object(&model_id, &response_id, final_conversation.as_deref(), "failed", &output, Some(&msg)); + yield sse("response.failed", json!({ "type": "response.failed", "response": resp })); + } else { + let resp = response_object(&model_id, &response_id, final_conversation.as_deref(), "completed", &output, None); + yield sse("response.completed", json!({ "type": "response.completed", "response": resp })); + } + }; + Sse::new(body) +} + +fn build_response_object( + model_id: &str, + response_id: &str, + conversation_id: Option<&str>, + events: &[AgentEvent], +) -> serde_json::Value { + let mut output = Vec::new(); + let mut failed = None; + for event in events { + if let AgentEvent::Error(msg) = event { + failed = Some(msg.clone()); + continue; + } + if let Some(item) = event_to_item(event, output.len()) { + output.push(item); + } + } + let status = if failed.is_some() { + "failed" + } else { + "completed" + }; + response_object( + model_id, + response_id, + conversation_id, + status, + &output, + failed.as_deref(), + ) +} + +/// Map an [`AgentEvent`] to a Responses output item. +fn event_to_item(event: &AgentEvent, index: usize) -> Option { + match event { + AgentEvent::Text(text) => Some(json!({ + "type": "message", + "id": format!("msg_{index}"), + "role": "assistant", + "status": "completed", + "content": [{ "type": "output_text", "text": text }], + })), + // Server-executed: a self-contained, already-resolved item (call + result). + AgentEvent::ServerTool { + id, + name, + arguments, + output, + } => Some(json!({ + "type": "sequins.tool_result", + "id": id, + "name": name, + "arguments": arguments, + "output": output, + "status": "completed", + })), + // Client-provided: a function_call the client must execute and answer. + AgentEvent::ClientTool { + id, + name, + arguments, + } => Some(json!({ + "type": "function_call", + "id": format!("fc_{index}"), + "call_id": id, + "name": name, + "arguments": serde_json::to_string(arguments).unwrap_or_default(), + "status": "completed", + })), + AgentEvent::Error(_) => None, + } +} + +fn response_object( + model_id: &str, + response_id: &str, + conversation_id: Option<&str>, + status: &str, + output: &[serde_json::Value], + error: Option<&str>, +) -> serde_json::Value { + let mut obj = json!({ + "id": response_id, + "object": "response", + "created_at": unix_secs(), + "model": model_id, + "status": status, + "output": output, + "usage": { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0 }, + }); + if let Some(cid) = conversation_id { + obj["conversation"] = json!(cid); + } + if let Some(msg) = error { + obj["error"] = json!({ "message": msg }); + } + obj +} + +fn sse(event: &str, data: serde_json::Value) -> Result { + Ok(Event::default().event(event).data(data.to_string())) +} + +fn parse_arguments(arguments: &str) -> serde_json::Value { + serde_json::from_str(arguments).unwrap_or(serde_json::Value::Null) +} + +// --------------------------------------------------------------------------- +// Assistant façade — one AgentEvent-style stream for Local and Remote, used by +// the FFI so Swift has a single interface regardless of backend. +// --------------------------------------------------------------------------- + +/// A normalized chat event surfaced to native clients (the FFI). Server tool +/// activity is visible; `render_visualization` arrives as a `ClientTool`. +#[derive(Debug, Clone)] +pub enum ChatEvent { + /// Assistant text. + Text(String), + /// A tool the server executed in-process (name, JSON arguments, rendered output). + ServerTool { + name: String, + arguments: String, + output: String, + }, + /// A tool call for the client to handle (e.g. `render_visualization`). + ClientTool { name: String, arguments: String }, + /// The turn finished; carries ids for continuation/persistence. + Done { + response_id: String, + conversation_id: Option, + }, + /// The turn failed. + Error(String), +} + +/// A chat assistant that streams [`ChatEvent`]s, over Local (in-process model) or +/// Remote (the daemon's `/v1/responses`). Both are Rig `CompletionModel`s underneath. +pub enum Assistant { + /// In-process: run the middleware model directly, persisting to `store`. + Local { + model: SequinsAssistantModel, + store: Option>, + }, + /// Remote: POST the daemon's `/v1/responses` (base_url includes `/v1`). + Remote { + base_url: String, + token: Option, + http: reqwest::Client, + }, +} + +impl Assistant { + /// In-process assistant over `model`, persisting conversations to `store`. + pub fn local(model: SequinsAssistantModel, store: Option>) -> Self { + Assistant::Local { model, store } + } + + /// Remote assistant over the daemon's `/v1` at `base_url` (bearer `token`). + pub fn remote(base_url: impl Into, token: Option) -> Self { + Assistant::Remote { + base_url: base_url.into(), + token, + http: reqwest::Client::new(), + } + } +} + +impl Assistant { + /// Run a chat turn (an OpenAI Responses-shaped request) as a `ChatEvent` stream. + pub fn chat( + &self, + request: serde_json::Value, + ) -> std::pin::Pin + Send>> { + match self { + Assistant::Local { model, store } => { + Box::pin(local_chat(model.clone(), store.clone(), request)) + } + Assistant::Remote { + base_url, + token, + http, + } => Box::pin(remote_chat( + base_url.clone(), + token.clone(), + http.clone(), + request, + )), + } + } +} + +fn local_chat( + model: SequinsAssistantModel, + store: Option>, + request: serde_json::Value, +) -> impl Stream + Send { + async_stream::stream! { + let req: ResponsesRequest = match serde_json::from_value(request) { + Ok(r) => r, + Err(e) => { yield ChatEvent::Error(format!("invalid request: {e}")); return; } + }; + let response_id = new_id("resp"); + let conversation_id = resolve_conversation(store.as_deref(), &req).await; + let mut completion_req = match build_completion_request(&req) { + Ok(r) => r, + Err(m) => { yield ChatEvent::Error(m); return; } + }; + if let (Some(s), Some(cid)) = (store.as_deref(), conversation_id.as_deref()) { + if let Some(conv) = s.get_conversation(cid).await { + prepend_history(&mut completion_req, &conv); + } + } + let do_store = req.store.unwrap_or(true) && store.is_some(); + let persist = do_store.then(|| PersistTurn { + store: store.clone().unwrap(), + conversation_id: conversation_id.clone(), + title: derive_title(&req), + input_items: input_conversation_items(&req), + response_id: response_id.clone(), + }); + + let events = model.run_events(completion_req); + futures::pin_mut!(events); + let mut collected = Vec::new(); + while let Some(event) = events.next().await { + match &event { + AgentEvent::Text(t) => yield ChatEvent::Text(t.clone()), + AgentEvent::ServerTool { name, arguments, output, .. } => yield ChatEvent::ServerTool { + name: name.clone(), + arguments: arguments.to_string(), + output: output.clone(), + }, + AgentEvent::ClientTool { name, arguments, .. } => yield ChatEvent::ClientTool { + name: name.clone(), + arguments: arguments.to_string(), + }, + AgentEvent::Error(m) => yield ChatEvent::Error(m.clone()), + } + collected.push(event); + } + let final_conversation = match persist { + Some(p) => p.run(&collected).await.or(conversation_id), + None => conversation_id, + }; + yield ChatEvent::Done { response_id, conversation_id: final_conversation }; + } +} + +/// Map a single Responses `output` item (`message` / `sequins.tool_result` / +/// `function_call`) to a [`ChatEvent`]. Returns `None` for empty text or unknown +/// item types. Shared by the streaming relay and used to interpret persisted items. +fn output_item_to_event(item: &serde_json::Value) -> Option { + match item["type"].as_str() { + Some("message") => { + let text: String = item["content"] + .as_array() + .map(|parts| { + parts + .iter() + .filter_map(|p| p["text"].as_str()) + .collect::>() + .join("") + }) + .unwrap_or_default(); + (!text.is_empty()).then_some(ChatEvent::Text(text)) + } + Some("sequins.tool_result") => Some(ChatEvent::ServerTool { + name: item["name"].as_str().unwrap_or_default().to_string(), + arguments: item["arguments"].to_string(), + output: item["output"].as_str().unwrap_or_default().to_string(), + }), + Some("function_call") => Some(ChatEvent::ClientTool { + name: item["name"].as_str().unwrap_or_default().to_string(), + arguments: item["arguments"].as_str().unwrap_or_default().to_string(), + }), + _ => None, + } +} + +/// Continuation ids from a terminal `response.completed` / `response.failed` event's +/// nested `response` object. +fn done_from_response(resp: &serde_json::Value) -> ChatEvent { + ChatEvent::Done { + response_id: resp["id"].as_str().unwrap_or_default().to_string(), + conversation_id: resp["conversation"].as_str().map(str::to_string), + } +} + +/// Remote chat: a **streaming** POST to `/v1/responses` (`stream: true`), consuming the +/// daemon's Server-Sent Events and relaying each output item as a [`ChatEvent`] as it +/// arrives — so the remote path streams just like the local one. Terminal ids come from +/// the final `response.completed` / `response.failed` event. +fn remote_chat( + base_url: String, + token: Option, + http: reqwest::Client, + request: serde_json::Value, +) -> impl Stream + Send { + use eventsource_stream::Eventsource; + async_stream::stream! { + let url = format!("{}/responses", base_url.trim_end_matches('/')); + let mut body = request; + body["stream"] = json!(true); + + let mut builder = http.post(&url).json(&body); + if let Some(t) = &token { + builder = builder.bearer_auth(t); + } + let resp = match builder.send().await { + Ok(r) => match r.error_for_status() { + Ok(r) => r, + Err(e) => { yield ChatEvent::Error(format!("remote status: {e}")); return; } + }, + Err(e) => { yield ChatEvent::Error(format!("remote request: {e}")); return; } + }; + + let mut events = resp.bytes_stream().eventsource(); + let mut done_emitted = false; + while let Some(next) = events.next().await { + let event = match next { + Ok(e) => e, + Err(e) => { yield ChatEvent::Error(format!("remote stream: {e}")); break; } + }; + let data: serde_json::Value = match serde_json::from_str(&event.data) { + Ok(v) => v, + Err(_) => continue, + }; + match event.event.as_str() { + "response.output_item.done" => { + if let Some(ev) = output_item_to_event(&data["item"]) { + yield ev; + } + } + "response.completed" => { + yield done_from_response(&data["response"]); + done_emitted = true; + break; + } + "response.failed" => { + yield ChatEvent::Error( + data["response"]["error"]["message"] + .as_str() + .unwrap_or("remote error") + .to_string(), + ); + yield done_from_response(&data["response"]); + done_emitted = true; + break; + } + _ => {} + } + } + if !done_emitted { + // The stream closed without a terminal event — still emit a Done so callers + // (and the FFI stream) terminate cleanly. + yield ChatEvent::Done { response_id: String::new(), conversation_id: None }; + } + } +} + +// --------------------------------------------------------------------------- +// Request wire types (Responses API subset) +// --------------------------------------------------------------------------- + +#[derive(Debug, Deserialize)] +struct ResponsesRequest { + model: String, + input: ResponsesInput, + #[serde(default)] + instructions: Option, + #[serde(default)] + tools: Vec, + #[serde(default)] + stream: bool, + /// Persist this turn (default true). When false, nothing is written. + #[serde(default)] + store: Option, + /// Continue the conversation containing this prior response. + #[serde(default)] + previous_response_id: Option, + /// Explicit conversation id to append to. + #[serde(default)] + conversation: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +enum ResponsesInput { + Text(String), + Items(Vec), +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "type")] +enum InputItem { + #[serde(rename = "message")] + Message { + #[serde(default)] + role: String, + content: InputContent, + }, + #[serde(rename = "function_call")] + FunctionCall { + #[serde(default)] + call_id: String, + name: String, + #[serde(default)] + arguments: String, + }, + #[serde(rename = "function_call_output")] + FunctionCallOutput { + #[serde(default)] + call_id: String, + #[serde(default)] + output: String, + }, + /// Any other item type (reasoning, etc.) is ignored. + #[serde(other)] + Other, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +enum InputContent { + Text(String), + Parts(Vec), +} + +impl InputContent { + fn text(&self) -> String { + match self { + InputContent::Text(s) => s.clone(), + InputContent::Parts(parts) => parts + .iter() + .filter_map(|p| p.text.clone()) + .collect::>() + .join(""), + } + } +} + +#[derive(Debug, Deserialize)] +struct ContentPart { + #[serde(default)] + text: Option, +} + +#[derive(Debug, Deserialize)] +struct ResponsesTool { + #[serde(default)] + name: Option, + #[serde(default)] + description: Option, + #[serde(default)] + parameters: Option, +} + +impl ResponsesTool { + fn as_definition(&self) -> Option { + let name = self.name.clone()?; + Some(ToolDefinition { + name, + description: self.description.clone().unwrap_or_default(), + parameters: self.parameters.clone().unwrap_or_else(|| json!({})), + }) + } +} + +// --------------------------------------------------------------------------- +// Errors + small helpers +// --------------------------------------------------------------------------- + +fn model_not_found(model: &str) -> (StatusCode, Json) { + ( + StatusCode::NOT_FOUND, + Json(json!({ "error": { + "message": format!("The model '{model}' does not exist or is not configured."), + "type": "invalid_request_error", + "code": "model_not_found", + }})), + ) +} + +fn bad_request(message: &str) -> (StatusCode, Json) { + ( + StatusCode::BAD_REQUEST, + Json(json!({ "error": { "message": message, "type": "invalid_request_error" } })), + ) +} + +fn unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn new_id(prefix: &str) -> String { + format!( + "{prefix}_{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + ) +} + +#[cfg(test)] +mod stream_relay_tests { + use super::*; + + #[test] + fn maps_message_item_to_text() { + let item = json!({ + "type": "message", + "content": [{ "type": "output_text", "text": "hello " }, { "text": "world" }], + }); + match output_item_to_event(&item) { + Some(ChatEvent::Text(t)) => assert_eq!(t, "hello world"), + other => panic!("expected Text, got {other:?}"), + } + // Empty text yields nothing. + assert!(output_item_to_event(&json!({ "type": "message", "content": [] })).is_none()); + } + + #[test] + fn maps_server_and_client_tool_items() { + let server = json!({ + "type": "sequins.tool_result", + "name": "run_sql", + "arguments": { "sql": "SELECT 1" }, + "output": "1 row", + }); + match output_item_to_event(&server) { + Some(ChatEvent::ServerTool { + name, + arguments, + output, + }) => { + assert_eq!(name, "run_sql"); + assert_eq!(output, "1 row"); + assert!(arguments.contains("SELECT 1")); + } + other => panic!("expected ServerTool, got {other:?}"), + } + + let client = json!({ + "type": "function_call", + "name": "render_visualization", + "arguments": "{\"query\":\"spans last 1h\"}", + }); + match output_item_to_event(&client) { + Some(ChatEvent::ClientTool { name, arguments }) => { + assert_eq!(name, "render_visualization"); + assert_eq!(arguments, "{\"query\":\"spans last 1h\"}"); + } + other => panic!("expected ClientTool, got {other:?}"), + } + + assert!(output_item_to_event(&json!({ "type": "unknown" })).is_none()); + } + + #[test] + fn done_reads_ids_from_response() { + let resp = json!({ "id": "resp_1", "conversation": "conv_9" }); + match done_from_response(&resp) { + ChatEvent::Done { + response_id, + conversation_id, + } => { + assert_eq!(response_id, "resp_1"); + assert_eq!(conversation_id.as_deref(), Some("conv_9")); + } + other => panic!("expected Done, got {other:?}"), + } + // Missing conversation → None. + match done_from_response(&json!({ "id": "resp_2" })) { + ChatEvent::Done { + conversation_id, .. + } => assert!(conversation_id.is_none()), + other => panic!("expected Done, got {other:?}"), + } + } +} diff --git a/crates/sequins-assistant/src/serve.rs b/crates/sequins-assistant/src/serve.rs new file mode 100644 index 00000000..2de75651 --- /dev/null +++ b/crates/sequins-assistant/src/serve.rs @@ -0,0 +1,470 @@ +//! An OpenAI-compatible HTTP surface over a **named registry** of Rig +//! [`CompletionModel`]s — the generic "Rig proxying" server. +//! +//! - `GET /v1/models` lists the registry's model ids (empty when none configured). +//! - `POST /v1/chat/completions` resolves `model` in the registry and runs it, +//! streaming (SSE) or not. An unknown/absent model id returns the standard +//! OpenAI `model_not_found` error. +//! +//! This is domain-agnostic: it serves *any* `CompletionModel` (here a +//! [`SequinsAssistantModel`](crate::model::SequinsAssistantModel)) and is the far +//! side of the remote wire — our own app and any OpenAI client hit the same route. + +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::extract::State; +use axum::http::StatusCode; +use axum::response::sse::{Event, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use indexmap::IndexMap; +use rig::completion::{CompletionModel, CompletionRequest, CompletionResponse, ToolDefinition}; +use rig::message::{ + AssistantContent, Message, Text, ToolCall, ToolFunction, ToolResult, ToolResultContent, + UserContent, +}; +use rig::OneOrMany; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +/// Build the OpenAI-compatible router over a named registry of models. +/// +/// The registry order is preserved in `GET /v1/models`. An empty registry serves +/// an empty model list and answers every completion with `model_not_found`. +pub fn completion_model_router(models: IndexMap) -> Router +where + M: CompletionModel + Send + Sync + 'static, +{ + let state = Arc::new(AppState { models }); + Router::new() + .route("/v1/models", get(list_models::)) + .route("/v1/chat/completions", post(chat_completions::)) + .with_state(state) +} + +struct AppState { + models: IndexMap, +} + +// --------------------------------------------------------------------------- +// GET /v1/models +// --------------------------------------------------------------------------- + +async fn list_models(State(state): State>>) -> Json +where + M: CompletionModel + Send + Sync + 'static, +{ + let created = unix_secs(); + let data: Vec<_> = state + .models + .keys() + .map(|id| json!({ "id": id, "object": "model", "created": created, "owned_by": "sequins" })) + .collect(); + Json(json!({ "object": "list", "data": data })) +} + +// --------------------------------------------------------------------------- +// POST /v1/chat/completions +// --------------------------------------------------------------------------- + +async fn chat_completions( + State(state): State>>, + Json(req): Json, +) -> Response +where + M: CompletionModel + Send + Sync + 'static, +{ + tracing::debug!( + model = %req.model, + messages = req.messages.len(), + caller_tools = req.tools.len(), + stream = req.stream, + "assistant chat request" + ); + + let Some(model) = state.models.get(&req.model).cloned() else { + tracing::warn!(model = %req.model, "assistant chat: unknown model"); + return model_not_found(&req.model).into_response(); + }; + + let completion_req = match build_completion_request(&req) { + Ok(r) => r, + Err(msg) => { + tracing::warn!(model = %req.model, error = %msg, "assistant chat: bad request"); + return bad_request(&msg).into_response(); + } + }; + + let response = match model.completion(completion_req).await { + Ok(r) => r, + Err(e) => { + // Surface the upstream/tool-loop failure — otherwise a bad backing key + // or unreachable provider looks like a silent "failed to send" client-side. + tracing::warn!(model = %req.model, error = %e, "assistant chat: upstream error"); + return upstream_error(&e.to_string()).into_response(); + } + }; + + let (text, tool_calls) = split_choice(&response); + let model_id = req.model.clone(); + + if req.stream { + stream_response(model_id, text, tool_calls).into_response() + } else { + Json(build_chat_response(&model_id, text, tool_calls, &response)).into_response() + } +} + +/// Translate an OpenAI chat request into a Rig [`CompletionRequest`], merging all +/// `system` messages into the preamble and mapping the rest into chat history. +fn build_completion_request(req: &ChatRequest) -> Result { + let mut system_texts: Vec = Vec::new(); + let mut history: Vec = Vec::new(); + + for msg in &req.messages { + match msg.role.as_str() { + "system" | "developer" => { + if let Some(c) = msg.content_text() { + system_texts.push(c); + } + } + "user" => { + history.push(Message::User { + content: OneOrMany::one(UserContent::Text(Text::new( + msg.content_text().unwrap_or_default(), + ))), + }); + } + "assistant" => { + let mut parts: Vec = Vec::new(); + if let Some(c) = msg.content_text() { + if !c.is_empty() { + parts.push(AssistantContent::Text(Text::new(c))); + } + } + for tc in &msg.tool_calls { + parts.push(AssistantContent::ToolCall(ToolCall::new( + tc.id.clone(), + ToolFunction::new(tc.function.name.clone(), tc.function.parsed_arguments()), + ))); + } + if let Ok(content) = OneOrMany::many(parts) { + history.push(Message::Assistant { id: None, content }); + } + } + "tool" => { + let id = msg.tool_call_id.clone().unwrap_or_default(); + history.push(Message::User { + content: OneOrMany::one(UserContent::ToolResult(ToolResult { + id, + call_id: None, + content: OneOrMany::one(ToolResultContent::Text(Text::new( + msg.content_text().unwrap_or_default(), + ))), + })), + }); + } + other => return Err(format!("unsupported message role '{other}'")), + } + } + + let chat_history = OneOrMany::many(history) + .map_err(|_| "at least one non-system message is required".to_string())?; + + let tools: Vec = req + .tools + .iter() + .map(|t| ToolDefinition { + name: t.function.name.clone(), + description: t.function.description.clone().unwrap_or_default(), + parameters: t.function.parameters.clone().unwrap_or_else(|| json!({})), + }) + .collect(); + + let preamble = (!system_texts.is_empty()).then(|| system_texts.join("\n\n")); + + Ok(CompletionRequest { + // No model override: `req.model` is our public registry id, not the backing + // provider's model name. The backing model supplies its own name (the + // middleware also clears this defensively). + model: None, + preamble, + chat_history, + documents: Vec::new(), + tools, + temperature: req.temperature, + // Drop the client's max_tokens: it sizes output for our *public* model id, + // but we route to a different backing model with its own limit. Forwarding + // an oversized value 400s ("max_tokens is too large for this model"); letting + // the backing model use its default is correct for a remapping proxy. + max_tokens: None, + tool_choice: None, + additional_params: None, + output_schema: None, + }) +} + +/// Split a completion response's choice into concatenated text and tool calls. +fn split_choice(response: &CompletionResponse) -> (String, Vec) { + let mut text = String::new(); + let mut tool_calls = Vec::new(); + for content in response.choice.iter() { + match content { + AssistantContent::Text(t) => text.push_str(&t.text), + AssistantContent::ToolCall(tc) => tool_calls.push(ChatToolCall { + id: tc.id.clone(), + r#type: "function".to_string(), + function: ChatToolCallFunction { + name: tc.function.name.clone(), + arguments: tc.function.arguments.to_string(), + }, + }), + _ => {} + } + } + (text, tool_calls) +} + +fn build_chat_response( + model_id: &str, + text: String, + tool_calls: Vec, + response: &CompletionResponse, +) -> serde_json::Value { + let finish_reason = if tool_calls.is_empty() { + "stop" + } else { + "tool_calls" + }; + let mut message = json!({ "role": "assistant" }); + message["content"] = if text.is_empty() && !tool_calls.is_empty() { + serde_json::Value::Null + } else { + json!(text) + }; + if !tool_calls.is_empty() { + message["tool_calls"] = json!(tool_calls); + } + json!({ + "id": chat_id(), + "object": "chat.completion", + "created": unix_secs(), + "model": model_id, + "choices": [{ "index": 0, "message": message, "finish_reason": finish_reason }], + "usage": { + "prompt_tokens": response.usage.input_tokens, + "completion_tokens": response.usage.output_tokens, + "total_tokens": response.usage.total_tokens, + } + }) +} + +/// Stream the (already-computed) result as OpenAI `chat.completion.chunk` SSE +/// events: a role delta, the content/tool-call delta, a finish chunk, then `[DONE]`. +fn stream_response( + model_id: String, + text: String, + tool_calls: Vec, +) -> Sse>> { + let id = chat_id(); + let created = unix_secs(); + let finish_reason = if tool_calls.is_empty() { + "stop" + } else { + "tool_calls" + }; + + let base = |delta: serde_json::Value, finish: Option<&str>| { + json!({ + "id": id, + "object": "chat.completion.chunk", + "created": created, + "model": model_id, + "choices": [{ "index": 0, "delta": delta, "finish_reason": finish }], + }) + }; + + let mut chunks: Vec = vec![base(json!({ "role": "assistant" }), None)]; + if !text.is_empty() { + chunks.push(base(json!({ "content": text }), None)); + } + if !tool_calls.is_empty() { + let tc: Vec<_> = tool_calls + .iter() + .enumerate() + .map(|(i, c)| { + json!({ + "index": i, + "id": c.id, + "type": "function", + "function": { "name": c.function.name, "arguments": c.function.arguments } + }) + }) + .collect(); + chunks.push(base(json!({ "tool_calls": tc }), None)); + } + chunks.push(base(json!({}), Some(finish_reason))); + + let events = chunks + .into_iter() + .map(|c| Ok(Event::default().data(c.to_string()))) + .chain(std::iter::once(Ok(Event::default().data("[DONE]")))); + + Sse::new(futures::stream::iter(events.collect::>())) +} + +// --------------------------------------------------------------------------- +// OpenAI wire types (request side) +// --------------------------------------------------------------------------- + +#[derive(Debug, Deserialize)] +struct ChatRequest { + model: String, + #[serde(default)] + messages: Vec, + #[serde(default)] + tools: Vec, + #[serde(default)] + stream: bool, + #[serde(default)] + temperature: Option, + // `max_tokens` is intentionally not captured: we route to a backing model whose + // limit differs from the public id the client sized for, so we never forward it. +} + +#[derive(Debug, Deserialize)] +struct ChatMessage { + role: String, + #[serde(default)] + content: Option, + #[serde(default)] + tool_calls: Vec, + #[serde(default)] + tool_call_id: Option, +} + +impl ChatMessage { + /// Extract plain text from an OpenAI message `content`, which may be a string + /// or an array of `{type:"text", text}` parts. + fn content_text(&self) -> Option { + match &self.content { + Some(serde_json::Value::String(s)) => Some(s.clone()), + Some(serde_json::Value::Array(parts)) => { + let joined: String = parts + .iter() + .filter_map(|p| p.get("text").and_then(|t| t.as_str())) + .collect::>() + .join(""); + Some(joined) + } + _ => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ChatToolCall { + #[serde(default)] + id: String, + #[serde(default = "function_type", rename = "type")] + r#type: String, + function: ChatToolCallFunction, +} + +fn function_type() -> String { + "function".to_string() +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ChatToolCallFunction { + name: String, + /// OpenAI encodes arguments as a JSON *string*. + #[serde(default)] + arguments: String, +} + +impl ChatToolCallFunction { + fn parsed_arguments(&self) -> serde_json::Value { + serde_json::from_str(&self.arguments).unwrap_or(serde_json::Value::Null) + } +} + +#[derive(Debug, Deserialize)] +struct ChatTool { + function: ChatToolFunction, +} + +#[derive(Debug, Deserialize)] +struct ChatToolFunction { + name: String, + #[serde(default)] + description: Option, + #[serde(default)] + parameters: Option, +} + +// --------------------------------------------------------------------------- +// Errors (OpenAI-shaped) +// --------------------------------------------------------------------------- + +fn model_not_found(model: &str) -> (StatusCode, Json) { + error_body( + StatusCode::NOT_FOUND, + format!("The model '{model}' does not exist or is not configured."), + "invalid_request_error", + Some("model_not_found"), + ) +} + +fn bad_request(message: &str) -> (StatusCode, Json) { + error_body( + StatusCode::BAD_REQUEST, + message.to_string(), + "invalid_request_error", + None, + ) +} + +fn upstream_error(message: &str) -> (StatusCode, Json) { + error_body( + StatusCode::BAD_GATEWAY, + message.to_string(), + "api_error", + None, + ) +} + +fn error_body( + status: StatusCode, + message: String, + kind: &str, + code: Option<&str>, +) -> (StatusCode, Json) { + ( + status, + Json(json!({ "error": { "message": message, "type": kind, "code": code } })), + ) +} + +// --------------------------------------------------------------------------- +// Small helpers +// --------------------------------------------------------------------------- + +fn unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn chat_id() -> String { + format!( + "chatcmpl-{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + ) +} diff --git a/crates/sequins-assistant/src/tools/mod.rs b/crates/sequins-assistant/src/tools/mod.rs new file mode 100644 index 00000000..479746d4 --- /dev/null +++ b/crates/sequins-assistant/src/tools/mod.rs @@ -0,0 +1,8 @@ +//! The assistant's tool set: a shared operation layer ([`ops`]) exposed through +//! two adapters — Rig tools for the in-process agent and MCP tools for external, +//! bring-your-own-model clients. + +pub mod ops; +pub mod registry; + +pub use ops::{OpError, Tools}; diff --git a/crates/sequins-assistant/src/tools/ops.rs b/crates/sequins-assistant/src/tools/ops.rs new file mode 100644 index 00000000..d7adcff2 --- /dev/null +++ b/crates/sequins-assistant/src/tools/ops.rs @@ -0,0 +1,660 @@ +//! The assistant's tool **operation layer** — one implementation of every tool, +//! shared by both the Rig agent adapter and the MCP server adapter. +//! +//! Each operation takes a typed args struct (deriving [`serde`] + [`schemars::JsonSchema`] +//! so the same definition drives both the Rig `ToolDefinition` and the MCP tool schema) +//! and returns an LLM-legible `String`. Two lanes, per the design: +//! +//! - **explore** (`list_tables`, `describe_schema`, `column_profile`, `time_range`, +//! `sample`, `explain`, `run_sql`) — direct DataFusion over the backend's +//! [`SessionContext`], so the agent can understand the data before writing a query. +//! These are domain-agnostic (later extractable as `datafusion-assistant`). +//! - **present** (`validate_seql`, `run_seql`) — the SeQL query path, so the agent's +//! final answer is a SeQL string the app re-executes through its normal render path. +//! +//! `run_sql`/`explain` are **read-only**: DDL, DML and multi-statement scripts are +//! rejected via [`SQLOptions`], so ad-hoc SQL can scan the signal tables but never +//! mutate storage or pollute the shared query context. + +use std::sync::Arc; + +use arrow::record_batch::RecordBatch; +use datafusion::execution::context::SQLOptions; +use datafusion::prelude::SessionContext; +use futures::StreamExt; +use schemars::JsonSchema; +use sequins_arrow_schema::SignalType; +use sequins_datafusion_backend::{hot_signal_tables, hot_signal_type_for_table, DataFusionBackend}; +use sequins_flight::{decode_metadata, ipc_to_batch, SeqlMetadata}; +use sequins_traits::QueryApi; +use serde::{Deserialize, Serialize}; + +/// Default number of rows returned by `sample` and rendered by `run_sql`/`run_seql`. +const DEFAULT_ROWS: usize = 10; +/// Hard cap on rows any single tool will render, to keep tool output token-bounded. +const MAX_ROWS: usize = 100; +/// Default number of most-frequent values returned by `column_profile`. +const DEFAULT_TOP_K: usize = 10; + +/// Errors surfaced by the tool operation layer. Rendered into the tool's string +/// result by the adapters (the model sees the message and can correct itself). +#[derive(Debug, thiserror::Error)] +pub enum OpError { + #[error("unknown table '{table}' — known tables: {known}")] + UnknownTable { table: String, known: String }, + #[error("unknown column '{column}' in table '{table}'")] + UnknownColumn { column: String, table: String }, + #[error("query error: {0}")] + Query(#[from] sequins_traits::QueryError), + #[error("sql error: {0}")] + DataFusion(#[from] datafusion::error::DataFusionError), + #[error("arrow error: {0}")] + Arrow(#[from] arrow::error::ArrowError), +} + +// --------------------------------------------------------------------------- +// Args — one struct per tool. `deny_unknown_fields` keeps model mistakes loud. +// --------------------------------------------------------------------------- + +/// Arguments for `list_tables` (none). +#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ListTablesArgs {} + +/// Arguments for `describe_schema`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct DescribeSchemaArgs { + /// Signal table to describe, e.g. `spans`, `logs`, `datapoints`. + pub table: String, +} + +/// Arguments for `column_profile`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ColumnProfileArgs { + /// Signal table containing the column. + pub table: String, + /// Column to profile. + pub column: String, + /// How many most-frequent values to list (default 10). + #[serde(default)] + pub top_k: Option, +} + +/// Arguments for `time_range`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct TimeRangeArgs { + /// Signal table whose time span to report. + pub table: String, +} + +/// Arguments for `sample`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct SampleArgs { + /// Signal table to sample rows from. + pub table: String, + /// Number of rows to return (default 10, max 100). + #[serde(default)] + pub limit: Option, +} + +/// Arguments for `explain`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ExplainArgs { + /// A read-only SQL `SELECT` whose optimized logical plan to show. + pub sql: String, +} + +/// Arguments for `run_sql`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct RunSqlArgs { + /// A read-only SQL `SELECT` over the signal tables. DDL/DML is rejected. + pub sql: String, + /// Max rows to return (default 10, max 100). + #[serde(default)] + pub limit: Option, +} + +/// Arguments for `validate_seql`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ValidateSeqlArgs { + /// The SeQL query string to parse-check. + pub query: String, +} + +/// Arguments for `run_seql`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct RunSeqlArgs { + /// The SeQL query string to execute. + pub query: String, + /// How many sample result rows to include (default 10, max 100). + #[serde(default)] + pub sample_rows: Option, +} + +// --------------------------------------------------------------------------- +// Tools — holds the backend; every op is a method returning rendered text. +// --------------------------------------------------------------------------- + +/// The shared tool operation layer over a [`DataFusionBackend`]. +#[derive(Clone)] +pub struct Tools { + backend: Arc, +} + +impl Tools { + /// Build the tool layer over an existing backend. + pub fn new(backend: Arc) -> Self { + Self { backend } + } + + /// The backend these tools operate over. + pub fn backend(&self) -> &Arc { + &self.backend + } + + async fn ctx(&self) -> Result { + Ok(self.backend.session().await?) + } + + /// List the signal tables the assistant can query, with their time column. + pub async fn list_tables(&self, _args: ListTablesArgs) -> Result { + let mut out = String::from("Signal tables (query with SeQL or read-only SQL):\n"); + for (name, signal) in hot_signal_tables() { + let time_col = signal.time_column().unwrap_or("(none)"); + out.push_str(&format!( + "- {name}: signal={}, time_column={time_col}\n", + signal.name() + )); + } + out.push_str("\nUse describe_schema(table) for columns."); + Ok(out) + } + + /// Describe a table's columns and Arrow types. + pub async fn describe_schema(&self, args: DescribeSchemaArgs) -> Result { + validate_table(&args.table)?; + let ctx = self.ctx().await?; + let df = ctx.table(&args.table).await?; + let schema = df.schema().as_arrow(); + let mut out = format!( + "Schema of `{}` ({} columns):\n", + args.table, + schema.fields().len() + ); + for f in schema.fields() { + out.push_str(&format!( + "- {}: {}{}\n", + f.name(), + f.data_type(), + if f.is_nullable() { " (nullable)" } else { "" } + )); + } + Ok(out) + } + + /// Profile a column: total/non-null/approx-distinct, min/max, and top-k values. + pub async fn column_profile(&self, args: ColumnProfileArgs) -> Result { + validate_table(&args.table)?; + let ctx = self.ctx().await?; + self.validate_column(&ctx, &args.table, &args.column) + .await?; + + let t = quote_ident(&args.table); + let c = quote_ident(&args.column); + let top_k = args.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_ROWS); + + let mut out = format!("Profile of `{}`.`{}`:\n", args.table, args.column); + + // Row counts always work for any column type — kept separate from + // approx_distinct so an unsupported type (e.g. Float64, which DataFusion's + // HyperLogLog can't hash) doesn't hide the counts too. + let counts_sql = format!("SELECT count(*) AS total_rows, count({c}) AS non_null FROM {t}"); + match self.query_readonly(&ctx, &counts_sql, MAX_ROWS).await { + Ok(batches) => out.push_str(&render_batches(&batches)?), + Err(e) => out.push_str(&format!("(counts unavailable: {e})\n")), + } + + // Approximate distinct cardinality — best effort; unsupported for some types. + let distinct_sql = format!("SELECT approx_distinct({c}) AS approx_distinct FROM {t}"); + match self.query_readonly(&ctx, &distinct_sql, MAX_ROWS).await { + Ok(batches) => { + out.push_str("\nApprox distinct:\n"); + out.push_str(&render_batches(&batches)?); + } + Err(_) => out.push_str("\nApprox distinct: unavailable for this column type.\n"), + } + + let minmax_sql = format!("SELECT min({c}) AS min, max({c}) AS max FROM {t}"); + if let Ok(batches) = self.query_readonly(&ctx, &minmax_sql, MAX_ROWS).await { + out.push_str("\nRange:\n"); + out.push_str(&render_batches(&batches)?); + } + + let topk_sql = format!( + "SELECT {c} AS value, count(*) AS n FROM {t} GROUP BY {c} ORDER BY n DESC LIMIT {top_k}" + ); + match self.query_readonly(&ctx, &topk_sql, top_k).await { + Ok(batches) => { + out.push_str(&format!("\nTop {top_k} values:\n")); + out.push_str(&render_batches(&batches)?); + } + Err(e) => out.push_str(&format!("\n(top values unavailable: {e})\n")), + } + Ok(out) + } + + /// Report the min/max of a table's time column (nanoseconds since epoch). + pub async fn time_range(&self, args: TimeRangeArgs) -> Result { + let signal = validate_table(&args.table)?; + let Some(time_col) = signal.time_column() else { + return Ok(format!("Table `{}` has no time column.", args.table)); + }; + let ctx = self.ctx().await?; + let sql = format!( + "SELECT min({c}) AS earliest_ns, max({c}) AS latest_ns, count(*) AS rows FROM {t}", + c = quote_ident(time_col), + t = quote_ident(&args.table), + ); + let batches = self.query_readonly(&ctx, &sql, MAX_ROWS).await?; + Ok(format!( + "Time range of `{}` (column `{time_col}`, unix nanoseconds):\n{}", + args.table, + render_batches(&batches)? + )) + } + + /// Return up to `limit` sample rows from a table. + pub async fn sample(&self, args: SampleArgs) -> Result { + validate_table(&args.table)?; + let limit = args.limit.unwrap_or(DEFAULT_ROWS).clamp(1, MAX_ROWS); + let ctx = self.ctx().await?; + let sql = format!("SELECT * FROM {} LIMIT {limit}", quote_ident(&args.table)); + let batches = self.query_readonly(&ctx, &sql, limit).await?; + Ok(format!( + "Up to {limit} rows from `{}`:\n{}", + args.table, + render_batches(&batches)? + )) + } + + /// Show the optimized logical plan of a read-only SQL query (no execution). + pub async fn explain(&self, args: ExplainArgs) -> Result { + let ctx = self.ctx().await?; + let df = ctx.sql_with_options(&args.sql, read_only()).await?; + let plan = df.into_optimized_plan()?; + Ok(format!( + "Optimized logical plan:\n{}", + plan.display_indent() + )) + } + + /// Execute a read-only SQL query and render up to `limit` rows. + pub async fn run_sql(&self, args: RunSqlArgs) -> Result { + let limit = args.limit.unwrap_or(DEFAULT_ROWS).clamp(1, MAX_ROWS); + let ctx = self.ctx().await?; + let batches = self.query_readonly(&ctx, &args.sql, limit).await?; + let rows: usize = batches.iter().map(RecordBatch::num_rows).sum(); + Ok(format!( + "{rows} row(s) (capped at {limit}):\n{}", + render_batches(&batches)? + )) + } + + /// Parse-check a SeQL query, returning `{ok}` or `{ok:false, error:{...}}`. + pub async fn validate_seql(&self, args: ValidateSeqlArgs) -> Result { + let value = match seql_parser::parse(&args.query) { + Ok(_) => serde_json::json!({ "ok": true }), + Err(e) => serde_json::json!({ + "ok": false, + "error": { "message": e.message, "offset": e.offset, "length": e.length } + }), + }; + Ok(value.to_string()) + } + + /// Execute a SeQL query and summarize its result shape, columns, row count, + /// sample rows, and stats — the feedback loop for writing a good final query. + pub async fn run_seql(&self, args: RunSeqlArgs) -> Result { + let sample_rows = args.sample_rows.unwrap_or(DEFAULT_ROWS).clamp(1, MAX_ROWS); + let mut stream = self.backend.query(&args.query).await?; + + let mut shape: Option = None; + let mut columns: Vec = Vec::new(); + let mut sample: Vec = Vec::new(); + let mut sampled_rows = 0usize; + let mut total_rows = 0usize; + let mut stats_line = String::new(); + + while let Some(frame) = stream.next().await { + let fd = frame?; + let Some(meta) = decode_metadata(&fd.app_metadata) else { + continue; + }; + match meta { + // Only the primary result table (`table: None`) feeds the summary; + // auxiliary merge/navigate tables are skipped. + SeqlMetadata::Schema { + table: None, + shape: s, + columns: cols, + .. + } => { + shape = Some(s.as_str().to_string()); + columns = cols + .iter() + .map(|c| format!("{} ({:?}, {:?})", c.name, c.data_type, c.role)) + .collect(); + } + SeqlMetadata::Data { table: None } => { + if let Ok(batch) = ipc_to_batch(&fd.data_body) { + total_rows += batch.num_rows(); + if sampled_rows < sample_rows { + let take = (sample_rows - sampled_rows).min(batch.num_rows()); + sample.push(batch.slice(0, take)); + sampled_rows += take; + } + } + } + SeqlMetadata::Complete { stats } => { + stats_line = format!( + "rows_returned={}, rows_scanned={}, exec_us={}", + stats.rows_returned, stats.rows_scanned, stats.execution_time_us + ); + } + _ => {} + } + } + + let mut out = format!( + "SeQL executed.\nshape: {}\ncolumns:\n", + shape.as_deref().unwrap_or("(unknown)") + ); + for c in &columns { + out.push_str(&format!(" - {c}\n")); + } + out.push_str(&format!("rows returned: {total_rows}\n")); + if !stats_line.is_empty() { + out.push_str(&format!("stats: {stats_line}\n")); + } + if !sample.is_empty() { + out.push_str(&format!("sample (up to {sample_rows} rows):\n")); + out.push_str(&render_batches(&sample)?); + } + Ok(out) + } + + /// Run a read-only SQL statement and collect up to `limit` rows. + async fn query_readonly( + &self, + ctx: &SessionContext, + sql: &str, + limit: usize, + ) -> Result, OpError> { + let df = ctx.sql_with_options(sql, read_only()).await?; + let df = df.limit(0, Some(limit))?; + Ok(df.collect().await?) + } + + async fn validate_column( + &self, + ctx: &SessionContext, + table: &str, + column: &str, + ) -> Result<(), OpError> { + let df = ctx.table(table).await?; + if df.schema().as_arrow().field_with_name(column).is_err() { + return Err(OpError::UnknownColumn { + column: column.to_string(), + table: table.to_string(), + }); + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/// Read-only SQL: reject DDL, DML, and multi-statement scripts so ad-hoc SQL +/// can never mutate storage or the shared session context. +fn read_only() -> SQLOptions { + SQLOptions::new() + .with_allow_ddl(false) + .with_allow_dml(false) + .with_allow_statements(false) +} + +/// Validate a signal table name, returning its [`SignalType`]. +fn validate_table(table: &str) -> Result { + hot_signal_type_for_table(table).ok_or_else(|| OpError::UnknownTable { + table: table.to_string(), + known: hot_signal_tables() + .map(|(n, _)| n) + .collect::>() + .join(", "), + }) +} + +/// Quote a SQL identifier, escaping embedded double quotes. +fn quote_ident(ident: &str) -> String { + format!("\"{}\"", ident.replace('"', "\"\"")) +} + +/// Render record batches as an LLM-legible ASCII table. +fn render_batches(batches: &[RecordBatch]) -> Result { + if batches.iter().all(|b| b.num_rows() == 0) { + return Ok("(no rows)\n".to_string()); + } + Ok(format!( + "{}\n", + arrow::util::pretty::pretty_format_batches(batches)? + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use sequins_storage::test_fixtures::{ + make_test_otlp_metrics, make_test_otlp_traces, TestStorageBuilder, + }; + use sequins_traits::OtlpIngest; + + /// Build a backend seeded with `n_spans` test spans. + async fn seeded_tools(n_spans: usize) -> (Tools, tempfile::TempDir) { + let (storage, temp) = TestStorageBuilder::new().build().await; + storage + .ingest_traces(make_test_otlp_traces(1, n_spans)) + .await + .unwrap(); + let backend = Arc::new(DataFusionBackend::new(Arc::new(storage))); + (Tools::new(backend), temp) + } + + /// Profiling a `Float64` column (DataFusion's `approx_distinct` can't hash floats) + /// must still return the row counts, degrading only the distinct estimate. + #[tokio::test] + async fn column_profile_float_column_degrades_gracefully() { + let (storage, _t) = TestStorageBuilder::new().build().await; + storage + .ingest_metrics(make_test_otlp_metrics(1, 2, 4)) + .await + .unwrap(); + let tools = Tools::new(Arc::new(DataFusionBackend::new(Arc::new(storage)))); + + let out = tools + .column_profile(ColumnProfileArgs { + table: "datapoints".into(), + column: "value".into(), + top_k: Some(3), + }) + .await + .unwrap(); + + assert!(out.contains("total_rows"), "counts must survive: {out}"); + assert!( + out.contains("unavailable for this column type"), + "approx_distinct should degrade, not error: {out}" + ); + } + + #[tokio::test] + async fn list_tables_includes_spans() { + let (tools, _t) = seeded_tools(3).await; + let out = tools.list_tables(ListTablesArgs {}).await.unwrap(); + assert!(out.contains("spans")); + assert!(out.contains("logs")); + } + + #[tokio::test] + async fn describe_schema_spans() { + let (tools, _t) = seeded_tools(3).await; + let out = tools + .describe_schema(DescribeSchemaArgs { + table: "spans".into(), + }) + .await + .unwrap(); + assert!(out.contains("trace_id")); + assert!(out.contains("span_id")); + } + + #[tokio::test] + async fn describe_schema_unknown_table_errors() { + let (tools, _t) = seeded_tools(1).await; + let err = tools + .describe_schema(DescribeSchemaArgs { + table: "nope".into(), + }) + .await + .unwrap_err(); + assert!(matches!(err, OpError::UnknownTable { .. })); + } + + #[tokio::test] + async fn sample_returns_rows() { + let (tools, _t) = seeded_tools(5).await; + let out = tools + .sample(SampleArgs { + table: "spans".into(), + limit: Some(3), + }) + .await + .unwrap(); + assert!(out.contains("rows from `spans`")); + assert!(out.contains("trace_id")); + } + + #[tokio::test] + async fn time_range_reports_span() { + let (tools, _t) = seeded_tools(5).await; + let out = tools + .time_range(TimeRangeArgs { + table: "spans".into(), + }) + .await + .unwrap(); + assert!(out.contains("earliest_ns")); + assert!(out.contains("latest_ns")); + } + + #[tokio::test] + async fn column_profile_name() { + let (tools, _t) = seeded_tools(5).await; + let out = tools + .column_profile(ColumnProfileArgs { + table: "spans".into(), + column: "name".into(), + top_k: Some(3), + }) + .await + .unwrap(); + assert!(out.contains("total")); + assert!(out.contains("approx_distinct")); + } + + #[tokio::test] + async fn column_profile_unknown_column_errors() { + let (tools, _t) = seeded_tools(1).await; + let err = tools + .column_profile(ColumnProfileArgs { + table: "spans".into(), + column: "not_a_col".into(), + top_k: None, + }) + .await + .unwrap_err(); + assert!(matches!(err, OpError::UnknownColumn { .. })); + } + + #[tokio::test] + async fn run_sql_select_works() { + let (tools, _t) = seeded_tools(7).await; + let out = tools + .run_sql(RunSqlArgs { + sql: "SELECT count(*) AS c FROM spans".into(), + limit: None, + }) + .await + .unwrap(); + assert!(out.contains("row(s)")); + } + + #[tokio::test] + async fn run_sql_rejects_ddl() { + let (tools, _t) = seeded_tools(1).await; + let err = tools + .run_sql(RunSqlArgs { + sql: "CREATE TABLE evil (x INT)".into(), + limit: None, + }) + .await + .unwrap_err(); + assert!(matches!(err, OpError::DataFusion(_))); + } + + #[tokio::test] + async fn explain_shows_plan() { + let (tools, _t) = seeded_tools(3).await; + let out = tools + .explain(ExplainArgs { + sql: "SELECT name FROM spans".into(), + }) + .await + .unwrap(); + assert!(out.to_lowercase().contains("plan")); + } + + #[tokio::test] + async fn validate_seql_ok_and_err() { + let (tools, _t) = seeded_tools(1).await; + let ok = tools + .validate_seql(ValidateSeqlArgs { + query: "spans last 1h".into(), + }) + .await + .unwrap(); + assert!(ok.contains("\"ok\":true")); + + let bad = tools + .validate_seql(ValidateSeqlArgs { + query: "this is not seql @@@".into(), + }) + .await + .unwrap(); + assert!(bad.contains("\"ok\":false")); + } + + #[tokio::test] + async fn run_seql_summarizes_result() { + let (tools, _t) = seeded_tools(6).await; + let out = tools + .run_seql(RunSeqlArgs { + query: "spans last 1h LIMIT 5".into(), + sample_rows: Some(3), + }) + .await + .unwrap(); + assert!(out.contains("shape:")); + assert!(out.contains("columns:")); + } +} diff --git a/crates/sequins-assistant/src/tools/registry.rs b/crates/sequins-assistant/src/tools/registry.rs new file mode 100644 index 00000000..191cf02d --- /dev/null +++ b/crates/sequins-assistant/src/tools/registry.rs @@ -0,0 +1,145 @@ +//! The single tool registry — one list of `(name, description, JSON schema, invoker)` +//! for every assistant tool, shared by both adapters: +//! +//! - the **Rig** adapter turns [`tool_definitions`] into the model's tool set and +//! dispatches its calls through [`invoke`]; +//! - the **MCP** adapter lists the same [`specs`] and dispatches `tools/call` +//! through the same [`invoke`]. +//! +//! Keeping the schema and the dispatch in one place guarantees the two surfaces +//! never drift. + +use rig::completion::ToolDefinition; +use schemars::{schema_for, JsonSchema}; +use serde::de::DeserializeOwned; + +use super::ops::{ + ColumnProfileArgs, DescribeSchemaArgs, ExplainArgs, ListTablesArgs, RunSeqlArgs, RunSqlArgs, + SampleArgs, TimeRangeArgs, ValidateSeqlArgs, +}; +use super::{OpError, Tools}; + +/// A tool's model-facing metadata. +pub struct ToolSpec { + /// Tool name (must match what the model calls). + pub name: &'static str, + /// Human-readable description sent to the model. + pub description: &'static str, + /// JSON Schema for the tool's arguments. + pub parameters: serde_json::Value, +} + +/// The names of every tool this assistant executes in-process. Used by the +/// middleware model to tell *our* tool calls from a caller's own tools. +pub const TOOL_NAMES: &[&str] = &[ + "list_tables", + "describe_schema", + "column_profile", + "time_range", + "sample", + "explain", + "run_sql", + "validate_seql", + "run_seql", +]; + +/// Is `name` one of our in-process tools (vs. a caller-provided tool)? +pub fn is_ours(name: &str) -> bool { + TOOL_NAMES.contains(&name) +} + +fn schema() -> serde_json::Value { + serde_json::to_value(schema_for!(T)).unwrap_or_else(|_| serde_json::json!({ "type": "object" })) +} + +/// Every tool's spec, in a stable order. +pub fn specs() -> Vec { + vec![ + ToolSpec { + name: "list_tables", + description: "List the queryable signal tables (spans, logs, datapoints, …) and their time columns.", + parameters: schema::(), + }, + ToolSpec { + name: "describe_schema", + description: "Show a signal table's columns and Arrow types. Call before writing a query.", + parameters: schema::(), + }, + ToolSpec { + name: "column_profile", + description: "Profile a column: total/non-null counts, approximate distinct cardinality, min/max, and the most frequent values.", + parameters: schema::(), + }, + ToolSpec { + name: "time_range", + description: "Report the earliest and latest timestamps (unix nanoseconds) of a signal table.", + parameters: schema::(), + }, + ToolSpec { + name: "sample", + description: "Return a handful of sample rows from a signal table to see real values.", + parameters: schema::(), + }, + ToolSpec { + name: "explain", + description: "Show the optimized logical plan of a read-only SQL SELECT, without running it.", + parameters: schema::(), + }, + ToolSpec { + name: "run_sql", + description: "Run a read-only SQL SELECT over the signal tables (DDL/DML rejected). For ad-hoc exploration only.", + parameters: schema::(), + }, + ToolSpec { + name: "validate_seql", + description: "Parse-check a SeQL query. Returns {ok:true} or {ok:false, error:{message,offset,length}}.", + parameters: schema::(), + }, + ToolSpec { + name: "run_seql", + description: "Execute a SeQL query and summarize its result: shape, columns, row count, sample rows, and stats. The final answer must be a SeQL query.", + parameters: schema::(), + }, + ] +} + +/// Rig tool definitions for the model's request. +pub fn tool_definitions() -> Vec { + specs() + .into_iter() + .map(|s| ToolDefinition { + name: s.name.to_string(), + description: s.description.to_string(), + parameters: s.parameters, + }) + .collect() +} + +/// Dispatch a tool call by name, parsing `args` into the tool's typed arguments. +/// Returns the rendered result string, or an error message the model can read. +pub async fn invoke(tools: &Tools, name: &str, args: serde_json::Value) -> Result { + // Tools with no arguments may arrive as `null`; treat that as `{}`. + let args = if args.is_null() { + serde_json::json!({}) + } else { + args + }; + + fn parse(v: serde_json::Value) -> Result { + serde_json::from_value(v).map_err(|e| format!("invalid arguments: {e}")) + } + + let result: Result = match name { + "list_tables" => tools.list_tables(parse(args)?).await, + "describe_schema" => tools.describe_schema(parse(args)?).await, + "column_profile" => tools.column_profile(parse(args)?).await, + "time_range" => tools.time_range(parse(args)?).await, + "sample" => tools.sample(parse(args)?).await, + "explain" => tools.explain(parse(args)?).await, + "run_sql" => tools.run_sql(parse(args)?).await, + "validate_seql" => tools.validate_seql(parse(args)?).await, + "run_seql" => tools.run_seql(parse(args)?).await, + other => return Err(format!("unknown tool: {other}")), + }; + result.map_err(|e| e.to_string()) +} diff --git a/crates/sequins-assistant/tests/agent_loop.rs b/crates/sequins-assistant/tests/agent_loop.rs new file mode 100644 index 00000000..04cffd70 --- /dev/null +++ b/crates/sequins-assistant/tests/agent_loop.rs @@ -0,0 +1,510 @@ +//! Middleware-loop and OpenAI-endpoint tests using a **fake backing model** — no +//! network, no real LLM. They prove the tool-injecting loop routes our tools vs. a +//! caller's tools correctly, and that the `/v1` surface behaves per the OpenAI spec. + +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use indexmap::IndexMap; +use rig::completion::{ + CompletionError, CompletionModel, CompletionRequest, CompletionResponse, Usage, +}; +use rig::message::{AssistantContent, Message, Text, ToolCall, ToolFunction, UserContent}; +use rig::streaming::StreamingCompletionResponse; +use rig::OneOrMany; +use sequins_assistant::model::MiddlewareStreamResponse; +use sequins_assistant::{completion_model_router, responses_router, SequinsAssistantModel, Tools}; +use sequins_datafusion_backend::DataFusionBackend; +use sequins_storage::test_fixtures::{make_test_otlp_traces, TestStorageBuilder}; +use sequins_traits::OtlpIngest; +use serde_json::json; +use tower::ServiceExt; + +/// A scripted backing model: each `completion` pops the next canned choice and +/// records the request it received (so tests can assert on tool/preamble injection). +#[derive(Clone)] +struct FakeModel { + script: Arc>>>, + seen: Arc>>, +} + +impl FakeModel { + fn new(script: Vec>) -> Self { + Self { + script: Arc::new(Mutex::new(script.into())), + seen: Arc::new(Mutex::new(Vec::new())), + } + } +} + +impl CompletionModel for FakeModel { + type Response = (); + type StreamingResponse = MiddlewareStreamResponse; + type Client = (); + + fn make(_client: &Self::Client, _model: impl Into) -> Self { + unreachable!("test double is constructed directly") + } + + async fn completion( + &self, + request: CompletionRequest, + ) -> Result, CompletionError> { + self.seen.lock().unwrap().push(request); + let next = self + .script + .lock() + .unwrap() + .pop_front() + .unwrap_or_else(|| vec![AssistantContent::Text(Text::new("(exhausted)"))]); + Ok(CompletionResponse { + choice: OneOrMany::many(next).expect("non-empty canned choice"), + usage: Usage::new(), + raw_response: (), + message_id: None, + }) + } + + async fn stream( + &self, + _request: CompletionRequest, + ) -> Result, CompletionError> { + unreachable!("streaming path not exercised by these tests") + } +} + +fn tool_call(id: &str, name: &str, args: serde_json::Value) -> AssistantContent { + AssistantContent::ToolCall(ToolCall::new( + id.into(), + ToolFunction::new(name.into(), args), + )) +} + +fn user_request(prompt: &str) -> CompletionRequest { + CompletionRequest { + model: None, + preamble: None, + chat_history: OneOrMany::one(Message::user(prompt)), + documents: Vec::new(), + tools: Vec::new(), + temperature: None, + max_tokens: None, + tool_choice: None, + additional_params: None, + output_schema: None, + } +} + +fn text_of(response: &CompletionResponse) -> String { + response + .choice + .iter() + .filter_map(|c| match c { + AssistantContent::Text(t) => Some(t.text.clone()), + _ => None, + }) + .collect() +} + +fn has_tool(response_calls: &CompletionResponse<()>, name: &str) -> bool { + response_calls + .choice + .iter() + .any(|c| matches!(c, AssistantContent::ToolCall(tc) if tc.function.name == name)) +} + +fn request_has_tool_result(request: &CompletionRequest) -> bool { + request.chat_history.iter().any(|m| { + matches!(m, Message::User { content } + if content.iter().any(|u| matches!(u, UserContent::ToolResult(_)))) + }) +} + +async fn seeded_tools(n_spans: usize) -> (Tools, tempfile::TempDir) { + let (storage, temp) = TestStorageBuilder::new().build().await; + storage + .ingest_traces(make_test_otlp_traces(1, n_spans)) + .await + .unwrap(); + let backend = Arc::new(DataFusionBackend::new(Arc::new(storage))); + (Tools::new(backend), temp) +} + +#[tokio::test] +async fn our_tool_executes_then_loops_to_text() { + let (tools, _t) = seeded_tools(5).await; + let fake = FakeModel::new(vec![ + vec![tool_call( + "1", + "run_sql", + json!({ "sql": "SELECT count(*) AS c FROM spans" }), + )], + vec![AssistantContent::Text(Text::new("There are spans."))], + ]); + let model = SequinsAssistantModel::new(fake.clone(), tools); + + let response = model + .completion(user_request("how many spans?")) + .await + .unwrap(); + + assert!(text_of(&response).contains("There are spans.")); + + let seen = fake.seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "backing model called once per round"); + // First request had our tools + grounding injected. + assert!(seen[0].tools.iter().any(|t| t.name == "run_sql")); + assert!(seen[0].preamble.as_ref().unwrap().contains("Sequins")); + // Second request carried the executed tool's result. + assert!(request_has_tool_result(&seen[1])); +} + +#[tokio::test] +async fn caller_tool_is_handed_back_not_executed() { + let (tools, _t) = seeded_tools(1).await; + let fake = FakeModel::new(vec![vec![tool_call( + "x", + "render_visualization", + json!({ "query": "spans last 1h" }), + )]]); + let model = SequinsAssistantModel::new(fake.clone(), tools); + + let response = model.completion(user_request("chart it")).await.unwrap(); + + assert!(has_tool(&response, "render_visualization")); + assert_eq!(fake.seen.lock().unwrap().len(), 1, "no extra rounds"); +} + +#[tokio::test] +async fn mixed_turn_strips_our_tool_calls() { + let (tools, _t) = seeded_tools(1).await; + let fake = FakeModel::new(vec![vec![ + tool_call("a", "run_sql", json!({ "sql": "SELECT 1" })), + tool_call("b", "render_visualization", json!({ "query": "spans" })), + ]]); + let model = SequinsAssistantModel::new(fake, tools); + + let response = model.completion(user_request("chart")).await.unwrap(); + + assert!(has_tool(&response, "render_visualization")); + assert!( + !has_tool(&response, "run_sql"), + "our tool call must be stripped from the caller-facing response" + ); +} + +#[tokio::test] +async fn backing_never_sees_public_model_id_as_override() { + // Regression: the caller's `model` is our public registry id (e.g. "default"), + // not the backing provider's model name. If forwarded as a `request.model` + // override, a real provider 404s with "model does not exist / no access". + let (tools, _t) = seeded_tools(1).await; + let fake = FakeModel::new(vec![vec![AssistantContent::Text(Text::new("ok"))]]); + let model = SequinsAssistantModel::new(fake.clone(), tools); + + let mut req = user_request("hi"); + req.model = Some("default".into()); + let _ = model.completion(req).await.unwrap(); + + assert_eq!( + fake.seen.lock().unwrap()[0].model, + None, + "the public model id must be cleared before reaching the backing model" + ); +} + +#[tokio::test] +async fn text_only_passes_through() { + let (tools, _t) = seeded_tools(1).await; + let fake = FakeModel::new(vec![vec![AssistantContent::Text(Text::new("hello"))]]); + let model = SequinsAssistantModel::new(fake.clone(), tools); + + let response = model.completion(user_request("hi")).await.unwrap(); + + assert_eq!(text_of(&response), "hello"); + assert_eq!(fake.seen.lock().unwrap().len(), 1); +} + +async fn body_json(response: axum::response::Response) -> (StatusCode, serde_json::Value) { + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let value = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null); + (status, value) +} + +fn router_with_model(tools: Tools) -> axum::Router { + let model = SequinsAssistantModel::new( + FakeModel::new(vec![vec![AssistantContent::Text(Text::new("pong"))]]), + tools, + ); + let mut models = IndexMap::new(); + models.insert("sequins".to_string(), model); + completion_model_router(models) +} + +#[tokio::test] +async fn v1_models_lists_configured_models() { + let (tools, _t) = seeded_tools(1).await; + let app = router_with_model(tools); + + let resp = app + .oneshot(Request::get("/v1/models").body(Body::empty()).unwrap()) + .await + .unwrap(); + let (status, body) = body_json(resp).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"][0]["id"], "sequins"); +} + +#[tokio::test] +async fn v1_models_empty_when_none_configured() { + let app = completion_model_router(IndexMap::>::new()); + + let resp = app + .oneshot(Request::get("/v1/models").body(Body::empty()).unwrap()) + .await + .unwrap(); + let (status, body) = body_json(resp).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(body["data"].as_array().unwrap().len(), 0); +} + +#[tokio::test] +async fn unknown_model_returns_model_not_found() { + let (tools, _t) = seeded_tools(1).await; + let app = router_with_model(tools); + + let req = Request::post("/v1/chat/completions") + .header("content-type", "application/json") + .body(Body::from( + json!({ "model": "nope", "messages": [{ "role": "user", "content": "hi" }] }) + .to_string(), + )) + .unwrap(); + let resp = app.oneshot(req).await.unwrap(); + let (status, body) = body_json(resp).await; + + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(body["error"]["code"], "model_not_found"); +} + +#[tokio::test] +async fn chat_completion_returns_assistant_text() { + let (tools, _t) = seeded_tools(1).await; + let app = router_with_model(tools); + + let req = Request::post("/v1/chat/completions") + .header("content-type", "application/json") + .body(Body::from( + json!({ "model": "sequins", "messages": [{ "role": "user", "content": "ping" }] }) + .to_string(), + )) + .unwrap(); + let resp = app.oneshot(req).await.unwrap(); + let (status, body) = body_json(resp).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(body["choices"][0]["message"]["content"], "pong"); + assert_eq!(body["choices"][0]["finish_reason"], "stop"); +} + +fn responses_router_with_server_tool(tools: Tools) -> axum::Router { + // First round calls our run_sql tool; second round answers with text — so the + // loop executes a *server* tool the Responses stream should surface. + let model = SequinsAssistantModel::new( + FakeModel::new(vec![ + vec![tool_call( + "1", + "run_sql", + json!({ "sql": "SELECT count(*) AS c FROM spans" }), + )], + vec![AssistantContent::Text(Text::new("There are spans."))], + ]), + tools, + ); + let mut models = IndexMap::new(); + models.insert("default".to_string(), model); + responses_router(models, None) +} + +#[tokio::test] +async fn responses_surfaces_server_tool_items() { + let (tools, _t) = seeded_tools(3).await; + let app = responses_router_with_server_tool(tools); + + let req = Request::post("/v1/responses") + .header("content-type", "application/json") + .body(Body::from( + json!({ "model": "default", "input": "how many spans?" }).to_string(), + )) + .unwrap(); + let resp = app.oneshot(req).await.unwrap(); + let (status, body) = body_json(resp).await; + + assert_eq!(status, StatusCode::OK); + let output = body["output"].as_array().expect("output array"); + assert!( + output + .iter() + .any(|i| i["type"] == "sequins.tool_result" && i["name"] == "run_sql"), + "server tool result must be surfaced: {body}" + ); + assert!( + output.iter().any(|i| i["type"] == "message"), + "final message must be present: {body}" + ); +} + +#[tokio::test] +async fn responses_persist_and_continue_conversation() { + use sequins_assistant::responses_router; + use sequins_metadata::AppStateStore; + use std::sync::Arc; + + let (tools, _t) = seeded_tools(1).await; + let fake = FakeModel::new(vec![ + vec![AssistantContent::Text(Text::new("Nice to meet you, Sam."))], + vec![AssistantContent::Text(Text::new("Your name is Sam."))], + ]); + let model = SequinsAssistantModel::new(fake.clone(), tools); + let mut models = IndexMap::new(); + models.insert("default".to_string(), model); + + let store = Arc::new(AppStateStore::new( + Arc::new(object_store::memory::InMemory::new()), + "app_state", + )); + let app = responses_router(models, Some(store.clone())); + + // Turn 1 — new conversation. + let (s1, b1) = body_json( + app.clone() + .oneshot( + Request::post("/v1/responses") + .header("content-type", "application/json") + .body(Body::from( + json!({ "model": "default", "input": "My name is Sam." }).to_string(), + )) + .unwrap(), + ) + .await + .unwrap(), + ) + .await; + assert_eq!(s1, StatusCode::OK); + let rid1 = b1["id"].as_str().unwrap().to_string(); + let cid = b1["conversation"].as_str().unwrap().to_string(); + + // Turn 2 — continue via previous_response_id. + let (s2, b2) = body_json( + app.clone() + .oneshot( + Request::post("/v1/responses") + .header("content-type", "application/json") + .body(Body::from( + json!({ "model": "default", "input": "What is my name?", "previous_response_id": rid1 }) + .to_string(), + )) + .unwrap(), + ) + .await + .unwrap(), + ) + .await; + assert_eq!(s2, StatusCode::OK); + assert_eq!(b2["conversation"].as_str(), Some(cid.as_str())); + + // Both turns persisted (2 user inputs + 2 assistant messages). + let conv = store.get_conversation(&cid).await.unwrap(); + assert_eq!(conv.items.len(), 4, "conv items: {:?}", conv.items); + + // Turn 2's request to the model was prepended with the prior exchange. + let seen = fake.seen.lock().unwrap(); + let turn2 = &seen[1]; + let has_prior = turn2 + .chat_history + .iter() + .any(|m| matches!(m, Message::User { content } + if content.iter().any(|c| matches!(c, UserContent::Text(t) if t.text.contains("My name is Sam"))))); + assert!(has_prior, "turn 2 should include prior history"); +} + +#[tokio::test] +async fn responses_streams_created_tool_and_completed() { + let (tools, _t) = seeded_tools(3).await; + let app = responses_router_with_server_tool(tools); + + let req = Request::post("/v1/responses") + .header("content-type", "application/json") + .body(Body::from( + json!({ "model": "default", "input": "how many spans?", "stream": true }).to_string(), + )) + .unwrap(); + let resp = app.oneshot(req).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let sse = String::from_utf8(bytes.to_vec()).unwrap(); + + assert!(sse.contains("response.created"), "{sse}"); + assert!(sse.contains("sequins.tool_result"), "{sse}"); + assert!(sse.contains("response.completed"), "{sse}"); +} + +/// End-to-end: `Assistant::Remote` consumes the daemon's `/v1/responses` SSE stream +/// incrementally, relaying the server-executed tool and the assistant text as +/// `ChatEvent`s and finishing with `Done` — proving the remote path streams like local. +#[tokio::test] +async fn remote_assistant_streams_over_sse() { + use futures::StreamExt; + use sequins_assistant::{Assistant, ChatEvent}; + + let (tools, _t) = seeded_tools(3).await; + let app = responses_router_with_server_tool(tools); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let assistant = Assistant::::remote(format!("http://{addr}/v1"), None); + let request = json!({ "model": "default", "input": "how many spans?" }); + let mut stream = assistant.chat(request); + + let mut server_tools = 0; + let mut texts: Vec = Vec::new(); + let mut done = false; + while let Some(event) = stream.next().await { + match event { + ChatEvent::ServerTool { name, .. } => { + assert_eq!(name, "run_sql"); + server_tools += 1; + } + ChatEvent::Text(t) => texts.push(t), + ChatEvent::Done { .. } => { + done = true; + break; + } + ChatEvent::Error(e) => panic!("unexpected error: {e}"), + ChatEvent::ClientTool { .. } => {} + } + } + + assert_eq!( + server_tools, 1, + "should surface the server-executed run_sql tool" + ); + assert!( + texts.iter().any(|t| t.contains("spans")), + "should stream the assistant text, got {texts:?}" + ); + assert!(done, "should emit a terminal Done"); +} diff --git a/crates/sequins-client/Cargo.toml b/crates/sequins-client/Cargo.toml index 3ece3607..23b3976c 100644 --- a/crates/sequins-client/Cargo.toml +++ b/crates/sequins-client/Cargo.toml @@ -29,6 +29,8 @@ tokio = { workspace = true } tokio-stream = { workspace = true } futures = { workspace = true } async-trait = { workspace = true } +reqwest = { workspace = true } +sequins-metadata = { workspace = true } # Serialization serde = { workspace = true } diff --git a/crates/sequins-client/src/lib.rs b/crates/sequins-client/src/lib.rs index ea2da5c6..5a48e73e 100644 --- a/crates/sequins-client/src/lib.rs +++ b/crates/sequins-client/src/lib.rs @@ -5,7 +5,9 @@ //! Returns a `SeqlStream` of `FlightData` for the caller to process. use arrow_flight::flight_service_client::FlightServiceClient; -use arrow_flight::sql::{CommandStatementSubstraitPlan, ProstMessageExt, SubstraitPlan}; +use arrow_flight::sql::{ + CommandStatementQuery, CommandStatementSubstraitPlan, ProstMessageExt, SubstraitPlan, +}; use arrow_flight::{FlightDescriptor, Ticket}; use async_trait::async_trait; use datafusion::execution::context::SessionContext; @@ -29,6 +31,11 @@ pub struct RemoteClient { /// Optional bearer token sent as `authorization: Bearer ` on every /// request. `None` = no auth header (the default; a keyless server ignores it). token: Option, + /// Base URL of the Pro management API (e.g. `http://host:8081`), used for the + /// dashboard REST endpoints. `None` disables the remote dashboard interface. + management_url: Option, + /// HTTP client for the management REST endpoints (dashboards). + http: reqwest::Client, } impl RemoteClient { @@ -54,9 +61,18 @@ impl RemoteClient { endpoint, schema_ctx: Arc::new(schema_ctx), token, + management_url: None, + http: reqwest::Client::new(), }) } + /// Configure the Pro management API base URL (e.g. `http://host:8081`) so the + /// dashboard REST endpoints work. Without it, [`DashboardApi`] calls error. + pub fn with_management_url(mut self, url: Option) -> Self { + self.management_url = url.map(|u| u.trim_end_matches('/').to_string()); + self + } + /// Wrap `msg` in a request, adding the `authorization: Bearer ` header /// when a token is configured. fn authed(&self, msg: T) -> Result, QueryError> { @@ -90,6 +106,17 @@ impl RemoteClient { Self::new("http://localhost:4319") } + /// Execute a **read-only** plain SQL query over Flight SQL's standard + /// `CommandStatementQuery` path and return the resulting `SeqlStream`. + async fn execute_sql(&self, sql: String) -> Result { + let cmd = CommandStatementQuery { + query: sql, + transaction_id: None, + }; + self.get_flight_info_and_do_get(cmd.as_any().encode_to_vec()) + .await + } + /// Send Substrait plan bytes to the server via `DoGet` and return the /// resulting `SeqlStream`. /// @@ -99,13 +126,6 @@ impl RemoteClient { /// 2. Extract the ticket from the first endpoint. /// 3. Call `DoGet(ticket)` to open the streaming result. async fn execute_plan(&self, plan_bytes: Vec) -> Result { - // connect_lazy() must be called from an async context (needs a tokio reactor). - // execute_plan() is always called from an async context, so this is safe. - let channel = self.endpoint.clone().connect_lazy(); - let mut client = - FlightServiceClient::new(channel).max_decoding_message_size(64 * 1024 * 1024); - - // Step 1: GetFlightInfo → get ticket let cmd = CommandStatementSubstraitPlan { plan: Some(SubstraitPlan { plan: plan_bytes.clone().into(), @@ -113,7 +133,21 @@ impl RemoteClient { }), transaction_id: None, }; - let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec()); + self.get_flight_info_and_do_get(cmd.as_any().encode_to_vec()) + .await + } + + /// Shared Flight SQL round-trip: `GetFlightInfo(cmd)` → first endpoint ticket → + /// `DoGet(ticket)` → mapped `SeqlStream`. + async fn get_flight_info_and_do_get(&self, cmd_any: Vec) -> Result { + // connect_lazy() must be called from an async context (needs a tokio reactor). + // This is always called from an async context, so this is safe. + let channel = self.endpoint.clone().connect_lazy(); + let mut client = + FlightServiceClient::new(channel).max_decoding_message_size(64 * 1024 * 1024); + + // Step 1: GetFlightInfo → get ticket + let descriptor = FlightDescriptor::new_cmd(cmd_any); let info = client .get_flight_info(self.authed(descriptor)?) .await @@ -159,6 +193,10 @@ impl QueryApi for RemoteClient { let plan_bytes = compile(seql, &self.schema_ctx).await?; self.execute_plan(plan_bytes).await } + + async fn sql(&self, sql: &str) -> Result { + self.execute_sql(sql.to_string()).await + } } #[async_trait] @@ -168,6 +206,86 @@ impl QueryExec for RemoteClient { } } +// ---- Remote dashboards (REST over the management API) ---------------------- + +impl RemoteClient { + fn dashboards_url(&self, suffix: &str) -> sequins_metadata::Result { + let base = self.management_url.as_ref().ok_or_else(|| { + sequins_metadata::MetadataError::Other( + "remote management URL not configured".to_string(), + ) + })?; + Ok(format!("{base}/api/dashboards{suffix}")) + } + + fn bearer(&self, rb: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + match &self.token { + Some(t) => rb.bearer_auth(t), + None => rb, + } + } +} + +fn meta_err(e: E) -> sequins_metadata::MetadataError { + sequins_metadata::MetadataError::Other(e.to_string()) +} + +#[async_trait::async_trait] +impl sequins_metadata::DashboardApi for RemoteClient { + async fn list_dashboards(&self) -> sequins_metadata::Result> { + let url = self.dashboards_url("")?; + let resp = self + .bearer(self.http.get(&url)) + .send() + .await + .map_err(meta_err)? + .error_for_status() + .map_err(meta_err)?; + resp.json().await.map_err(meta_err) + } + + async fn get_dashboard( + &self, + id: &str, + ) -> sequins_metadata::Result> { + let url = self.dashboards_url(&format!("/{id}"))?; + let resp = self + .bearer(self.http.get(&url)) + .send() + .await + .map_err(meta_err)? + .error_for_status() + .map_err(meta_err)?; + resp.json().await.map_err(meta_err) + } + + async fn save_dashboard( + &self, + dashboard: sequins_metadata::Dashboard, + ) -> sequins_metadata::Result { + let url = self.dashboards_url("")?; + let resp = self + .bearer(self.http.post(&url).json(&dashboard)) + .send() + .await + .map_err(meta_err)? + .error_for_status() + .map_err(meta_err)?; + resp.json().await.map_err(meta_err) + } + + async fn delete_dashboard(&self, id: &str) -> sequins_metadata::Result<()> { + let url = self.dashboards_url(&format!("/{id}"))?; + self.bearer(self.http.delete(&url)) + .send() + .await + .map_err(meta_err)? + .error_for_status() + .map_err(meta_err)?; + Ok(()) + } +} + /// Errors from the remote client #[derive(Debug, thiserror::Error)] pub enum ClientError { diff --git a/crates/sequins-cold-tier/src/error.rs b/crates/sequins-cold-tier/src/error.rs index 77bf19f4..1fc4c03d 100644 --- a/crates/sequins-cold-tier/src/error.rs +++ b/crates/sequins-cold-tier/src/error.rs @@ -16,6 +16,12 @@ pub enum Error { #[error("Vortex error: {0}")] Vortex(String), + /// The batch's Arrow schema cannot be encoded to the cold format (e.g. a + /// `Map` column Vortex 0.76 doesn't support). This is PERMANENT for that batch — + /// retrying never helps — so callers should drop it rather than retain it forever. + #[error("Unsupported for cold storage: {0}")] + UnsupportedForCold(String), + #[error("Serialization error: {0}")] Serialization(String), @@ -38,4 +44,13 @@ pub enum Error { SeriesIndex(#[from] sequins_series_index::error::Error), } +impl Error { + /// True if this batch can never be written to cold (a permanent schema + /// incompatibility), so it should be dropped rather than retried — otherwise it + /// accumulates in the hot tier forever and eventually OOMs the process. + pub fn is_unsupported_for_cold(&self) -> bool { + matches!(self, Error::UnsupportedForCold(_)) + } +} + pub type Result = std::result::Result; diff --git a/crates/sequins-cold-tier/src/record_batch.rs b/crates/sequins-cold-tier/src/record_batch.rs index 657f8db2..c7dd5fd2 100644 --- a/crates/sequins-cold-tier/src/record_batch.rs +++ b/crates/sequins-cold-tier/src/record_batch.rs @@ -79,14 +79,26 @@ impl ColdTier { inner_strategy }; - // Get the Arrow schema to create the DType + // Convert the Arrow schema + batch to Vortex. `DType::from_arrow` *panics* + // (rather than returning an error) on Arrow types Vortex can't represent — + // notably the `Map` overflow-attributes column. A panic on + // a background flush worker unwinds the task and can leave shared runtime state + // wedged (starving unrelated work, e.g. app-state reads), so contain it here + // and surface a normal error: this batch simply isn't flushed to cold. let arrow_schema = batch.schema(); - let dtype = DType::from_arrow(arrow_schema); - - // Convert Arrow RecordBatch to Vortex Array - // The false parameter indicates not to preserve nullability - let vortex_array = ArrayRef::from_arrow(batch, false) - .map_err(|e| Error::Storage(format!("Failed to convert Arrow batch: {}", e)))?; + let (dtype, vortex_array) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let dtype = DType::from_arrow(arrow_schema); + let array = ArrayRef::from_arrow(batch, false)?; + Ok::<(DType, ArrayRef), vortex::error::VortexError>((dtype, array)) + })) + .map_err(|_| { + Error::UnsupportedForCold( + "Vortex cannot encode this batch's Arrow schema (unsupported type, \ + e.g. a Map column); batch not flushed to cold" + .to_string(), + ) + })? + .map_err(|e| Error::Storage(format!("Failed to convert Arrow batch: {}", e)))?; // Create a stream from the single array let stream = stream::once(async move { VortexResult::Ok(vortex_array) }); @@ -234,6 +246,39 @@ mod tests { ); } + /// A batch carrying a `Map` column (the shape of the + /// `_overflow_attrs` overflow-attributes column) must fail the cold write with a + /// normal `Err` — Vortex *panics* on that Arrow type, and an uncontained panic on + /// a flush worker can wedge the shared runtime. See `write_record_batch_at`. + #[tokio::test] + async fn test_unsupported_map_schema_returns_err_not_panic() { + use arrow::array::{Int64Array, LargeBinaryBuilder, MapBuilder, StringBuilder}; + + let mut map = MapBuilder::new(None, StringBuilder::new(), LargeBinaryBuilder::new()); + map.keys().append_value("k"); + map.values().append_value(b"cbor-bytes"); + map.append(true).unwrap(); + let map_array = map.finish(); + + let batch = RecordBatch::try_from_iter(vec![ + ("ts", Arc::new(Int64Array::from(vec![1i64])) as ArrayRef), + ("_overflow_attrs", Arc::new(map_array) as ArrayRef), + ]) + .unwrap(); + let schema = batch.schema(); + + let (cold, _tmp) = crate::test_helpers::create_test_cold_tier().await; + let result = cold + .write_record_batch_at(batch, schema, "spans/unsupported.vortex", None) + .await; + let err = result.expect_err("a Map column Vortex can't encode must return Err, not panic"); + assert!( + err.is_unsupported_for_cold(), + "must be the permanent UnsupportedForCold variant (so the hot tier drops \ + it instead of retaining → OOM), got {err:?}" + ); + } + #[test] fn test_sort_batch_with_nulls() { let schema = Arc::new(Schema::new(vec![Field::new("ts", DataType::Int64, true)])); diff --git a/crates/sequins-datafusion-backend/Cargo.toml b/crates/sequins-datafusion-backend/Cargo.toml index 0d5487a4..ce0a1078 100644 --- a/crates/sequins-datafusion-backend/Cargo.toml +++ b/crates/sequins-datafusion-backend/Cargo.toml @@ -21,6 +21,8 @@ sequins-types = { workspace = true } sequins-attribute-codec = { workspace = true, features = ["datafusion"] } sequins-live-query = { workspace = true } sequins-traits = { workspace = true } +sequins-metadata = { workspace = true } +serde_json = { workspace = true } # Arrow + DataFusion arrow = { workspace = true } diff --git a/crates/sequins-datafusion-backend/src/app_state.rs b/crates/sequins-datafusion-backend/src/app_state.rs new file mode 100644 index 00000000..1f941bc4 --- /dev/null +++ b/crates/sequins-datafusion-backend/src/app_state.rs @@ -0,0 +1,320 @@ +//! DataFusion table providers projecting the durable app-state store +//! ([`sequins_metadata::AppStateStore`]) into queryable tables: `conversations`, +//! `messages`, and `dashboards`. +//! +//! Each provider snapshots the current store state at **scan time** (building a +//! fresh in-memory batch and delegating to a `MemTable`), so mutations are visible +//! to queries without rebuilding the `OnceCell`-cached `SessionContext`. Registered +//! alongside the signal tables in `build_session_ctx`, so the assistant's own +//! `run_sql` tool — and any SQL client — can read chat history and dashboards. + +use std::sync::Arc; + +use arrow::array::{ArrayRef, RecordBatch, StringArray, UInt32Array, UInt64Array}; +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use datafusion::catalog::Session; +use datafusion::datasource::{MemTable, TableProvider}; +use datafusion::error::{DataFusionError, Result as DfResult}; +use datafusion::logical_expr::{Expr, TableType}; +use datafusion::physical_plan::ExecutionPlan; +use sequins_metadata::AppStateStore; + +use crate::exec_err; +use sequins_traits::QueryError; + +/// Register `conversations`, `messages`, and `dashboards` into `ctx`. +pub(crate) fn register_app_state_tables( + ctx: &datafusion::prelude::SessionContext, + store: Arc, +) -> Result<(), QueryError> { + let providers: Vec<(&str, Arc)> = vec![ + ( + "conversations", + Arc::new(AppStateTable::new(store.clone(), AppTable::Conversations)), + ), + ( + "messages", + Arc::new(AppStateTable::new(store.clone(), AppTable::Messages)), + ), + ( + "dashboards", + Arc::new(AppStateTable::new(store, AppTable::Dashboards)), + ), + ]; + for (name, provider) in providers { + ctx.register_table(name, provider) + .map_err(|e| exec_err(format!("Failed to register {name} table: {e}")))?; + } + Ok(()) +} + +#[derive(Clone, Copy)] +enum AppTable { + Conversations, + Messages, + Dashboards, +} + +/// A table provider over one projection of the app-state store. +struct AppStateTable { + store: Arc, + table: AppTable, + schema: SchemaRef, +} + +impl std::fmt::Debug for AppStateTable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AppStateTable") + .field("schema", &self.schema) + .finish() + } +} + +impl AppStateTable { + fn new(store: Arc, table: AppTable) -> Self { + Self { + store, + schema: schema_for(table), + table, + } + } + + /// Build a fresh batch from the current store snapshot. + async fn snapshot_batch(&self) -> DfResult { + match self.table { + AppTable::Conversations => self.conversations_batch().await, + AppTable::Messages => self.messages_batch().await, + AppTable::Dashboards => self.dashboards_batch().await, + } + .map_err(|e| DataFusionError::Execution(format!("app-state snapshot: {e}"))) + } + + async fn conversations_batch(&self) -> Result { + let convs = self.store.conversations_snapshot().await; + let ids: Vec<&str> = convs.iter().map(|c| c.id.as_str()).collect(); + let titles: Vec> = convs.iter().map(|c| c.title.as_deref()).collect(); + let created: Vec = convs.iter().map(|c| c.created_at_ns).collect(); + let updated: Vec = convs.iter().map(|c| c.updated_at_ns).collect(); + let counts: Vec = convs.iter().map(|c| c.items.len() as u32).collect(); + RecordBatch::try_new( + self.schema.clone(), + vec![ + Arc::new(StringArray::from(ids)) as ArrayRef, + Arc::new(StringArray::from(titles)), + Arc::new(UInt64Array::from(created)), + Arc::new(UInt64Array::from(updated)), + Arc::new(UInt32Array::from(counts)), + ], + ) + } + + async fn messages_batch(&self) -> Result { + let convs = self.store.conversations_snapshot().await; + let mut conv_id = Vec::new(); + let mut resp_id: Vec> = Vec::new(); + let mut position = Vec::new(); + let mut role = Vec::new(); + let mut item_type = Vec::new(); + let mut text: Vec> = Vec::new(); + let mut tool_name: Vec> = Vec::new(); + let mut tool_args: Vec> = Vec::new(); + let mut tool_output: Vec> = Vec::new(); + let mut created = Vec::new(); + for c in &convs { + for it in &c.items { + conv_id.push(c.id.clone()); + resp_id.push(it.response_id.clone()); + position.push(it.position); + role.push(it.role.clone()); + item_type.push(it.item_type.clone()); + text.push(it.text.clone()); + tool_name.push(it.tool_name.clone()); + tool_args.push(it.tool_arguments.clone()); + tool_output.push(it.tool_output.clone()); + created.push(it.created_at_ns); + } + } + RecordBatch::try_new( + self.schema.clone(), + vec![ + Arc::new(StringArray::from(conv_id)) as ArrayRef, + Arc::new(StringArray::from(resp_id)), + Arc::new(UInt32Array::from(position)), + Arc::new(StringArray::from(role)), + Arc::new(StringArray::from(item_type)), + Arc::new(StringArray::from(text)), + Arc::new(StringArray::from(tool_name)), + Arc::new(StringArray::from(tool_args)), + Arc::new(StringArray::from(tool_output)), + Arc::new(UInt64Array::from(created)), + ], + ) + } + + async fn dashboards_batch(&self) -> Result { + let dashboards = self.store.dashboards_snapshot().await; + let ids: Vec<&str> = dashboards.iter().map(|d| d.id.as_str()).collect(); + let titles: Vec<&str> = dashboards.iter().map(|d| d.title.as_str()).collect(); + let created: Vec = dashboards.iter().map(|d| d.created_at_ns).collect(); + let updated: Vec = dashboards.iter().map(|d| d.updated_at_ns).collect(); + let panel_count: Vec = dashboards.iter().map(|d| d.panel_count() as u32).collect(); + let panels_json: Vec = dashboards + .iter() + .map(|d| serde_json::to_string(&d.rows).unwrap_or_default()) + .collect(); + RecordBatch::try_new( + self.schema.clone(), + vec![ + Arc::new(StringArray::from(ids)) as ArrayRef, + Arc::new(StringArray::from(titles)), + Arc::new(UInt64Array::from(created)), + Arc::new(UInt64Array::from(updated)), + Arc::new(UInt32Array::from(panel_count)), + Arc::new(StringArray::from(panels_json)), + ], + ) + } +} + +#[async_trait::async_trait] +impl TableProvider for AppStateTable { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + fn table_type(&self) -> TableType { + TableType::View + } + + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec>, + filters: &[Expr], + limit: Option, + ) -> DfResult> { + // Snapshot current state at scan time so mutations are always visible. + let batch = self.snapshot_batch().await?; + let mem = MemTable::try_new(self.schema.clone(), vec![vec![batch]])?; + mem.scan(state, projection, filters, limit).await + } +} + +fn schema_for(table: AppTable) -> SchemaRef { + let s = |name: &str| Field::new(name, DataType::Utf8, false); + let s_null = |name: &str| Field::new(name, DataType::Utf8, true); + let u64f = |name: &str| Field::new(name, DataType::UInt64, false); + let u32f = |name: &str| Field::new(name, DataType::UInt32, false); + let fields = match table { + AppTable::Conversations => vec![ + s("id"), + s_null("title"), + u64f("created_at_ns"), + u64f("updated_at_ns"), + u32f("item_count"), + ], + AppTable::Messages => vec![ + s("conversation_id"), + s_null("response_id"), + u32f("position"), + s("role"), + s("item_type"), + s_null("text"), + s_null("tool_name"), + s_null("tool_arguments"), + s_null("tool_output"), + u64f("created_at_ns"), + ], + AppTable::Dashboards => vec![ + s("id"), + s("title"), + u64f("created_at_ns"), + u64f("updated_at_ns"), + u32f("panel_count"), + s("panels_json"), + ], + }; + Arc::new(Schema::new(fields)) +} + +#[cfg(test)] +mod tests { + use crate::DataFusionBackend; + use sequins_metadata::ConversationItem; + use sequins_storage::test_fixtures::TestStorageBuilder; + use std::sync::Arc; + + fn item(role: &str, item_type: &str, text: &str, resp: Option<&str>) -> ConversationItem { + ConversationItem { + response_id: resp.map(str::to_string), + position: 0, + role: role.into(), + item_type: item_type.into(), + text: Some(text.into()), + tool_name: None, + tool_arguments: None, + tool_output: None, + created_at_ns: 0, + } + } + + #[tokio::test] + async fn app_state_tables_are_queryable() { + let (storage, _t) = TestStorageBuilder::new().build().await; + storage + .app_state() + .append_response( + None, + Some("First chat".into()), + vec![item("user", "message", "how many spans?", None)], + vec![ + ConversationItem { + tool_name: Some("run_sql".into()), + tool_output: Some("800".into()), + ..item("tool", "sequins.tool_result", "", Some("resp_1")) + }, + item( + "assistant", + "message", + "There are 800 spans.", + Some("resp_1"), + ), + ], + "resp_1".into(), + ) + .await + .unwrap(); + + let backend = DataFusionBackend::new(Arc::new(storage)); + let ctx = backend.session().await.unwrap(); + + let convs = ctx + .sql("SELECT count(*) AS c FROM conversations") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(convs[0].num_rows(), 1); + + // The tool result row is queryable in `messages`. + let tool_rows = ctx + .sql("SELECT tool_name, tool_output FROM messages WHERE item_type = 'sequins.tool_result'") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(tool_rows.iter().map(|b| b.num_rows()).sum::(), 1); + + // Dashboards table exists and is empty. + let dash = ctx + .sql("SELECT count(*) AS c FROM dashboards") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(dash[0].num_rows(), 1); + } +} diff --git a/crates/sequins-datafusion-backend/src/execution.rs b/crates/sequins-datafusion-backend/src/execution.rs index eeeec844..1cb0bf08 100644 --- a/crates/sequins-datafusion-backend/src/execution.rs +++ b/crates/sequins-datafusion-backend/src/execution.rs @@ -5,7 +5,7 @@ use arrow::array::AsArray; use arrow::compute::{concat_batches, filter_record_batch}; use arrow_flight::FlightData; use datafusion::common::DFSchema; -use datafusion::execution::context::{ExecutionProps, SessionContext}; +use datafusion::execution::context::{ExecutionProps, SQLOptions, SessionContext}; use datafusion::logical_expr::{Expr, LogicalPlan, Operator}; use datafusion::physical_expr::create_physical_expr; use datafusion::physical_plan::PhysicalExpr; @@ -88,6 +88,17 @@ fn get_rel(plan_rel: &plan_rel::RelType) -> Option<&datafusion_substrait::substr } } +/// The output column names carried on a Substrait `Root` (the SeQL aliases). Empty for +/// a bare `Rel` (no root names). `consume_rel` drops these, so we reapply them to the +/// result schema in [`execute_logical_plan_to_batch`] — this is what makes result +/// columns use the user's `as ` aliases instead of raw DataFusion expression text. +fn plan_rel_names(plan_rel: &plan_rel::RelType) -> &[String] { + match plan_rel { + plan_rel::RelType::Rel(_) => &[], + plan_rel::RelType::Root(root) => root.names.as_slice(), + } +} + /// Convert a signal name string back to `Signal` enum. /// /// Used in the live path to subscribe to the correct WAL broadcast channel. @@ -147,6 +158,7 @@ pub(crate) async fn execute_snapshot( if let Some(plan_rel) = plan.relations.first() { if let Some(rel_type) = &plan_rel.rel_type { if let Some(rel) = get_rel(rel_type) { + let names = plan_rel_names(rel_type); let ctx_state = ctx.state(); let consumer = DefaultSubstraitConsumer::new(&primary_extensions, &ctx_state); let logical_plan = consumer.consume_rel(rel).await.map_err(|e| { @@ -154,7 +166,7 @@ pub(crate) async fn execute_snapshot( })?; let (arrow_schema, batch) = - execute_logical_plan_to_batch(&ctx, logical_plan).await?; + execute_logical_plan_to_batch(&ctx, logical_plan, names).await?; let col_defs = crate::arrow_convert::schema_to_col_defs(&arrow_schema); all_frames.push(Ok(schema_flight_data( @@ -188,6 +200,68 @@ pub(crate) async fn execute_snapshot( Ok(Box::pin(stream::iter(all_frames))) } +/// Read-only SQL options: allow queries (SELECT/DQL) but deny DDL, DML, and +/// statements — so ad-hoc SQL can scan the registered tables but never mutate. +/// Mirrors the assistant's `run_sql` guard. +pub(crate) fn read_only_sql_options() -> SQLOptions { + SQLOptions::new() + .with_allow_ddl(false) + .with_allow_dml(false) + .with_allow_statements(false) +} + +/// Execute a **read-only** plain SQL query over `ctx`, framing the result as a +/// `Table`-shaped snapshot (`Schema` + `Data` (if non-empty) + `Complete`) — the +/// same `FlightData` framing the SeQL snapshot path emits, so existing clients +/// decode it unchanged. +pub(crate) async fn execute_sql_snapshot( + ctx: SessionContext, + sql: &str, + watermark_ns: u64, +) -> Result { + let start = Instant::now(); + + let df = ctx + .sql_with_options(sql, read_only_sql_options()) + .await + .map_err(|e| exec_err(format!("SQL error: {}", e)))?; + + let arrow_schema = Arc::new(df.schema().as_arrow().clone()); + let batches = df + .collect() + .await + .map_err(|e| exec_err(format!("SQL execution error: {}", e)))?; + let batch = if batches.is_empty() { + arrow::record_batch::RecordBatch::new_empty(arrow_schema.clone()) + } else { + concat_batches(&arrow_schema, &batches) + .map_err(|e| exec_err(format!("Failed to concat batches: {}", e)))? + }; + let col_defs = crate::arrow_convert::schema_to_col_defs(&arrow_schema); + + let mut frames: Vec> = Vec::new(); + frames.push(Ok(schema_flight_data( + None, + arrow_schema, + seql_ast::schema::ResponseShape::Table, + col_defs, + watermark_ns, + ))); + let total_rows = batch.num_rows() as u64; + if batch.num_rows() > 0 { + frames.push(Ok(data_flight_data(None, &batch))); + } + frames.push(Ok(complete_flight_data(QueryStats { + execution_time_us: start.elapsed().as_micros() as u64, + rows_scanned: total_rows, + bytes_read: 0, + rows_returned: total_rows, + warning_count: 0, + }))); + + Ok(Box::pin(stream::iter(frames))) +} + /// Decode a serialised Substrait `Plan`, consume the first relation, execute it, /// and return the result as a single concatenated `RecordBatch`. /// @@ -206,6 +280,7 @@ async fn consume_and_execute_root( .first() .and_then(|pr| pr.rel_type.as_ref()) .ok_or_else(|| exec_err("Plan has no relations"))?; + let names = plan_rel_names(rel_type); let rel = get_rel(rel_type).ok_or_else(|| exec_err("First relation has no Rel"))?; let ctx_state = ctx.state(); let consumer = DefaultSubstraitConsumer::new(&extensions, &ctx_state); @@ -213,7 +288,7 @@ async fn consume_and_execute_root( .consume_rel(rel) .await .map_err(|e| exec_err(format!("consume_rel: {}", e)))?; - let (_schema, batch) = execute_logical_plan_to_batch(ctx, logical_plan).await?; + let (_schema, batch) = execute_logical_plan_to_batch(ctx, logical_plan, names).await?; Ok(batch) } @@ -248,11 +323,13 @@ async fn consume_execute_root( .map_err(|e| exec_err(format!("consume_execute_root: decode: {}", e)))?; let extensions = Extensions::try_from(&plan.extensions) .map_err(|e| exec_err(format!("consume_execute_root: extensions: {}", e)))?; - let rel = plan + let rel_type = plan .relations .first() .and_then(|pr| pr.rel_type.as_ref()) - .and_then(get_rel) + .ok_or_else(|| exec_err("consume_execute_root: plan has no primary relation"))?; + let names = plan_rel_names(rel_type); + let rel = get_rel(rel_type) .ok_or_else(|| exec_err("consume_execute_root: plan has no primary relation"))?; let ctx_state = ctx.state(); let consumer = DefaultSubstraitConsumer::new(&extensions, &ctx_state); @@ -266,7 +343,7 @@ async fn consume_execute_root( logical_plan = strip_plan_time_upper_bound(logical_plan, strip_time_col)?; } - let (schema, batch) = execute_logical_plan_to_batch(ctx, logical_plan).await?; + let (schema, batch) = execute_logical_plan_to_batch(ctx, logical_plan, names).await?; let col_defs = crate::arrow_convert::schema_to_col_defs(&schema); Ok(RootResult { schema, @@ -435,12 +512,15 @@ async fn execute_aux_plans( )) })?; - let rel = aux_plan + let rel_type = aux_plan .relations .first() - .and_then(|pr| pr.rel_type.as_ref()) - .and_then(|rt| get_rel(rt)); - let Some(rel) = rel else { continue }; + .and_then(|pr| pr.rel_type.as_ref()); + let Some(rel_type) = rel_type else { continue }; + let names = plan_rel_names(rel_type); + let Some(rel) = get_rel(rel_type) else { + continue; + }; let ctx_state = ctx.state(); let consumer = DefaultSubstraitConsumer::new(&aux_extensions, &ctx_state); @@ -451,7 +531,7 @@ async fn execute_aux_plans( )) })?; - let (arrow_schema, batch) = execute_logical_plan_to_batch(ctx, logical_plan).await?; + let (arrow_schema, batch) = execute_logical_plan_to_batch(ctx, logical_plan, names).await?; let col_defs = crate::arrow_convert::schema_to_col_defs(&arrow_schema); frames.push(Ok(schema_flight_data( @@ -474,6 +554,7 @@ async fn execute_aux_plans( async fn execute_logical_plan_to_batch( ctx: &SessionContext, logical_plan: LogicalPlan, + names: &[String], ) -> Result< ( Arc, @@ -500,7 +581,42 @@ async fn execute_logical_plan_to_batch( .map_err(|e| exec_err(format!("Failed to concat batches: {}", e)))? }; - Ok((arrow_schema, batch)) + // Reapply the SeQL aliases (Substrait `Root.names`) that `consume_rel` dropped, so + // output columns read `total_spans`/`bucket`/`n` rather than the raw expression text. + // Guarded on an exact count match (names are in output order); otherwise leave as-is. + apply_column_names(arrow_schema, batch, names) +} + +/// Rename a batch's columns to `names` when the count matches (names-only change, so the +/// data is untouched). No-op when `names` is empty or the length differs. +fn apply_column_names( + schema: Arc, + batch: arrow::record_batch::RecordBatch, + names: &[String], +) -> Result< + ( + Arc, + arrow::record_batch::RecordBatch, + ), + QueryError, +> { + use arrow::datatypes::{Field, Schema}; + if names.is_empty() || names.len() != schema.fields().len() { + return Ok((schema, batch)); + } + let fields: Vec = schema + .fields() + .iter() + .zip(names) + .map(|(f, name)| Field::new(name, f.data_type().clone(), f.is_nullable())) + .collect(); + let renamed = Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone())); + // Rebuild with the same column arrays under the renamed schema (arrays carry no + // names; `with_schema` would reject a name change as incompatible). + let batch = + arrow::record_batch::RecordBatch::try_new(renamed.clone(), batch.columns().to_vec()) + .map_err(|e| exec_err(format!("Failed to rename columns: {}", e)))?; + Ok((renamed, batch)) } /// Execute a live (streaming) query. @@ -550,6 +666,7 @@ async fn execute_live( if let Some(plan_rel) = plan.relations.first() { if let Some(rel_type) = &plan_rel.rel_type { if let Some(rel) = get_rel(rel_type) { + let names = plan_rel_names(rel_type); let ctx_state = ctx.state(); let consumer = DefaultSubstraitConsumer::new(&primary_extensions, &ctx_state); let logical_plan = consumer.consume_rel(rel).await.map_err(|e| { @@ -573,7 +690,7 @@ async fn execute_live( }); let (arrow_schema, batch) = - execute_logical_plan_to_batch(&ctx, logical_plan).await?; + execute_logical_plan_to_batch(&ctx, logical_plan, names).await?; let col_defs = crate::arrow_convert::schema_to_col_defs(&arrow_schema); historical_frames.push(Ok(schema_flight_data( diff --git a/crates/sequins-datafusion-backend/src/lib.rs b/crates/sequins-datafusion-backend/src/lib.rs index 90665cfe..b81bb77b 100644 --- a/crates/sequins-datafusion-backend/src/lib.rs +++ b/crates/sequins-datafusion-backend/src/lib.rs @@ -32,6 +32,7 @@ use std::sync::Arc; use tokio::sync::OnceCell; // Submodules +pub(crate) mod app_state; pub mod arrow_convert; pub(crate) mod execution; pub mod registration; @@ -66,6 +67,12 @@ pub struct DataFusionBackend { /// [`QueryScope`] (indexed by `scope as usize`: All / HotOnly / ColdOnly). /// Each registers the appropriate tier providers and is reused across queries. ctx_cache: [OnceCell; 3], + /// A context registering **only** the app-state tables + /// (`conversations`/`messages`/`dashboards`) — no signal/tier providers. Used by + /// [`execute_app_state_sql`](Self::execute_app_state_sql) so reading chat history + /// and dashboards never depends on (or triggers) cold-tier Vortex schema + /// inference, keeping those reads fast and immune to telemetry-tier issues. + app_state_ctx: OnceCell, } impl DataFusionBackend { @@ -74,6 +81,7 @@ impl DataFusionBackend { Self { storage, ctx_cache: std::array::from_fn(|_| OnceCell::new()), + app_state_ctx: OnceCell::new(), } } @@ -130,6 +138,59 @@ impl DataFusionBackend { self.session_ctx_for_scope(QueryScope::All).await } + /// The `All`-scope DataFusion [`SessionContext`] with every signal table + /// registered (hot ∪ cold), for in-process tooling that needs direct + /// DataFrame/SQL access alongside the SeQL query path — e.g. the assistant's + /// data-exploration lane (`describe_schema`, `column_profile`, `run_sql`, …). + /// + /// The context is lazily built and cached like the query path's, so tables + /// reflect current data at scan time. Read-only by construction: only the + /// union signal-table providers are registered, so ad-hoc SQL can scan but + /// not mutate storage. + pub async fn session(&self) -> Result { + self.session_ctx_for_scope(QueryScope::All).await + } + + /// Execute a **read-only** plain SQL query (SELECT only) against the `All`-scope + /// context and return a framed `SeqlStream` (shape `Table`). Lets clients read + /// the app-state tables (`conversations`/`messages`/`dashboards`) and any other + /// registered DataFusion table that SeQL does not address. DDL/DML/statements are + /// rejected by [`read_only_sql_options`](execution::read_only_sql_options). + pub async fn execute_sql_query( + &self, + sql: &str, + ) -> Result { + let ctx = self.session().await?; + let watermark = self.storage.wal().last_seq(); + execution::execute_sql_snapshot(ctx, sql, watermark).await + } + + /// Execute a **read-only** plain SQL query against a context that registers + /// *only* the durable app-state tables (`conversations`/`messages`/`dashboards`). + /// + /// Unlike [`execute_sql_query`](Self::execute_sql_query) — which uses the `All` + /// scope and so registers the hot+cold signal tables (triggering cold-tier Vortex + /// schema inference) — this path never touches the telemetry tiers. Reading chat + /// history therefore can't be blocked or destabilised by a cold-tier problem + /// (e.g. a Vortex type it can't infer), and skips the cold-listing overhead. This + /// is the entry point the desktop app uses for its conversation/message reads. + pub async fn execute_app_state_sql( + &self, + sql: &str, + ) -> Result { + let ctx = self + .app_state_ctx + .get_or_try_init(|| async { + let ctx = SessionContext::new(); + app_state::register_app_state_tables(&ctx, self.storage.app_state().clone())?; + Ok::<_, QueryError>(ctx) + }) + .await? + .clone(); + let watermark = self.storage.wal().last_seq(); + execution::execute_sql_snapshot(ctx, sql, watermark).await + } + /// Return the cached `SessionContext` for `scope`, initialising it on first use. pub(crate) async fn session_ctx_for_scope( &self, @@ -184,6 +245,11 @@ impl DataFusionBackend { .await?; } + // Project the durable app-state store (conversations/messages/dashboards) + // into queryable tables alongside the signal tables, so the assistant's + // `run_sql` and any SQL client can read chat history and dashboards. + app_state::register_app_state_tables(&ctx, self.storage.app_state().clone())?; + Ok(ctx) } } diff --git a/crates/sequins-datafusion-backend/src/trait_impls.rs b/crates/sequins-datafusion-backend/src/trait_impls.rs index c81f3c7e..32fd6ec0 100644 --- a/crates/sequins-datafusion-backend/src/trait_impls.rs +++ b/crates/sequins-datafusion-backend/src/trait_impls.rs @@ -28,6 +28,10 @@ impl QueryApi for DataFusionBackend { let plan_bytes = compile(seql, &ctx).await?; self.execute(plan_bytes).await } + + async fn sql(&self, sql: &str) -> Result { + self.execute_sql_query(sql).await + } } #[async_trait] @@ -38,4 +42,8 @@ impl QueryExec for DataFusionBackend { let storage = self.storage.clone(); execute_plan(&storage, plan_bytes, self.session_ctx_for_scope(scope)).await } + + async fn execute_sql(&self, sql: String) -> Result { + self.execute_sql_query(&sql).await + } } diff --git a/crates/sequins-datafusion-backend/tests/alias_columns.rs b/crates/sequins-datafusion-backend/tests/alias_columns.rs new file mode 100644 index 00000000..5d98e698 --- /dev/null +++ b/crates/sequins-datafusion-backend/tests/alias_columns.rs @@ -0,0 +1,74 @@ +//! SeQL aliases must become the output column names, and a `ts() bin` bucket must be a +//! real Timestamp column — both are what let clients render clean labels and time axes. + +use arrow::datatypes::DataType; +use futures::StreamExt; +use sequins_datafusion_backend::DataFusionBackend; +use sequins_flight::{decode_metadata, SeqlMetadata}; +use sequins_storage::test_fixtures::{make_test_otlp_traces, TestStorageBuilder}; +use sequins_traits::{OtlpIngest, QueryApi}; +use std::sync::Arc; + +/// Run `seql` and return the primary result's `(field_name, data_type)` list. +async fn schema_of(backend: &DataFusionBackend, seql: &str) -> Vec<(String, DataType)> { + let mut stream = backend.query(seql).await.expect("query failed"); + while let Some(frame) = stream.next().await { + let frame = frame.expect("frame error"); + // The Data frame for the primary table carries the schema in its Arrow batch. + if let Some(SeqlMetadata::Data { table: None }) = decode_metadata(&frame.app_metadata) { + let batch = sequins_flight::ipc_to_batch(&frame.data_body).unwrap(); + return batch + .schema() + .fields() + .iter() + .map(|f| (f.name().clone(), f.data_type().clone())) + .collect(); + } + } + panic!("no primary data frame for `{seql}`"); +} + +#[tokio::test] +async fn scalar_aggregation_uses_alias_name() { + let (storage, _t) = TestStorageBuilder::new().build().await; + storage + .ingest_traces(make_test_otlp_traces(1, 40)) + .await + .unwrap(); + let backend = DataFusionBackend::new(Arc::new(storage)); + + let schema = schema_of( + &backend, + "spans last 1h | group by {} { count() as total_spans }", + ) + .await; + assert_eq!(schema.len(), 1); + assert_eq!(schema[0].0, "total_spans", "alias must be the column name"); +} + +#[tokio::test] +async fn timeseries_bucket_is_named_and_timestamped() { + let (storage, _t) = TestStorageBuilder::new().build().await; + storage + .ingest_traces(make_test_otlp_traces(1, 60)) + .await + .unwrap(); + let backend = DataFusionBackend::new(Arc::new(storage)); + + let schema = schema_of( + &backend, + "spans last 1h | group by { ts() bin 1m as bucket } { count() as n }", + ) + .await; + + let names: Vec<&str> = schema.iter().map(|(n, _)| n.as_str()).collect(); + assert!(names.contains(&"bucket"), "group-key alias, got {names:?}"); + assert!(names.contains(&"n"), "aggregation alias, got {names:?}"); + + let bucket = schema.iter().find(|(n, _)| n == "bucket").unwrap(); + assert!( + matches!(bucket.1, DataType::Timestamp(_, _)), + "bucket must be a Timestamp, got {:?}", + bucket.1 + ); +} diff --git a/crates/sequins-datafusion-backend/tests/app_state_sql.rs b/crates/sequins-datafusion-backend/tests/app_state_sql.rs new file mode 100644 index 00000000..ebbf5e11 --- /dev/null +++ b/crates/sequins-datafusion-backend/tests/app_state_sql.rs @@ -0,0 +1,77 @@ +//! `execute_app_state_sql` reads the app-state tables from a telemetry-free context, +//! so chat/dashboard reads never depend on (or trigger) signal/cold-tier machinery. + +use futures::StreamExt; +use sequins_datafusion_backend::DataFusionBackend; +use sequins_flight::{decode_metadata, SeqlMetadata}; +use sequins_metadata::ConversationItem; +use sequins_storage::test_fixtures::{make_test_otlp_traces, TestStorageBuilder}; +use sequins_traits::OtlpIngest; +use std::sync::Arc; + +fn user_item(text: &str) -> ConversationItem { + ConversationItem { + response_id: Some("resp_1".into()), + position: 0, + role: "user".into(), + item_type: "message".into(), + text: Some(text.into()), + tool_name: None, + tool_arguments: None, + tool_output: None, + created_at_ns: 0, + } +} + +/// Count the rows returned by an app-state SQL read. +async fn app_state_rows(backend: &DataFusionBackend, sql: &str) -> usize { + let mut stream = backend + .execute_app_state_sql(sql) + .await + .expect("execute_app_state_sql"); + let mut rows = 0; + while let Some(frame) = stream.next().await { + let frame = frame.expect("frame error"); + if let Some(SeqlMetadata::Data { .. }) = decode_metadata(&frame.app_metadata) { + if let Ok(batch) = sequins_flight::ipc_to_batch(&frame.data_body) { + rows += batch.num_rows(); + } + } + } + rows +} + +#[tokio::test] +async fn app_state_sql_reads_conversations() { + let (storage, _t) = TestStorageBuilder::new().build().await; + // Ingest telemetry too, to prove the app-state read is independent of the tiers. + storage + .ingest_traces(make_test_otlp_traces(1, 10)) + .await + .unwrap(); + storage + .app_state() + .append_response( + None, + Some("First chat".into()), + vec![user_item("hello")], + vec![], + "resp_1".into(), + ) + .await + .unwrap(); + + let storage = Arc::new(storage); + let backend = DataFusionBackend::new(storage); + + let rows = app_state_rows( + &backend, + "SELECT id, title, updated_at_ns, item_count FROM conversations", + ) + .await; + assert_eq!(rows, 1, "the one persisted conversation should be returned"); + + // Messages of that conversation are readable too. + let msg_rows = app_state_rows(&backend, "SELECT role, text FROM messages").await; + assert_eq!(msg_rows, 1, "the single user message should be returned"); +} diff --git a/crates/sequins-ffi/Cargo.toml b/crates/sequins-ffi/Cargo.toml index e05be127..645e71ad 100644 --- a/crates/sequins-ffi/Cargo.toml +++ b/crates/sequins-ffi/Cargo.toml @@ -27,12 +27,15 @@ sequins-datafusion-backend = { workspace = true } sequins-server = { workspace = true } sequins-client = { workspace = true } sequins-traits = { workspace = true } +sequins-assistant = { workspace = true } +sequins-metadata = { workspace = true } # Async tokio = { workspace = true } futures = { workspace = true } # Serialization +serde = { workspace = true } serde_json = { workspace = true } base64 = { workspace = true } diff --git a/crates/sequins-ffi/include/sequins.h b/crates/sequins-ffi/include/sequins.h index c0d2f9e3..fe1cf82e 100644 --- a/crates/sequins-ffi/include/sequins.h +++ b/crates/sequins-ffi/include/sequins.h @@ -209,6 +209,16 @@ typedef enum CVisualizationType { VisualizationSeparateCharts = 5, } CVisualizationType; +/** + * Opaque handle to a constructed assistant (Local or Remote). + */ +typedef struct CAssistant CAssistant; + +/** + * Opaque handle to a running assistant chat stream. + */ +typedef struct CAssistantStream CAssistantStream; + /** * Opaque C type for DataSource - never actually defined * This provides type safety without exposing internals @@ -230,6 +240,69 @@ typedef struct CStreamHandle CStreamHandle; */ typedef struct CViewHandle CViewHandle; +/** + * Connection config for the assistant. + * + * - **Local**: `base_url`/`model`/`api_key` describe the backing LLM provider + * (OpenAI-compatible). `base_url` may be null for api.openai.com. + * - **Remote**: `base_url` is the daemon's `/v1` base (e.g. `http://host:8082/v1`), + * `api_key` is the bearer token, `model` is ignored. + */ +typedef struct CAssistantConfig { + const char *base_url; + const char *model; + const char *api_key; +} CAssistantConfig; + +/** + * A server-executed tool call and its result (for rendering activity). + */ +typedef struct CToolActivity { + const char *name; + /** + * Tool arguments as a JSON string. + */ + const char *arguments; + /** + * Rendered tool output. + */ + const char *output; +} CToolActivity; + +/** + * A tool call the client should handle (e.g. `render_visualization`). + */ +typedef struct CToolCall { + const char *name; + /** + * Tool arguments as a JSON string. + */ + const char *arguments; +} CToolCall; + +/** + * Terminal event with continuation ids. + */ +typedef struct CAssistantDone { + const char *response_id; + /** + * Conversation id to continue via `previous_response_id`; null if unpersisted. + */ + const char *conversation_id; +} CAssistantDone; + +/** + * C vtable for assistant events. Callbacks may fire from a Tokio worker thread and + * must copy out what they need and return promptly (the pointers are freed after). + */ +typedef struct CAssistantEventVTable { + void (*on_text)(const char*, void *ctx); + void (*on_tool_activity)(const struct CToolActivity*, void *ctx); + void (*on_tool_call)(const struct CToolCall*, void *ctx); + void (*on_done)(const struct CAssistantDone*, void *ctx); + void (*on_error)(const char*, void *ctx); +} CAssistantEventVTable; + /** * OTLP server configuration for local mode */ @@ -1426,6 +1499,99 @@ typedef struct CSpanQuery { uintptr_t limit; } CSpanQuery; +/** + * Construct an assistant over a data source and provider/daemon config. + * + * # Safety + * - `data_source` must be a valid `CDataSource*`. + * - `config` string pointers must be valid null-terminated UTF-8 or null. + * - On error returns null and, if `error_out` is non-null, writes an owned error + * string the caller must free with `sequins_string_free`. + */ +struct CAssistant *sequins_assistant_new(struct CDataSource *data_source, + struct CAssistantConfig config, + char **error_out); + +/** + * Free an assistant handle. + * + * # Safety + * `assistant` must be a valid pointer from `sequins_assistant_new` (or null). + */ +void sequins_assistant_free(struct CAssistant *assistant); + +/** + * Start a chat turn. `request_json` is an OpenAI Responses-shaped request + * (`input`, `tools`, `instructions`, `conversation`/`previous_response_id`, …). + * Returns a stream handle; events arrive via `vtable` until `on_done`/`on_error`. + * + * # Safety + * - `assistant` must be valid for the stream's lifetime. + * - `request_json` must be valid null-terminated UTF-8. + * - `vtable` fn pointers and `ctx` must remain valid until the stream is freed. + */ +struct CAssistantStream *sequins_assistant_chat(struct CAssistant *assistant, + const char *request_json, + struct CAssistantEventVTable vtable, + void *ctx); + +/** + * Best-effort cancel a running chat stream. Still free it with + * `sequins_assistant_stream_free`. + * + * # Safety + * `handle` must be a valid `CAssistantStream*` from `sequins_assistant_chat`. + */ +void sequins_assistant_cancel(struct CAssistantStream *handle); + +/** + * Free a chat stream handle. Aborts the task and **blocks** until it stops, so no + * callback fires after the caller's context is freed. + * + * # Safety + * `handle` must be a valid `CAssistantStream*` (or null). + */ +void sequins_assistant_stream_free(struct CAssistantStream *handle); + +/** + * List all dashboards. On success writes a JSON array to `out_json`. + * + * # Safety + * `data_source` must be valid; `out_json`/`error_out` are out-params. + */ +bool sequins_dashboard_list(struct CDataSource *data_source, char **out_json, char **error_out); + +/** + * Get a dashboard by id. Writes a JSON object (or `null`) to `out_json`. + * + * # Safety + * `data_source`/`id` must be valid; `out_json`/`error_out` are out-params. + */ +bool sequins_dashboard_get(struct CDataSource *data_source, + const char *id, + char **out_json, + char **error_out); + +/** + * Create or update a dashboard from a JSON object. Writes the stored dashboard + * (with id/timestamps) to `out_json`. + * + * # Safety + * `data_source`/`dashboard_json` must be valid; `out_json`/`error_out` are out-params. + */ +bool sequins_dashboard_save(struct CDataSource *data_source, + const char *dashboard_json, + char **out_json, + char **error_out); + +/** + * Delete a dashboard by id. + * + * # Safety + * `data_source`/`id` must be valid; `error_out` is an out-param. + */ +bool sequins_dashboard_delete(struct CDataSource *data_source, const char *id, char **error_out); + /** * Create a new local data source with embedded storage * @@ -1836,6 +2002,42 @@ struct CStreamHandle *sequins_seql_query(struct CDataSource *data_source, struct CFrameSinkVTable vtable, void *ctx); +/** + * Execute a **read-only** plain SQL query (SELECT only) and stream the framed + * result through the same `CFrameSinkVTable` as [`sequins_seql_query`]. + * + * This is how clients read the app-state tables (`conversations`, `messages`, + * `dashboards`) and any other registered DataFusion table that SeQL does not + * address. Local runs it in-process (`sql_with_options`, read-only); Remote sends + * it over Flight SQL's standard `CommandStatementQuery`. Results arrive as a + * `Table`-shaped snapshot (schema + data + complete). DDL/DML are rejected. + * + * # Safety + * Same contract as [`sequins_seql_query`]. + */ +struct CStreamHandle *sequins_sql_query(struct CDataSource *data_source, + const char *sql_text, + struct CFrameSinkVTable vtable, + void *ctx); + +/** + * Execute a **read-only** plain SQL query against *only* the app-state tables + * (`conversations`, `messages`, `dashboards`), streaming the framed result through + * the same `CFrameSinkVTable` as [`sequins_sql_query`]. + * + * Prefer this over [`sequins_sql_query`] for reading chat history and dashboards: + * it uses a telemetry-free context, so the read can't be blocked or destabilised by + * a signal/cold-tier problem (and it skips the cold-listing overhead). If the query + * task panics, an error frame is delivered rather than leaving the client hanging. + * + * # Safety + * Same contract as [`sequins_seql_query`]. + */ +struct CStreamHandle *sequins_app_state_query(struct CDataSource *data_source, + const char *sql_text, + struct CFrameSinkVTable vtable, + void *ctx); + /** * Execute a SeQL query in live streaming mode * diff --git a/crates/sequins-ffi/src/assistant.rs b/crates/sequins-ffi/src/assistant.rs new file mode 100644 index 00000000..1ee51aca --- /dev/null +++ b/crates/sequins-ffi/src/assistant.rs @@ -0,0 +1,321 @@ +//! FFI: streaming AI-assistant chat over the normalized [`Assistant`] façade. +//! +//! One interface regardless of backend: Local runs the in-process middleware model +//! (persisting conversations); Remote posts the daemon's `/v1/responses`. Events are +//! delivered through a C vtable — text, server-tool activity, client tool calls (the +//! app's `render_visualization`), a terminal `done` (with ids), and errors. Mirrors +//! the `seql.rs` streaming pattern (opaque handle + spawned task + **blocking** free). + +use std::ffi::{c_char, c_void, CStr, CString}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use futures::StreamExt; +use sequins_assistant::{Assistant, BackingModel, ChatEvent}; +use tokio::task::JoinHandle; + +use crate::data_source::{CDataSource, DataSourceImpl}; +use crate::runtime::RUNTIME; +use crate::seql::{AssertSend, SendPtr}; + +/// Opaque handle to a constructed assistant (Local or Remote). +pub struct CAssistant { + inner: Arc>, +} + +/// Connection config for the assistant. +/// +/// - **Local**: `base_url`/`model`/`api_key` describe the backing LLM provider +/// (OpenAI-compatible). `base_url` may be null for api.openai.com. +/// - **Remote**: `base_url` is the daemon's `/v1` base (e.g. `http://host:8082/v1`), +/// `api_key` is the bearer token, `model` is ignored. +#[repr(C)] +pub struct CAssistantConfig { + pub base_url: *const c_char, + pub model: *const c_char, + pub api_key: *const c_char, +} + +/// A server-executed tool call and its result (for rendering activity). +#[repr(C)] +pub struct CToolActivity { + pub name: *const c_char, + /// Tool arguments as a JSON string. + pub arguments: *const c_char, + /// Rendered tool output. + pub output: *const c_char, +} + +/// A tool call the client should handle (e.g. `render_visualization`). +#[repr(C)] +pub struct CToolCall { + pub name: *const c_char, + /// Tool arguments as a JSON string. + pub arguments: *const c_char, +} + +/// Terminal event with continuation ids. +#[repr(C)] +pub struct CAssistantDone { + pub response_id: *const c_char, + /// Conversation id to continue via `previous_response_id`; null if unpersisted. + pub conversation_id: *const c_char, +} + +/// C vtable for assistant events. Callbacks may fire from a Tokio worker thread and +/// must copy out what they need and return promptly (the pointers are freed after). +#[repr(C)] +pub struct CAssistantEventVTable { + pub on_text: Option, + pub on_tool_activity: Option, + pub on_tool_call: Option, + pub on_done: Option, + pub on_error: Option, +} +// SAFETY: only fn pointers + a caller-owned void* context. +unsafe impl Send for CAssistantEventVTable {} +unsafe impl Sync for CAssistantEventVTable {} + +struct AssistantSink { + vtable: CAssistantEventVTable, + ctx: SendPtr, +} +// SAFETY: vtable is Send; ctx is a SendPtr (caller-guaranteed thread-safe). +unsafe impl Send for AssistantSink {} + +/// Opaque handle to a running assistant chat stream. +pub struct CAssistantStream { + cancel: Arc, + _task: JoinHandle<()>, +} + +fn opt_cstr(p: *const c_char) -> Option { + if p.is_null() { + return None; + } + unsafe { CStr::from_ptr(p) } + .to_str() + .ok() + .map(str::to_string) + .filter(|s| !s.is_empty()) +} + +unsafe fn set_error(error_out: *mut *mut c_char, msg: &str) { + if !error_out.is_null() { + *error_out = CString::new(msg).unwrap_or_default().into_raw(); + } +} + +fn to_cstring(s: String) -> CString { + CString::new(s).unwrap_or_default() +} + +/// Construct an assistant over a data source and provider/daemon config. +/// +/// # Safety +/// - `data_source` must be a valid `CDataSource*`. +/// - `config` string pointers must be valid null-terminated UTF-8 or null. +/// - On error returns null and, if `error_out` is non-null, writes an owned error +/// string the caller must free with `sequins_string_free`. +#[no_mangle] +pub unsafe extern "C" fn sequins_assistant_new( + data_source: *mut CDataSource, + config: CAssistantConfig, + error_out: *mut *mut c_char, +) -> *mut CAssistant { + if data_source.is_null() { + set_error(error_out, "data source is null"); + return std::ptr::null_mut(); + } + let impl_ref = &*(data_source as *const DataSourceImpl); + let base_url = opt_cstr(config.base_url); + let api_key = opt_cstr(config.api_key); + + let assistant: Assistant = match impl_ref { + #[cfg(feature = "local")] + DataSourceImpl::Local { + storage, backend, .. + } => { + let Some(model_name) = opt_cstr(config.model) else { + set_error(error_out, "local assistant requires a model name"); + return std::ptr::null_mut(); + }; + let Some(key) = api_key.as_deref() else { + set_error(error_out, "local assistant requires an api_key"); + return std::ptr::null_mut(); + }; + let backing = + match sequins_assistant::build_backing_model(base_url.as_deref(), &model_name, key) + { + Ok(b) => b, + Err(e) => { + set_error(error_out, &format!("failed to build backing model: {e}")); + return std::ptr::null_mut(); + } + }; + let tools = sequins_assistant::Tools::new(Arc::clone(backend)); + let model = sequins_assistant::SequinsAssistantModel::new(backing, tools); + Assistant::local(model, Some(Arc::clone(storage.app_state()))) + } + DataSourceImpl::Remote { .. } => { + let Some(base) = base_url else { + set_error(error_out, "remote assistant requires a base_url"); + return std::ptr::null_mut(); + }; + Assistant::remote(base, api_key) + } + }; + + Box::into_raw(Box::new(CAssistant { + inner: Arc::new(assistant), + })) +} + +/// Free an assistant handle. +/// +/// # Safety +/// `assistant` must be a valid pointer from `sequins_assistant_new` (or null). +#[no_mangle] +pub unsafe extern "C" fn sequins_assistant_free(assistant: *mut CAssistant) { + if !assistant.is_null() { + drop(Box::from_raw(assistant)); + } +} + +/// Start a chat turn. `request_json` is an OpenAI Responses-shaped request +/// (`input`, `tools`, `instructions`, `conversation`/`previous_response_id`, …). +/// Returns a stream handle; events arrive via `vtable` until `on_done`/`on_error`. +/// +/// # Safety +/// - `assistant` must be valid for the stream's lifetime. +/// - `request_json` must be valid null-terminated UTF-8. +/// - `vtable` fn pointers and `ctx` must remain valid until the stream is freed. +#[no_mangle] +pub unsafe extern "C" fn sequins_assistant_chat( + assistant: *mut CAssistant, + request_json: *const c_char, + vtable: CAssistantEventVTable, + ctx: *mut c_void, +) -> *mut CAssistantStream { + if assistant.is_null() || request_json.is_null() { + return std::ptr::null_mut(); + } + let Some(request) = CStr::from_ptr(request_json) + .to_str() + .ok() + .and_then(|s| serde_json::from_str::(s).ok()) + else { + return std::ptr::null_mut(); + }; + + let inner = Arc::clone(&(*assistant).inner); + let cancel = Arc::new(AtomicBool::new(false)); + let cancel_task = Arc::clone(&cancel); + let sink = AssistantSink { + vtable, + ctx: SendPtr(ctx), + }; + + let task = RUNTIME.spawn(AssertSend(async move { + let mut stream = inner.chat(request); + while let Some(event) = stream.next().await { + if cancel_task.load(Ordering::Relaxed) { + break; + } + dispatch_chat_event(event, &sink); + } + })); + + Box::into_raw(Box::new(CAssistantStream { + cancel, + _task: task, + })) +} + +/// Best-effort cancel a running chat stream. Still free it with +/// `sequins_assistant_stream_free`. +/// +/// # Safety +/// `handle` must be a valid `CAssistantStream*` from `sequins_assistant_chat`. +#[no_mangle] +pub unsafe extern "C" fn sequins_assistant_cancel(handle: *mut CAssistantStream) { + if handle.is_null() { + return; + } + (*handle).cancel.store(true, Ordering::Relaxed); + (*handle)._task.abort(); +} + +/// Free a chat stream handle. Aborts the task and **blocks** until it stops, so no +/// callback fires after the caller's context is freed. +/// +/// # Safety +/// `handle` must be a valid `CAssistantStream*` (or null). +#[no_mangle] +pub unsafe extern "C" fn sequins_assistant_stream_free(handle: *mut CAssistantStream) { + if !handle.is_null() { + let stream = Box::from_raw(handle); + stream.cancel.store(true, Ordering::Relaxed); + stream._task.abort(); + let _ = futures::executor::block_on(stream._task); + } +} + +fn dispatch_chat_event(event: ChatEvent, sink: &AssistantSink) { + let ctx = sink.ctx.0; + unsafe { + match event { + ChatEvent::Text(t) => { + if let Some(cb) = sink.vtable.on_text { + let c = to_cstring(t); + cb(c.as_ptr(), ctx); + } + } + ChatEvent::ServerTool { + name, + arguments, + output, + } => { + if let Some(cb) = sink.vtable.on_tool_activity { + let (n, a, o) = (to_cstring(name), to_cstring(arguments), to_cstring(output)); + let activity = CToolActivity { + name: n.as_ptr(), + arguments: a.as_ptr(), + output: o.as_ptr(), + }; + cb(&activity, ctx); + } + } + ChatEvent::ClientTool { name, arguments } => { + if let Some(cb) = sink.vtable.on_tool_call { + let (n, a) = (to_cstring(name), to_cstring(arguments)); + let call = CToolCall { + name: n.as_ptr(), + arguments: a.as_ptr(), + }; + cb(&call, ctx); + } + } + ChatEvent::Done { + response_id, + conversation_id, + } => { + if let Some(cb) = sink.vtable.on_done { + let r = to_cstring(response_id); + let c = conversation_id.map(to_cstring); + let done = CAssistantDone { + response_id: r.as_ptr(), + conversation_id: c.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()), + }; + cb(&done, ctx); + } + } + ChatEvent::Error(m) => { + if let Some(cb) = sink.vtable.on_error { + let c = to_cstring(m); + cb(c.as_ptr(), ctx); + } + } + } + } +} diff --git a/crates/sequins-ffi/src/dashboard.rs b/crates/sequins-ffi/src/dashboard.rs new file mode 100644 index 00000000..f2b1cba7 --- /dev/null +++ b/crates/sequins-ffi/src/dashboard.rs @@ -0,0 +1,226 @@ +//! FFI: dashboard persistence (list/get/save/delete), normalized over Local +//! (in-process `Storage`) and Remote (`RemoteClient` REST). JSON in, JSON out. +//! +//! Management-style ABI: each fn returns `bool` (success), writes JSON to an +//! out-param (caller frees with `sequins_string_free`), and on failure writes an +//! owned error string to `error_out`. + +use std::ffi::{c_char, CStr, CString}; + +use sequins_metadata::{Dashboard, DashboardApi}; + +use crate::data_source::{CDataSource, DataSourceImpl}; +use crate::runtime::RUNTIME; + +/// Resolve the dashboard interface for this data source (Local `Storage` or Remote +/// `RemoteClient` — both implement `DashboardApi`). +fn dashboard_api(impl_ref: &DataSourceImpl) -> &dyn DashboardApi { + match impl_ref { + #[cfg(feature = "local")] + DataSourceImpl::Local { storage, .. } => storage.as_ref(), + DataSourceImpl::Remote { client } => client.as_ref(), + } +} + +unsafe fn set_error(error_out: *mut *mut c_char, msg: &str) { + if !error_out.is_null() { + *error_out = CString::new(msg).unwrap_or_default().into_raw(); + } +} + +unsafe fn write_json(out: *mut *mut c_char, value: &T) -> bool { + match serde_json::to_string(value) { + Ok(s) => { + if !out.is_null() { + *out = CString::new(s).unwrap_or_default().into_raw(); + } + true + } + Err(_) => false, + } +} + +/// List all dashboards. On success writes a JSON array to `out_json`. +/// +/// # Safety +/// `data_source` must be valid; `out_json`/`error_out` are out-params. +#[no_mangle] +pub unsafe extern "C" fn sequins_dashboard_list( + data_source: *mut CDataSource, + out_json: *mut *mut c_char, + error_out: *mut *mut c_char, +) -> bool { + if data_source.is_null() { + set_error(error_out, "data source is null"); + return false; + } + let api = dashboard_api(&*(data_source as *const DataSourceImpl)); + match RUNTIME.block_on(api.list_dashboards()) { + Ok(list) => write_json(out_json, &list), + Err(e) => { + set_error(error_out, &e.to_string()); + false + } + } +} + +/// Get a dashboard by id. Writes a JSON object (or `null`) to `out_json`. +/// +/// # Safety +/// `data_source`/`id` must be valid; `out_json`/`error_out` are out-params. +#[no_mangle] +pub unsafe extern "C" fn sequins_dashboard_get( + data_source: *mut CDataSource, + id: *const c_char, + out_json: *mut *mut c_char, + error_out: *mut *mut c_char, +) -> bool { + if data_source.is_null() || id.is_null() { + set_error(error_out, "data source or id is null"); + return false; + } + let id = match CStr::from_ptr(id).to_str() { + Ok(s) => s, + Err(_) => { + set_error(error_out, "id is not valid UTF-8"); + return false; + } + }; + let api = dashboard_api(&*(data_source as *const DataSourceImpl)); + match RUNTIME.block_on(api.get_dashboard(id)) { + Ok(dash) => write_json(out_json, &dash), + Err(e) => { + set_error(error_out, &e.to_string()); + false + } + } +} + +/// Create or update a dashboard from a JSON object. Writes the stored dashboard +/// (with id/timestamps) to `out_json`. +/// +/// # Safety +/// `data_source`/`dashboard_json` must be valid; `out_json`/`error_out` are out-params. +#[no_mangle] +pub unsafe extern "C" fn sequins_dashboard_save( + data_source: *mut CDataSource, + dashboard_json: *const c_char, + out_json: *mut *mut c_char, + error_out: *mut *mut c_char, +) -> bool { + if data_source.is_null() || dashboard_json.is_null() { + set_error(error_out, "data source or dashboard is null"); + return false; + } + let dashboard: Dashboard = match CStr::from_ptr(dashboard_json) + .to_str() + .ok() + .and_then(|s| serde_json::from_str(s).ok()) + { + Some(d) => d, + None => { + set_error(error_out, "invalid dashboard JSON"); + return false; + } + }; + let api = dashboard_api(&*(data_source as *const DataSourceImpl)); + match RUNTIME.block_on(api.save_dashboard(dashboard)) { + Ok(stored) => write_json(out_json, &stored), + Err(e) => { + set_error(error_out, &e.to_string()); + false + } + } +} + +/// Delete a dashboard by id. +/// +/// # Safety +/// `data_source`/`id` must be valid; `error_out` is an out-param. +#[no_mangle] +pub unsafe extern "C" fn sequins_dashboard_delete( + data_source: *mut CDataSource, + id: *const c_char, + error_out: *mut *mut c_char, +) -> bool { + if data_source.is_null() || id.is_null() { + set_error(error_out, "data source or id is null"); + return false; + } + let id = match CStr::from_ptr(id).to_str() { + Ok(s) => s, + Err(_) => { + set_error(error_out, "id is not valid UTF-8"); + return false; + } + }; + let api = dashboard_api(&*(data_source as *const DataSourceImpl)); + match RUNTIME.block_on(api.delete_dashboard(id)) { + Ok(()) => true, + Err(e) => { + set_error(error_out, &e.to_string()); + false + } + } +} + +#[cfg(all(test, feature = "local"))] +mod tests { + use super::*; + use crate::data_source::{ + sequins_data_source_free, sequins_data_source_new_local, sequins_string_free, + COtlpServerConfig, + }; + + unsafe fn take(ptr: *mut c_char) -> String { + assert!(!ptr.is_null()); + let s = CStr::from_ptr(ptr).to_string_lossy().into_owned(); + sequins_string_free(ptr); + s + } + + #[test] + fn dashboard_ffi_roundtrip() { + let tmp = tempfile::tempdir().unwrap(); + let db = CString::new(tmp.path().to_str().unwrap()).unwrap(); + let mut err: *mut c_char = std::ptr::null_mut(); + let ds = sequins_data_source_new_local( + db.as_ptr(), + COtlpServerConfig { + grpc_port: 0, + http_port: 0, + }, + &mut err, + ); + assert!(!ds.is_null()); + + // Save. + let dashboard = serde_json::json!({ + "id": "", "title": "Errors", "created_at_ns": 0, "updated_at_ns": 0, + "panels": [{ "visualization": { "seql": "logs last 1h", "title": "logs", "shape": "table" }, + "layout": { "x": 0, "y": 0, "w": 6, "h": 4 } }] + }); + let dashboard_c = CString::new(dashboard.to_string()).unwrap(); + let mut out: *mut c_char = std::ptr::null_mut(); + let mut err2: *mut c_char = std::ptr::null_mut(); + let ok = unsafe { sequins_dashboard_save(ds, dashboard_c.as_ptr(), &mut out, &mut err2) }; + assert!(ok); + let saved: serde_json::Value = serde_json::from_str(&unsafe { take(out) }).unwrap(); + let id = saved["id"].as_str().unwrap().to_string(); + assert!(!id.is_empty()); + + // List → 1. + let mut list_out: *mut c_char = std::ptr::null_mut(); + let ok = unsafe { sequins_dashboard_list(ds, &mut list_out, &mut err2) }; + assert!(ok); + let list: serde_json::Value = serde_json::from_str(&unsafe { take(list_out) }).unwrap(); + assert_eq!(list.as_array().unwrap().len(), 1); + + // Delete. + let id_c = CString::new(id).unwrap(); + let ok = unsafe { sequins_dashboard_delete(ds, id_c.as_ptr(), &mut err2) }; + assert!(ok); + + sequins_data_source_free(ds); + } +} diff --git a/crates/sequins-ffi/src/data_source.rs b/crates/sequins-ffi/src/data_source.rs index a281bd6f..840522b3 100644 --- a/crates/sequins-ffi/src/data_source.rs +++ b/crates/sequins-ffi/src/data_source.rs @@ -183,7 +183,7 @@ pub extern "C" fn sequins_data_source_new_remote( } }; - let _management_str = unsafe { + let management_str = unsafe { match CStr::from_ptr(management_url).to_str() { Ok(s) => s, Err(e) => { @@ -196,9 +196,10 @@ pub extern "C" fn sequins_data_source_new_remote( } }; - // Create RemoteClient — synchronous (lazy channel, no actual TCP connection yet) + // Create RemoteClient — synchronous (lazy channel, no actual TCP connection yet). + // The management URL powers the dashboard REST endpoints. let client = match RemoteClient::new(query_str) { - Ok(c) => Arc::new(c), + Ok(c) => Arc::new(c.with_management_url(Some(management_str.to_string()))), Err(e) => { set_error(error_out, &format!("Failed to create RemoteClient: {}", e)); return std::ptr::null_mut(); diff --git a/crates/sequins-ffi/src/lib.rs b/crates/sequins-ffi/src/lib.rs index 98266306..8cfe6a44 100644 --- a/crates/sequins-ffi/src/lib.rs +++ b/crates/sequins-ffi/src/lib.rs @@ -7,7 +7,9 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] +pub mod assistant; mod compat; +pub mod dashboard; pub mod data_source; pub mod logging; pub mod management; diff --git a/crates/sequins-ffi/src/seql.rs b/crates/sequins-ffi/src/seql.rs index a28db4c8..9bd228ca 100644 --- a/crates/sequins-ffi/src/seql.rs +++ b/crates/sequins-ffi/src/seql.rs @@ -169,7 +169,7 @@ pub struct CStreamHandle { // ── Internal context wrapper ────────────────────────────────────────────────── /// Newtype wrapper for raw pointers that are send-safe by caller guarantee -struct SendPtr(*mut std::ffi::c_void); +pub(crate) struct SendPtr(pub(crate) *mut std::ffi::c_void); // SAFETY: Caller guarantees the pointer is valid and thread-safe for the stream lifetime. unsafe impl Send for SendPtr {} @@ -188,7 +188,7 @@ unsafe impl Send for SinkCtx {} /// Caller must ensure that all data accessed across `.await` points is actually /// thread-safe. Used here because the raw pointer in `SinkCtx.ctx` is wrapped /// in `SendPtr` but Rust's async future analysis still sees the inner `*mut c_void`. -struct AssertSend(F); +pub(crate) struct AssertSend(pub(crate) F); impl std::future::Future for AssertSend { type Output = F::Output; fn poll( @@ -233,6 +233,64 @@ pub struct CFrameSinkVTable { unsafe impl Send for CFrameSinkVTable {} unsafe impl Sync for CFrameSinkVTable {} +/// Query backend for a data source — Local (in-process) or Remote (over the wire). +/// Both `DataFusionBackend` and `RemoteClient` implement `QueryApi`, but that trait +/// isn't `dyn`-safe (native `async fn`), so we dispatch with a small enum. +enum QueryExecutor { + #[cfg(feature = "local")] + Local(Arc), + Remote(Arc), +} + +impl QueryExecutor { + async fn query(&self, seql: &str) -> Result { + match self { + #[cfg(feature = "local")] + QueryExecutor::Local(b) => b.query(seql).await, + QueryExecutor::Remote(c) => c.query(seql).await, + } + } + + async fn query_live(&self, seql: &str) -> Result { + match self { + #[cfg(feature = "local")] + QueryExecutor::Local(b) => b.query_live(seql).await, + QueryExecutor::Remote(c) => c.query_live(seql).await, + } + } + + async fn sql(&self, sql: &str) -> Result { + use sequins_traits::QueryApi; + match self { + #[cfg(feature = "local")] + QueryExecutor::Local(b) => b.sql(sql).await, + QueryExecutor::Remote(c) => c.sql(sql).await, + } + } + + /// Read the app-state tables (`conversations`/`messages`/`dashboards`) via a + /// telemetry-free context locally, so the read never depends on cold-tier health. + /// Remote goes over the normal Flight SQL path (the daemon owns its own tiers). + async fn app_state_sql(&self, sql: &str) -> Result { + match self { + #[cfg(feature = "local")] + QueryExecutor::Local(b) => b.execute_app_state_sql(sql).await, + QueryExecutor::Remote(c) => { + use sequins_traits::QueryApi; + c.sql(sql).await + } + } + } +} + +fn query_executor(ds: &DataSourceImpl) -> QueryExecutor { + match ds { + #[cfg(feature = "local")] + DataSourceImpl::Local { backend, .. } => QueryExecutor::Local(Arc::clone(backend)), + DataSourceImpl::Remote { client } => QueryExecutor::Remote(Arc::clone(client)), + } +} + /// Cancel a running SeQL stream /// /// This is a best-effort cancellation. The stream may produce a few more frames @@ -304,12 +362,9 @@ pub unsafe extern "C" fn sequins_seql_query( } }; - // Get the shared DataFusionBackend from the data source + // Resolve the query backend (Local in-process or Remote over Flight). let ds = &*(data_source as *const DataSourceImpl); - let backend = match ds { - DataSourceImpl::Local { backend, .. } => Arc::clone(backend), - DataSourceImpl::Remote { .. } => return std::ptr::null_mut(), - }; + let executor = query_executor(ds); let cancel = Arc::new(AtomicBool::new(false)); let cancel_clone = cancel.clone(); @@ -323,7 +378,7 @@ pub unsafe extern "C" fn sequins_seql_query( // valid and thread-safe for the lifetime of the stream. let task = RUNTIME.spawn(AssertSend(async move { // Use QueryApi to compile and execute in one call - let mut stream = match backend.query(&query_str).await { + let mut stream = match executor.query(&query_str).await { Ok(s) => s, Err(e) => { let c_err = CQueryError::from_error(&e); @@ -362,6 +417,199 @@ pub unsafe extern "C" fn sequins_seql_query( })) } +/// Execute a **read-only** plain SQL query (SELECT only) and stream the framed +/// result through the same `CFrameSinkVTable` as [`sequins_seql_query`]. +/// +/// This is how clients read the app-state tables (`conversations`, `messages`, +/// `dashboards`) and any other registered DataFusion table that SeQL does not +/// address. Local runs it in-process (`sql_with_options`, read-only); Remote sends +/// it over Flight SQL's standard `CommandStatementQuery`. Results arrive as a +/// `Table`-shaped snapshot (schema + data + complete). DDL/DML are rejected. +/// +/// # Safety +/// Same contract as [`sequins_seql_query`]. +#[no_mangle] +#[tracing::instrument(skip_all, name = "sql_query")] +pub unsafe extern "C" fn sequins_sql_query( + data_source: *mut CDataSource, + sql_text: *const c_char, + vtable: CFrameSinkVTable, + ctx: *mut c_void, +) -> *mut CStreamHandle { + if data_source.is_null() || sql_text.is_null() { + return std::ptr::null_mut(); + } + + let sql_str = match CStr::from_ptr(sql_text).to_str() { + Ok(s) => s.to_string(), + Err(_) => { + tracing::error!("Invalid UTF-8 in SQL text"); + if let Some(cb) = vtable.on_error { + let err = QueryError::InvalidAst { + message: "Invalid UTF-8 in SQL text".to_string(), + }; + cb(Box::into_raw(CQueryError::from_error(&err)), ctx); + } + return std::ptr::null_mut(); + } + }; + + let ds = &*(data_source as *const DataSourceImpl); + let executor = query_executor(ds); + + let cancel = Arc::new(AtomicBool::new(false)); + let cancel_clone = cancel.clone(); + + let sink_ctx = SinkCtx { + vtable, + ctx: SendPtr(ctx), + }; + + let task = RUNTIME.spawn(AssertSend(async move { + let mut stream = match executor.sql(&sql_str).await { + Ok(s) => s, + Err(e) => { + if let Some(cb) = sink_ctx.vtable.on_error { + unsafe { cb(Box::into_raw(CQueryError::from_error(&e)), sink_ctx.ctx.0) }; + } + return; + } + }; + + while let Some(frame_result) = stream.next().await { + if cancel_clone.load(Ordering::Relaxed) { + break; + } + let fd = match frame_result { + Ok(fd) => fd, + Err(e) => { + if let Some(cb) = sink_ctx.vtable.on_error { + unsafe { cb(Box::into_raw(CQueryError::from_error(&e)), sink_ctx.ctx.0) }; + } + break; + } + }; + let Some(metadata) = decode_metadata(&fd.app_metadata) else { + tracing::warn!("Failed to decode frame metadata"); + continue; + }; + dispatch_flight_metadata(metadata, &fd.data_body, &sink_ctx); + } + })); + + Box::into_raw(Box::new(CStreamHandle { + cancel, + _task: task, + })) +} + +/// Execute a **read-only** plain SQL query against *only* the app-state tables +/// (`conversations`, `messages`, `dashboards`), streaming the framed result through +/// the same `CFrameSinkVTable` as [`sequins_sql_query`]. +/// +/// Prefer this over [`sequins_sql_query`] for reading chat history and dashboards: +/// it uses a telemetry-free context, so the read can't be blocked or destabilised by +/// a signal/cold-tier problem (and it skips the cold-listing overhead). If the query +/// task panics, an error frame is delivered rather than leaving the client hanging. +/// +/// # Safety +/// Same contract as [`sequins_seql_query`]. +#[no_mangle] +#[tracing::instrument(skip_all, name = "app_state_query")] +pub unsafe extern "C" fn sequins_app_state_query( + data_source: *mut CDataSource, + sql_text: *const c_char, + vtable: CFrameSinkVTable, + ctx: *mut c_void, +) -> *mut CStreamHandle { + if data_source.is_null() || sql_text.is_null() { + return std::ptr::null_mut(); + } + + let sql_str = match CStr::from_ptr(sql_text).to_str() { + Ok(s) => s.to_string(), + Err(_) => { + tracing::error!("Invalid UTF-8 in SQL text"); + if let Some(cb) = vtable.on_error { + let err = QueryError::InvalidAst { + message: "Invalid UTF-8 in SQL text".to_string(), + }; + cb(Box::into_raw(CQueryError::from_error(&err)), ctx); + } + return std::ptr::null_mut(); + } + }; + + let ds = &*(data_source as *const DataSourceImpl); + let executor = query_executor(ds); + + let cancel = Arc::new(AtomicBool::new(false)); + let cancel_clone = cancel.clone(); + + let sink_ctx = SinkCtx { + vtable, + ctx: SendPtr(ctx), + }; + // Captured for the panic guard (both are `Copy`), so a swallowed panic in the + // spawned task still reaches the client instead of hanging it forever. + let panic_on_error = sink_ctx.vtable.on_error; + let panic_ctx = ctx; + + let task = RUNTIME.spawn(AssertSend(async move { + let body = async move { + let mut stream = match executor.app_state_sql(&sql_str).await { + Ok(s) => s, + Err(e) => { + if let Some(cb) = sink_ctx.vtable.on_error { + unsafe { cb(Box::into_raw(CQueryError::from_error(&e)), sink_ctx.ctx.0) }; + } + return; + } + }; + + while let Some(frame_result) = stream.next().await { + if cancel_clone.load(Ordering::Relaxed) { + break; + } + let fd = match frame_result { + Ok(fd) => fd, + Err(e) => { + if let Some(cb) = sink_ctx.vtable.on_error { + unsafe { + cb(Box::into_raw(CQueryError::from_error(&e)), sink_ctx.ctx.0) + }; + } + break; + } + }; + let Some(metadata) = decode_metadata(&fd.app_metadata) else { + tracing::warn!("Failed to decode frame metadata"); + continue; + }; + dispatch_flight_metadata(metadata, &fd.data_body, &sink_ctx); + } + }; + + if futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(body)) + .await + .is_err() + { + tracing::error!("app-state query task panicked"); + if let Some(cb) = panic_on_error { + let err = QueryError::Execution { + message: "internal error while reading app-state tables".to_string(), + }; + unsafe { cb(Box::into_raw(CQueryError::from_error(&err)), panic_ctx) }; + } + } + })); + + Box::into_raw(Box::new(CStreamHandle { + cancel, + _task: task, + })) +} + /// Execute a SeQL query in live streaming mode /// /// Identical to `sequins_seql_query` except the query runs in live mode: @@ -412,10 +660,7 @@ pub unsafe extern "C" fn sequins_seql_query_live( }; let ds = &*(data_source as *const DataSourceImpl); - let backend = match ds { - DataSourceImpl::Local { backend, .. } => Arc::clone(backend), - DataSourceImpl::Remote { .. } => return std::ptr::null_mut(), - }; + let executor = query_executor(ds); let cancel = Arc::new(AtomicBool::new(false)); let cancel_clone = cancel.clone(); @@ -426,7 +671,7 @@ pub unsafe extern "C" fn sequins_seql_query_live( }; let task = RUNTIME.spawn(AssertSend(async move { - let mut stream = match backend.query_live(&query_str).await { + let mut stream = match executor.query_live(&query_str).await { Ok(s) => s, Err(e) => { let c_err = CQueryError::from_error(&e); @@ -706,10 +951,7 @@ pub unsafe extern "C" fn sequins_view_create( }; let ds = &*(data_source as *const DataSourceImpl); - let backend = match ds { - DataSourceImpl::Local { backend, .. } => Arc::clone(backend), - DataSourceImpl::Remote { .. } => return std::ptr::null_mut(), - }; + let executor = query_executor(ds); let retention = if retention_ns == 0 { 3_600_000_000_000u64 // default: 1 hour @@ -726,7 +968,7 @@ pub unsafe extern "C" fn sequins_view_create( }; let task = RUNTIME.spawn(AssertSend(async move { - let seql_stream = match backend.query_live(&query_str).await { + let seql_stream = match executor.query_live(&query_str).await { Ok(s) => s, Err(e) => { tracing::error!(error = %e, "View query failed"); @@ -978,6 +1220,77 @@ mod tests { // ── SeQL Query FFI Tests ────────────────────────────────────────────────────── + #[test] + fn test_sequins_sql_query_reads_app_state_tables() { + let (data_source, _dir) = create_test_data_source(); + + let mut collector = FrameCollector::default(); + let ctx = &mut collector as *mut _ as *mut c_void; + let vtable = CFrameSinkVTable { + on_schema: Some(on_schema_callback), + on_data: Some(on_data_callback), + on_delta: None, + on_heartbeat: None, + on_complete: Some(on_complete_callback), + on_warning: None, + on_error: Some(on_error_callback), + }; + + // The `conversations` app-state table is registered even when empty, and is + // reachable only via plain SQL (SeQL does not address it). + let sql = CString::new( + "SELECT id, title, updated_at_ns, item_count FROM conversations ORDER BY updated_at_ns DESC", + ) + .unwrap(); + let stream_handle = unsafe { sequins_sql_query(data_source, sql.as_ptr(), vtable, ctx) }; + assert!( + !stream_handle.is_null(), + "SQL stream handle should not be null" + ); + std::thread::sleep(std::time::Duration::from_millis(500)); + + assert_eq!( + collector.error_count, 0, + "read-only SELECT should not error" + ); + assert_eq!( + collector.schema_count, 1, + "should emit exactly one schema frame" + ); + assert!(collector.complete_count > 0, "should emit a complete frame"); + + unsafe { sequins_seql_stream_free(stream_handle) }; + + // A mutating statement must be rejected by the read-only SQL options. + let mut ddl_collector = FrameCollector::default(); + let ddl_ctx = &mut ddl_collector as *mut _ as *mut c_void; + let ddl_vtable = CFrameSinkVTable { + on_schema: Some(on_schema_callback), + on_data: Some(on_data_callback), + on_delta: None, + on_heartbeat: None, + on_complete: Some(on_complete_callback), + on_warning: None, + on_error: Some(on_error_callback), + }; + let ddl = CString::new("CREATE TABLE evil (x INT)").unwrap(); + let ddl_handle = + unsafe { sequins_sql_query(data_source, ddl.as_ptr(), ddl_vtable, ddl_ctx) }; + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!( + ddl_collector.error_count > 0, + "DDL must be rejected read-only" + ); + assert_eq!(ddl_collector.complete_count, 0, "DDL must not complete"); + + unsafe { + if !ddl_handle.is_null() { + sequins_seql_stream_free(ddl_handle); + } + sequins_data_source_free(data_source); + } + } + #[test] fn test_sequins_seql_query_valid_query() { let (data_source, _dir) = create_test_data_source(); diff --git a/crates/sequins-metadata/Cargo.toml b/crates/sequins-metadata/Cargo.toml new file mode 100644 index 00000000..f954fa8b --- /dev/null +++ b/crates/sequins-metadata/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "sequins-metadata" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "Durable app-state store for Sequins — chat conversations and dashboards on the shared object store" + +[dependencies] +object_store = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +async-trait = { workspace = true } +tokio = { workspace = true } +futures = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/crates/sequins-metadata/src/error.rs b/crates/sequins-metadata/src/error.rs new file mode 100644 index 00000000..a40102db --- /dev/null +++ b/crates/sequins-metadata/src/error.rs @@ -0,0 +1,15 @@ +//! Errors for the app-state store. + +/// Result alias for app-state operations. +pub type Result = std::result::Result; + +/// Errors persisting or loading app state. +#[derive(Debug, thiserror::Error)] +pub enum MetadataError { + #[error("object store error: {0}")] + Store(#[from] object_store::Error), + #[error("serialization error: {0}")] + Serde(#[from] serde_json::Error), + #[error("{0}")] + Other(String), +} diff --git a/crates/sequins-metadata/src/lib.rs b/crates/sequins-metadata/src/lib.rs new file mode 100644 index 00000000..b279eaa7 --- /dev/null +++ b/crates/sequins-metadata/src/lib.rs @@ -0,0 +1,18 @@ +//! Durable app-state for Sequins: chat **conversations** and **dashboards**. +//! +//! Conversations are persisted as a byproduct of the standard OpenAI Responses API +//! (`store` + `previous_response_id`); dashboards through a small custom API. Both +//! live as JSON on the same shared object store the cold tier uses — so in Pro they +//! are shared across the team — and are projected into DataFusion tables (by +//! `sequins-datafusion-backend`) so they're queryable by the same engine. + +pub mod error; +pub mod store; +pub mod types; + +pub use error::{MetadataError, Result}; +pub use store::{AppStateStore, DashboardApi}; +pub use types::{ + Conversation, ConversationItem, Dashboard, DashboardRow, Layout, Panel, RowPanel, + SavedVisualization, DEFAULT_ROW_HEIGHT, +}; diff --git a/crates/sequins-metadata/src/store.rs b/crates/sequins-metadata/src/store.rs new file mode 100644 index 00000000..a8d8fe5f --- /dev/null +++ b/crates/sequins-metadata/src/store.rs @@ -0,0 +1,393 @@ +//! [`AppStateStore`] — durable, in-memory-cached store for conversations and +//! dashboards, persisted as JSON on the shared object store. +//! +//! State is held in `RwLock`ed maps for fast reads (and for the DataFusion table +//! providers to snapshot at scan time) with **write-through** to the object store, +//! mirroring how the retention policy and cold-flush watermark are persisted. The +//! object store natively supports overwrite/delete, so app state can mutate even +//! though the telemetry tiers are append-only. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use object_store::path::Path as ObjPath; +use object_store::{ObjectStore, ObjectStoreExt, PutPayload}; +use tokio::sync::RwLock; + +use crate::error::Result; +use crate::types::{Conversation, ConversationItem, Dashboard}; + +fn now_ns() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0) +} + +/// Durable app-state store over an object-store prefix. +pub struct AppStateStore { + store: Arc, + prefix: String, + conversations: RwLock>, + dashboards: RwLock>, + /// `response_id` → `conversation_id`, for resolving `previous_response_id`. + response_index: RwLock>, + seq: AtomicU64, +} + +impl AppStateStore { + /// Build a store over `store` rooted at `prefix` (e.g. `/app_state`). + /// Call [`load`](Self::load) once to hydrate from durable storage. + pub fn new(store: Arc, prefix: impl Into) -> Self { + Self { + store, + prefix: prefix.into().trim_end_matches('/').to_string(), + conversations: RwLock::new(HashMap::new()), + dashboards: RwLock::new(HashMap::new()), + response_index: RwLock::new(HashMap::new()), + seq: AtomicU64::new(0), + } + } + + fn conversation_path(&self, id: &str) -> ObjPath { + ObjPath::from(format!("{}/conversations/{id}.json", self.prefix)) + } + + fn dashboard_path(&self, id: &str) -> ObjPath { + ObjPath::from(format!("{}/dashboards/{id}.json", self.prefix)) + } + + fn next_id(&self, kind: &str) -> String { + let n = self.seq.fetch_add(1, Ordering::Relaxed); + format!("{kind}_{}_{n}", now_ns()) + } + + /// Hydrate the in-memory maps from durable storage. Malformed objects are + /// skipped (logged), never fatal. + pub async fn load(&self) -> Result<()> { + let conv_prefix = ObjPath::from(format!("{}/conversations", self.prefix)); + for location in self.list_locations(&conv_prefix).await? { + match self.get_json::(&location).await { + Ok(conv) => { + let mut idx = self.response_index.write().await; + for item in &conv.items { + if let Some(rid) = &item.response_id { + idx.insert(rid.clone(), conv.id.clone()); + } + } + drop(idx); + self.conversations + .write() + .await + .insert(conv.id.clone(), conv); + } + Err(e) => tracing::warn!(%location, error = %e, "skipping unreadable conversation"), + } + } + + let dash_prefix = ObjPath::from(format!("{}/dashboards", self.prefix)); + for location in self.list_locations(&dash_prefix).await? { + match self.get_json::(&location).await { + Ok(mut dash) => { + dash.migrate_legacy(); + self.dashboards.write().await.insert(dash.id.clone(), dash); + } + Err(e) => tracing::warn!(%location, error = %e, "skipping unreadable dashboard"), + } + } + Ok(()) + } + + async fn list_locations(&self, prefix: &ObjPath) -> Result> { + let mut stream = self.store.list(Some(prefix)); + let mut out = Vec::new(); + while let Some(meta) = stream.next().await { + out.push(meta?.location); + } + Ok(out) + } + + async fn get_json(&self, location: &ObjPath) -> Result { + let bytes = self.store.get(location).await?.bytes().await?; + Ok(serde_json::from_slice(&bytes)?) + } + + async fn put_json(&self, path: &ObjPath, value: &T) -> Result<()> { + let bytes = serde_json::to_vec(value)?; + self.store.put(path, PutPayload::from(bytes)).await?; + Ok(()) + } + + // ---- Conversations ----------------------------------------------------- + + /// Append a Responses turn to a conversation (creating it if needed), then + /// persist. `input_items` (user-supplied, before the turn) then `output_items` + /// (produced by `response_id`) are appended in order. Returns the conversation id. + pub async fn append_response( + &self, + conversation_id: Option, + title: Option, + input_items: Vec, + output_items: Vec, + response_id: String, + ) -> Result { + let now = now_ns(); + let cid = conversation_id.unwrap_or_else(|| self.next_id("conv")); + + let snapshot = { + let mut convs = self.conversations.write().await; + let conv = convs.entry(cid.clone()).or_insert_with(|| Conversation { + id: cid.clone(), + title: title.clone(), + created_at_ns: now, + updated_at_ns: now, + items: Vec::new(), + }); + if conv.title.is_none() { + conv.title = title; + } + let mut position = conv.items.len() as u32; + for mut item in input_items.into_iter().chain(output_items) { + item.position = position; + position += 1; + conv.items.push(item); + } + conv.updated_at_ns = now; + conv.clone() + }; + + self.response_index + .write() + .await + .insert(response_id, cid.clone()); + let path = self.conversation_path(&cid); + self.put_json(&path, &snapshot).await?; + Ok(cid) + } + + /// Resolve a `previous_response_id` to its conversation id. + pub async fn conversation_by_response(&self, response_id: &str) -> Option { + self.response_index.read().await.get(response_id).cloned() + } + + /// Fetch a full conversation by id. + pub async fn get_conversation(&self, id: &str) -> Option { + self.conversations.read().await.get(id).cloned() + } + + /// Snapshot all conversations (for the DataFusion table provider / listing). + pub async fn conversations_snapshot(&self) -> Vec { + self.conversations.read().await.values().cloned().collect() + } + + // ---- Dashboards -------------------------------------------------------- + + /// Snapshot all dashboards (for the DataFusion table provider). + pub async fn dashboards_snapshot(&self) -> Vec { + self.dashboards.read().await.values().cloned().collect() + } + + /// Create or update a dashboard, stamping `id`/timestamps as needed. Returns + /// the stored dashboard (with its id). + pub async fn upsert_dashboard(&self, mut dashboard: Dashboard) -> Result { + dashboard.migrate_legacy(); + let now = now_ns(); + if dashboard.id.is_empty() { + dashboard.id = self.next_id("dash"); + dashboard.created_at_ns = now; + } + dashboard.updated_at_ns = now; + + let stored = { + let mut dbs = self.dashboards.write().await; + if let Some(existing) = dbs.get(&dashboard.id) { + dashboard.created_at_ns = existing.created_at_ns; + } else if dashboard.created_at_ns == 0 { + dashboard.created_at_ns = now; + } + dbs.insert(dashboard.id.clone(), dashboard.clone()); + dashboard + }; + let path = self.dashboard_path(&stored.id); + self.put_json(&path, &stored).await?; + Ok(stored) + } + + /// Delete a dashboard (in-memory + durable). No-op if absent. + pub async fn delete_dashboard(&self, id: &str) -> Result<()> { + self.dashboards.write().await.remove(id); + // Absent object → ignore NotFound. + match self.store.delete(&self.dashboard_path(id)).await { + Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), + Err(e) => Err(e.into()), + } + } + + /// Fetch a dashboard by id. + pub async fn get_dashboard(&self, id: &str) -> Option { + self.dashboards.read().await.get(id).cloned() + } +} + +/// Read/write dashboards. Implemented by [`AppStateStore`] (local) and, elsewhere, +/// by the remote client so the app has one interface across Local and Remote. +#[async_trait] +pub trait DashboardApi: Send + Sync { + async fn list_dashboards(&self) -> Result>; + async fn get_dashboard(&self, id: &str) -> Result>; + async fn save_dashboard(&self, dashboard: Dashboard) -> Result; + async fn delete_dashboard(&self, id: &str) -> Result<()>; +} + +#[async_trait] +impl DashboardApi for AppStateStore { + async fn list_dashboards(&self) -> Result> { + Ok(self.dashboards_snapshot().await) + } + async fn get_dashboard(&self, id: &str) -> Result> { + Ok(AppStateStore::get_dashboard(self, id).await) + } + async fn save_dashboard(&self, dashboard: Dashboard) -> Result { + self.upsert_dashboard(dashboard).await + } + async fn delete_dashboard(&self, id: &str) -> Result<()> { + AppStateStore::delete_dashboard(self, id).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::{DashboardRow, RowPanel, SavedVisualization, DEFAULT_ROW_HEIGHT}; + + fn mem_store() -> Arc { + Arc::new(object_store::memory::InMemory::new()) + } + + fn item(role: &str, text: &str) -> ConversationItem { + ConversationItem { + response_id: None, + position: 0, + role: role.into(), + item_type: "message".into(), + text: Some(text.into()), + tool_name: None, + tool_arguments: None, + tool_output: None, + created_at_ns: 0, + } + } + + #[tokio::test] + async fn conversation_append_and_reload() { + let store = mem_store(); + let s = AppStateStore::new(store.clone(), "app_state"); + let cid = s + .append_response( + None, + Some("Title".into()), + vec![item("user", "hi")], + vec![ConversationItem { + response_id: Some("resp_1".into()), + ..item("assistant", "hello") + }], + "resp_1".into(), + ) + .await + .unwrap(); + + // Second turn resolves the conversation via previous_response_id. + let resolved = s.conversation_by_response("resp_1").await.unwrap(); + assert_eq!(resolved, cid); + s.append_response( + Some(cid.clone()), + None, + vec![item("user", "more")], + vec![ConversationItem { + response_id: Some("resp_2".into()), + ..item("assistant", "sure") + }], + "resp_2".into(), + ) + .await + .unwrap(); + + // Reload from durable storage → same 4 items. + let s2 = AppStateStore::new(store, "app_state"); + s2.load().await.unwrap(); + let conv = s2.get_conversation(&cid).await.unwrap(); + assert_eq!(conv.items.len(), 4); + assert_eq!(conv.items[3].text.as_deref(), Some("sure")); + assert_eq!( + s2.conversation_by_response("resp_2").await.as_deref(), + Some(cid.as_str()) + ); + } + + #[tokio::test] + async fn dashboard_upsert_delete_reload() { + let store = mem_store(); + let s = AppStateStore::new(store.clone(), "app_state"); + let saved = s + .upsert_dashboard(Dashboard { + id: String::new(), + title: "Errors".into(), + created_at_ns: 0, + updated_at_ns: 0, + rows: vec![DashboardRow { + height: DEFAULT_ROW_HEIGHT, + panels: vec![RowPanel { + visualization: SavedVisualization { + seql: "logs last 1h".into(), + title: "Recent logs".into(), + shape: Some("table".into()), + }, + weight: 1.0, + }], + }], + panels: Vec::new(), + }) + .await + .unwrap(); + assert!(!saved.id.is_empty()); + assert_eq!(saved.panel_count(), 1); + + let s2 = AppStateStore::new(store.clone(), "app_state"); + s2.load().await.unwrap(); + assert_eq!(s2.dashboards_snapshot().await.len(), 1); + + s.delete_dashboard(&saved.id).await.unwrap(); + let s3 = AppStateStore::new(store, "app_state"); + s3.load().await.unwrap(); + assert!(s3.dashboards_snapshot().await.is_empty()); + } + + #[test] + fn legacy_panels_migrate_into_rows_grouped_by_y() { + // Old free-grid JSON: two panels on row y=0 (side by side) + one on y=4. + let json = serde_json::json!({ + "id": "d1", "title": "Old", "created_at_ns": 0, "updated_at_ns": 0, + "panels": [ + { "visualization": { "seql": "a", "title": "A" }, "layout": { "x": 0, "y": 0, "w": 6, "h": 4 } }, + { "visualization": { "seql": "b", "title": "B" }, "layout": { "x": 6, "y": 0, "w": 6, "h": 4 } }, + { "visualization": { "seql": "c", "title": "C" }, "layout": { "x": 0, "y": 4, "w": 12, "h": 4 } } + ] + }); + let mut dash: Dashboard = serde_json::from_value(json).unwrap(); + dash.migrate_legacy(); + + assert!(dash.panels.is_empty(), "legacy panels consumed"); + assert_eq!(dash.rows.len(), 2, "two y-groups → two rows"); + assert_eq!(dash.rows[0].panels.len(), 2, "row 0 has both y=0 panels"); + assert_eq!(dash.rows[0].panels[0].weight, 6.0, "weight from old width"); + assert_eq!(dash.rows[1].panels.len(), 1); + assert_eq!(dash.panel_count(), 3); + + // Idempotent. + dash.migrate_legacy(); + assert_eq!(dash.rows.len(), 2); + } +} diff --git a/crates/sequins-metadata/src/types.rs b/crates/sequins-metadata/src/types.rs new file mode 100644 index 00000000..2687b378 --- /dev/null +++ b/crates/sequins-metadata/src/types.rs @@ -0,0 +1,182 @@ +//! App-state model types: chat conversations and dashboards. +//! +//! Conversations are persisted as a byproduct of the standard OpenAI Responses +//! API (`store` + `previous_response_id`): each turn's input and output items are +//! appended as [`ConversationItem`]s. Dashboards are edited through a custom API. +//! Both serialize to JSON on the shared object store and are projected into +//! DataFusion tables for querying. + +use serde::{Deserialize, Serialize}; + +/// A chat conversation — an ordered list of items across one or more turns. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Conversation { + pub id: String, + #[serde(default)] + pub title: Option, + pub created_at_ns: u64, + pub updated_at_ns: u64, + #[serde(default)] + pub items: Vec, +} + +/// A single item in a conversation — a user/assistant/system message, a tool call, +/// or a server-executed tool result. Mirrors the Responses API output item shapes +/// so both plain messages and tool activity round-trip for display and replay. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConversationItem { + /// The response turn that produced this item (`None` for user-supplied input). + #[serde(default)] + pub response_id: Option, + /// Order within the conversation. + pub position: u32, + /// `user` | `assistant` | `system` | `tool`. + pub role: String, + /// `message` | `function_call` | `sequins.tool_result` | … + pub item_type: String, + #[serde(default)] + pub text: Option, + #[serde(default)] + pub tool_name: Option, + /// Tool call arguments as a JSON string. + #[serde(default)] + pub tool_arguments: Option, + /// Rendered tool output (for server-executed tools). + #[serde(default)] + pub tool_output: Option, + pub created_at_ns: u64, +} + +/// Default row height, in points. +pub const DEFAULT_ROW_HEIGHT: f64 = 280.0; + +fn default_row_height() -> f64 { + DEFAULT_ROW_HEIGHT +} + +fn default_weight() -> f64 { + 1.0 +} + +/// A saved dashboard — a titled, ordered stack of full-width [`DashboardRow`]s. +/// +/// The layout is a flexbox of rows: each row has a height and fills the full width, +/// splitting it among its panels by relative weight. Legacy free-grid dashboards +/// (`panels` with `x/y/w/h`) are migrated into rows by [`Dashboard::migrate_legacy`]. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Dashboard { + pub id: String, + pub title: String, + pub created_at_ns: u64, + pub updated_at_ns: u64, + #[serde(default)] + pub rows: Vec, + /// Legacy free-grid panels — read from old stored dashboards, migrated into + /// `rows`, and never re-serialized once migrated. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub panels: Vec, +} + +impl Dashboard { + /// Total number of panels across all rows. + pub fn panel_count(&self) -> usize { + self.rows.iter().map(|r| r.panels.len()).sum() + } + + /// Convert any legacy `panels` (free x/y/w/h grid) into `rows`: panels are grouped + /// into rows by their `y`, ordered left-to-right by `x`, with each panel's width + /// `w` becoming its row weight. Idempotent; a no-op once migrated. + pub fn migrate_legacy(&mut self) { + if self.panels.is_empty() { + return; + } + let mut legacy = std::mem::take(&mut self.panels); + legacy.sort_by_key(|p| (p.layout.y, p.layout.x)); + let mut rows: Vec = Vec::new(); + let mut current_y: Option = None; + for p in legacy { + let weight = if p.layout.w == 0 { + 1.0 + } else { + p.layout.w as f64 + }; + let row_panel = RowPanel { + visualization: p.visualization, + weight, + }; + if current_y == Some(p.layout.y) { + rows.last_mut().unwrap().panels.push(row_panel); + } else { + current_y = Some(p.layout.y); + rows.push(DashboardRow { + height: DEFAULT_ROW_HEIGHT, + panels: vec![row_panel], + }); + } + } + // Prepend migrated rows before any rows that already exist (there shouldn't be). + rows.append(&mut self.rows); + self.rows = rows; + } +} + +/// A full-width dashboard row: a fixed height and an ordered set of panels that split +/// the width by weight. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DashboardRow { + /// Row height in points. + #[serde(default = "default_row_height")] + pub height: f64, + #[serde(default)] + pub panels: Vec, +} + +impl Default for DashboardRow { + fn default() -> Self { + Self { + height: DEFAULT_ROW_HEIGHT, + panels: Vec::new(), + } + } +} + +/// A panel within a row: a saved visualization and its relative width weight. The row +/// normalizes weights across its panels to fill the full width. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RowPanel { + pub visualization: SavedVisualization, + #[serde(default = "default_weight")] + pub weight: f64, +} + +/// A legacy free-grid panel: a saved visualization plus its old `x/y/w/h` layout. +/// Retained only to deserialize and migrate older dashboards. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Panel { + pub visualization: SavedVisualization, + #[serde(default)] + pub layout: Layout, +} + +/// A visualization the app can re-render: a SeQL query, a title, and an optional +/// requested `ResponseShape` (as its `as_str()` form, e.g. `"timeseries"`). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SavedVisualization { + pub seql: String, + pub title: String, + #[serde(default)] + pub shape: Option, +} + +/// Legacy grid placement of a panel within a dashboard (pre-rows layout). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Layout { + #[serde(default)] + pub x: u32, + #[serde(default)] + pub y: u32, + #[serde(default)] + pub w: u32, + #[serde(default)] + pub h: u32, +} diff --git a/crates/sequins-storage/Cargo.toml b/crates/sequins-storage/Cargo.toml index addd63d4..f9f44a22 100644 --- a/crates/sequins-storage/Cargo.toml +++ b/crates/sequins-storage/Cargo.toml @@ -17,6 +17,7 @@ sequins-wal = { workspace = true } sequins-live-query = { workspace = true } sequins-hot-tier = { workspace = true } sequins-cold-tier = { workspace = true } +sequins-metadata = { workspace = true } # Arrow + DataFusion arrow = { workspace = true } diff --git a/crates/sequins-storage/src/storage/accessors.rs b/crates/sequins-storage/src/storage/accessors.rs index 79c17e74..bb05a27b 100644 --- a/crates/sequins-storage/src/storage/accessors.rs +++ b/crates/sequins-storage/src/storage/accessors.rs @@ -33,6 +33,13 @@ impl Storage { &self.wal } + /// The durable app-state store (chat conversations + dashboards). Shared with + /// the DataFusion backend (to project it into queryable tables) and the + /// assistant's Responses endpoint (to persist conversations). + pub fn app_state(&self) -> &Arc { + &self.app_state + } + /// Get the live query broadcast sender (for publishing RecordBatches to live subscribers) pub fn live_broadcast_tx(&self) -> broadcast::Sender<(Signal, Arc)> { self.live_broadcast.clone() diff --git a/crates/sequins-storage/src/storage/app_state.rs b/crates/sequins-storage/src/storage/app_state.rs new file mode 100644 index 00000000..57408fec --- /dev/null +++ b/crates/sequins-storage/src/storage/app_state.rs @@ -0,0 +1,26 @@ +//! `DashboardApi` for [`Storage`] — delegates to the durable [`AppStateStore`]. +//! +//! This is the **local** implementation of the dashboard interface; the remote +//! client implements the same trait over HTTP so the app has one interface. + +use super::Storage; +use sequins_metadata::{Dashboard, DashboardApi, Result as MetaResult}; + +#[async_trait::async_trait] +impl DashboardApi for Storage { + async fn list_dashboards(&self) -> MetaResult> { + Ok(self.app_state.dashboards_snapshot().await) + } + + async fn get_dashboard(&self, id: &str) -> MetaResult> { + Ok(self.app_state.get_dashboard(id).await) + } + + async fn save_dashboard(&self, dashboard: Dashboard) -> MetaResult { + self.app_state.upsert_dashboard(dashboard).await + } + + async fn delete_dashboard(&self, id: &str) -> MetaResult<()> { + self.app_state.delete_dashboard(id).await + } +} diff --git a/crates/sequins-storage/src/storage/constructor.rs b/crates/sequins-storage/src/storage/constructor.rs index a548ba77..da897533 100644 --- a/crates/sequins-storage/src/storage/constructor.rs +++ b/crates/sequins-storage/src/storage/constructor.rs @@ -55,8 +55,22 @@ impl Storage { let ct = cold_tier_ref.read().await; match ct.write_signal(signal, (*batch).clone()).await { Ok(()) => true, + // Permanent: the cold format can't encode this batch's schema + // (e.g. a Map column). Retrying never helps, so report success + // to EVICT it from the hot tier — otherwise it accumulates + // forever and OOM-kills the process. Data is dropped (logged). + Err(e) if e.is_unsupported_for_cold() => { + tracing::warn!( + "dropping {:?} batch that cold storage cannot encode \ + (not persisted): {}", + signal, + e + ); + true + } + // Transient (I/O, etc.): retain so it retries on the next pass. Err(e) => { - tracing::error!("cold flush for {:?} failed: {}", signal, e); + tracing::error!("cold flush for {:?} failed (retained): {}", signal, e); false } } @@ -74,6 +88,25 @@ impl Storage { // Load persisted retention policy from object storage if it exists. let retention_policy = Self::load_retention_policy(&store, &config.cold_tier.uri).await?; + // App state (conversations + dashboards) lives under a *shared* `app_state` + // prefix of the cold root (no node id) so the whole cluster/team sees the + // same dashboards and conversations. Hydrate it from durable storage. + let app_base = + sequins_cold_tier::store_base_path(&config.cold_tier.uri).trim_end_matches('/'); + let app_state_prefix = if app_base.is_empty() { + "app_state".to_string() + } else { + format!("{app_base}/app_state") + }; + let app_state = Arc::new(sequins_metadata::AppStateStore::new( + store.clone(), + app_state_prefix, + )); + app_state + .load() + .await + .map_err(|e| crate::error::Error::Storage(format!("Failed to load app state: {e}")))?; + // Initialize the WAL under this node's private sub-prefix of the shared // cold root (bucket-relative for s3://gs://az://, the local path for // file://). Mirrors the watermark path in `checkpoint`. @@ -107,6 +140,7 @@ impl Storage { live_query_manager, shutdown_notify: Arc::new(tokio::sync::Notify::new()), retention_policy: Arc::new(RwLock::new(retention_policy)), + app_state, clock, replay_seq: std::sync::atomic::AtomicU64::new(0), }; diff --git a/crates/sequins-storage/src/storage/mod.rs b/crates/sequins-storage/src/storage/mod.rs index e03fc233..6931b8f1 100644 --- a/crates/sequins-storage/src/storage/mod.rs +++ b/crates/sequins-storage/src/storage/mod.rs @@ -13,6 +13,7 @@ use tokio::sync::RwLock; // Module declarations mod accessors; +mod app_state; mod background; mod checkpoint; mod constructor; @@ -40,6 +41,10 @@ pub struct Storage { pub(super) shutdown_notify: Arc, /// Persisted retention policy (overrides config defaults) pub(super) retention_policy: Arc>>, + /// Durable app-state (chat conversations + dashboards) on the shared object + /// store — shared across the cluster like the cold tier, so Pro teams share + /// dashboards and conversations. + pub(super) app_state: Arc, /// Wall-clock time provider (injectable for deterministic testing) pub(crate) clock: Arc, /// WAL sequence to use for the entry currently being replayed on startup. diff --git a/crates/sequins-traits/src/query.rs b/crates/sequins-traits/src/query.rs index 20eb8dc2..b944025c 100644 --- a/crates/sequins-traits/src/query.rs +++ b/crates/sequins-traits/src/query.rs @@ -50,6 +50,17 @@ pub type SeqlStream = Pin> pub trait QueryApi: Send + Sync { /// Execute a SeQL query string and return a FlightData stream async fn query(&self, seql: &str) -> Result; + + /// Execute a **read-only** plain SQL query (SELECT only) and return a framed + /// `FlightData` stream (shape `Table`). Used to read the app-state tables + /// (`conversations`/`messages`/`dashboards`) and other DataFusion tables that + /// SeQL does not address. The default errors; backends that support SQL override it. + async fn sql(&self, sql: &str) -> Result { + let _ = sql; + Err(QueryError::UnsupportedStage { + stage: "raw SQL".to_string(), + }) + } } /// Server-side query executor (executes pre-compiled Substrait plans) @@ -57,4 +68,14 @@ pub trait QueryApi: Send + Sync { pub trait QueryExec: Send + Sync { /// Execute a Substrait Plan (with SeqlExtension) and return a FlightData stream async fn execute(&self, plan_bytes: Vec) -> Result; + + /// Execute a **read-only** plain SQL query and return a framed `FlightData` + /// stream. Backs the Flight SQL `CommandStatementQuery` path. The default + /// errors; executors that support SQL override it. + async fn execute_sql(&self, sql: String) -> Result { + let _ = sql; + Err(QueryError::UnsupportedStage { + stage: "raw SQL".to_string(), + }) + } } From 6a2490097ec0f013a5fa523f6b1e7b5cf09683e5 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 16 Jul 2026 22:08:26 +0800 Subject: [PATCH 02/10] feat(macos): assistant chat, visualizations & dashboards, fixes - Assistant chat UI: markdown message bubbles, grouped tool-activity blocks, conversation persistence via app-state SQL (SQLQueryAPI self-retaining collector fix so async chat loads complete). - Visualization + dashboards: VizFormat/VizType, render_visualization & add_to_dashboard client tools, draggable dashboard grid with insertion-bar drop targeting, area-chart fill interpolation fix. - KeychainStore for the per-environment assistant secret; environment editor for remote query/management/assistant URLs (path-less Flight origin defaults). - Fix HistogramLine.recomputeMaxActiveBucket() crash: guard the `1.. --- .../Models/ConnectionEnvironment.swift | 14 +- apps/macos/Sequins/SequinsApp.swift | 11 + .../Sequins/Services/KeychainStore.swift | 66 +++ .../ViewModels/AppStateViewModel.swift | 27 + .../ViewModels/AssistantViewModel.swift | 330 ++++++++++++ .../ViewModels/DashboardsViewModel.swift | 176 ++++++ .../Assistant/AssistantContentView.swift | 77 +++ .../Views/Assistant/ChatInputBar.swift | 45 ++ .../Views/Assistant/ChatListPanel.swift | 67 +++ .../Views/Assistant/ChatMessageRow.swift | 120 +++++ .../Views/Assistant/ChatTranscriptView.swift | 102 ++++ .../Assistant/InlineVisualizationCard.swift | 61 +++ .../Views/Assistant/MarkdownText.swift | 193 +++++++ .../Dashboards/AddToDashboardSheet.swift | 108 ++++ .../Views/Dashboards/ChartEditorSheet.swift | 149 ++++++ .../Views/Dashboards/DashboardGridView.swift | 499 ++++++++++++++++++ .../Views/Dashboards/DashboardListPanel.swift | 88 +++ .../Dashboards/DashboardsContentView.swift | 72 +++ .../Views/Explore/ExploreScalarView.swift | 48 +- .../Views/Explore/ExploreTimeSeriesView.swift | 58 +- .../macos/Sequins/Views/Main/MainWindow.swift | 35 +- .../Sequins/Views/Main/UnifiedFilterBar.swift | 4 + .../Views/Settings/AddEnvironmentView.swift | 19 +- .../Views/Settings/EditEnvironmentView.swift | 56 +- .../Views/Visualization/DataTableView.swift | 117 ++++ .../Views/Visualization/TimeSeriesChart.swift | 182 +++++++ .../Views/Visualization/TraceVizView.swift | 100 ++++ .../Visualization/VisualizationRunner.swift | 115 ++++ .../Visualization/VisualizationView.swift | 159 ++++++ .../Views/Visualization/VizCharts.swift | 300 +++++++++++ .../Sequins/Views/Visualization/VizData.swift | 63 +++ .../Views/Visualization/VizTypePicker.swift | 35 ++ .../Sources/SequinsData/AssistantAPI.swift | 276 ++++++++++ .../Sources/SequinsData/DashboardStore.swift | 226 ++++++++ .../SequinsData/Models/HistogramLine.swift | 6 + .../Sources/SequinsData/RecordBatchTree.swift | 9 + .../Sources/SequinsData/SQLQueryAPI.swift | 220 ++++++++ .../Sources/SequinsData/TimeRange.swift | 94 ++++ .../Sources/SequinsData/VizFormat.swift | 184 +++++++ .../Sources/SequinsData/VizType.swift | 107 ++++ .../SequinsDataTests/DashboardVizTests.swift | 82 +++ .../SequinsDataTests/HistogramLineTests.swift | 77 +++ .../SequinsDataTests/TimeRangeSeQLTests.swift | 57 ++ .../SequinsDataTests/VizFormatTests.swift | 66 +++ apps/macos/build-ffi.sh | 44 ++ 45 files changed, 4863 insertions(+), 81 deletions(-) create mode 100644 apps/macos/Sequins/Services/KeychainStore.swift create mode 100644 apps/macos/Sequins/ViewModels/AssistantViewModel.swift create mode 100644 apps/macos/Sequins/ViewModels/DashboardsViewModel.swift create mode 100644 apps/macos/Sequins/Views/Assistant/AssistantContentView.swift create mode 100644 apps/macos/Sequins/Views/Assistant/ChatInputBar.swift create mode 100644 apps/macos/Sequins/Views/Assistant/ChatListPanel.swift create mode 100644 apps/macos/Sequins/Views/Assistant/ChatMessageRow.swift create mode 100644 apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift create mode 100644 apps/macos/Sequins/Views/Assistant/InlineVisualizationCard.swift create mode 100644 apps/macos/Sequins/Views/Assistant/MarkdownText.swift create mode 100644 apps/macos/Sequins/Views/Dashboards/AddToDashboardSheet.swift create mode 100644 apps/macos/Sequins/Views/Dashboards/ChartEditorSheet.swift create mode 100644 apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift create mode 100644 apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift create mode 100644 apps/macos/Sequins/Views/Dashboards/DashboardsContentView.swift create mode 100644 apps/macos/Sequins/Views/Visualization/DataTableView.swift create mode 100644 apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift create mode 100644 apps/macos/Sequins/Views/Visualization/TraceVizView.swift create mode 100644 apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift create mode 100644 apps/macos/Sequins/Views/Visualization/VisualizationView.swift create mode 100644 apps/macos/Sequins/Views/Visualization/VizCharts.swift create mode 100644 apps/macos/Sequins/Views/Visualization/VizData.swift create mode 100644 apps/macos/Sequins/Views/Visualization/VizTypePicker.swift create mode 100644 apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift create mode 100644 apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift create mode 100644 apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift create mode 100644 apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift create mode 100644 apps/macos/SequinsData/Sources/SequinsData/VizType.swift create mode 100644 apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift create mode 100644 apps/macos/SequinsData/Tests/SequinsDataTests/HistogramLineTests.swift create mode 100644 apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift create mode 100644 apps/macos/SequinsData/Tests/SequinsDataTests/VizFormatTests.swift create mode 100755 apps/macos/build-ffi.sh diff --git a/apps/macos/Sequins/Models/ConnectionEnvironment.swift b/apps/macos/Sequins/Models/ConnectionEnvironment.swift index 0233db9f..13ceff26 100644 --- a/apps/macos/Sequins/Models/ConnectionEnvironment.swift +++ b/apps/macos/Sequins/Models/ConnectionEnvironment.swift @@ -18,6 +18,14 @@ final class ConnectionEnvironment { var remoteQueryURL: String? var remoteManagementURL: String? + // Assistant (AI) settings — the API key / bearer token is stored in the Keychain + // (keyed by this environment's id), NOT here. + /// Local: the OpenAI-compatible provider base URL (nil = api.openai.com). + /// Remote: the daemon's assistant `/v1` base URL (e.g. `http://host:8082/v1`). + var assistantBaseURL: String? + /// The model id to use (required for local; optional for remote). + var assistantModel: String? + init( id: UUID = UUID(), name: String, @@ -27,7 +35,9 @@ final class ConnectionEnvironment { grpcPort: Int? = nil, httpPort: Int? = nil, remoteQueryURL: String? = nil, - remoteManagementURL: String? = nil + remoteManagementURL: String? = nil, + assistantBaseURL: String? = nil, + assistantModel: String? = nil ) { self.id = id self.name = name @@ -39,6 +49,8 @@ final class ConnectionEnvironment { self.httpPort = httpPort self.remoteQueryURL = remoteQueryURL self.remoteManagementURL = remoteManagementURL + self.assistantBaseURL = assistantBaseURL + self.assistantModel = assistantModel } /// The fixed UUID for the local environment - never changes diff --git a/apps/macos/Sequins/SequinsApp.swift b/apps/macos/Sequins/SequinsApp.swift index 2881249b..d4b542ac 100644 --- a/apps/macos/Sequins/SequinsApp.swift +++ b/apps/macos/Sequins/SequinsApp.swift @@ -39,6 +39,17 @@ struct SequinsApp: App { // Set up notification service setupNotifications(appState: state) + + // Demo/QA hook: auto-open the main window on launch when requested, so the + // menu-bar app can be driven headlessly. No-op unless the env var is set. + if let tabName = ProcessInfo.processInfo.environment["SEQUINS_AUTO_OPEN_WINDOW"] { + let tab = NavigationItem(rawValue: tabName) ?? .assistant + let launchState = state + DispatchQueue.main.async { + MainWindowController.shared.showWindow(appState: launchState, selectedTab: tab) + NSApp.activate(ignoringOtherApps: true) + } + } } private func setupNotifications(appState: AppStateViewModel) { diff --git a/apps/macos/Sequins/Services/KeychainStore.swift b/apps/macos/Sequins/Services/KeychainStore.swift new file mode 100644 index 00000000..c56f9e0a --- /dev/null +++ b/apps/macos/Sequins/Services/KeychainStore.swift @@ -0,0 +1,66 @@ +import Foundation +import Security + +/// Minimal macOS Keychain wrapper for the assistant's per-environment secret (the LLM +/// API key for local, or the bearer token for remote). Secrets are keyed by the +/// environment's UUID so each environment has its own credential. +struct KeychainStore { + static let shared = KeychainStore() + + private let service = "com.sequins.assistant" + + private init() {} + + private func account(for environmentId: UUID) -> String { + "assistant-secret-\(environmentId.uuidString)" + } + + /// Read the assistant secret for an environment, or `nil` if unset. + func assistantSecret(environmentId: UUID) -> String? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account(for: environmentId), + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne, + ] + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + guard status == errSecSuccess, + let data = item as? Data, + let value = String(data: data, encoding: .utf8), + !value.isEmpty + else { return nil } + return value + } + + /// Store (or clear, when `secret` is nil/empty) the assistant secret for an environment. + @discardableResult + func setAssistantSecret(_ secret: String?, environmentId: UUID) -> Bool { + let account = account(for: environmentId) + let base: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + + // Clearing. + guard let secret, !secret.isEmpty else { + let status = SecItemDelete(base as CFDictionary) + return status == errSecSuccess || status == errSecItemNotFound + } + + let data = Data(secret.utf8) + // Update if present, else add. + let attributes: [String: Any] = [kSecValueData as String: data] + let updateStatus = SecItemUpdate(base as CFDictionary, attributes as CFDictionary) + if updateStatus == errSecSuccess { return true } + if updateStatus == errSecItemNotFound { + var addQuery = base + addQuery[kSecValueData as String] = data + addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock + return SecItemAdd(addQuery as CFDictionary, nil) == errSecSuccess + } + return false + } +} diff --git a/apps/macos/Sequins/ViewModels/AppStateViewModel.swift b/apps/macos/Sequins/ViewModels/AppStateViewModel.swift index 41fde1e2..cb5a48e0 100644 --- a/apps/macos/Sequins/ViewModels/AppStateViewModel.swift +++ b/apps/macos/Sequins/ViewModels/AppStateViewModel.swift @@ -63,6 +63,29 @@ final class AppStateViewModel { timeRangeState.setCustomRange(start: start, end: end) } + /// Build the assistant's LLM/daemon config from the selected environment plus the + /// Keychain-stored secret. Returns `nil` when the assistant is not configured for + /// the current environment (so the UI can prompt the user to set it up). + /// + /// - Local: needs a model + API key (base URL optional → api.openai.com). + /// - Remote: needs the daemon `/v1` base URL + a bearer token. + func assistantConfig() -> AssistantConfig? { + if let env = environmentManager.selectedEnvironment { + let secret = KeychainStore.shared.assistantSecret(environmentId: env.id) + let base = env.assistantBaseURL?.isEmpty == false ? env.assistantBaseURL : nil + let model = env.assistantModel?.isEmpty == false ? env.assistantModel : nil + if let secret, !secret.isEmpty { + if env.isLocal, let model { + return AssistantConfig(baseURL: base, model: model, apiKey: secret) + } else if !env.isLocal, let base { + return AssistantConfig(baseURL: base, model: model, apiKey: secret) + } + } + } + // Dev/CI fallback: OPENAI_* environment variables (mirrors the daemon). + return AssistantConfig.fromProcessEnvironment() + } + init() { // Don't initialize data source in init - let it happen lazily // This prevents crashes during app startup @@ -204,6 +227,8 @@ enum NavigationItem: String, CaseIterable, Identifiable { case logs = "Logs" case profiles = "Profiles" case explore = "Explore" + case assistant = "Assistant" + case dashboards = "Dashboards" var id: String { rawValue } @@ -215,6 +240,8 @@ enum NavigationItem: String, CaseIterable, Identifiable { case .logs: return "doc.text" case .profiles: return "flame" case .explore: return "terminal" + case .assistant: return "bubble.left.and.text.bubble.right" + case .dashboards: return "square.grid.2x2" } } } diff --git a/apps/macos/Sequins/ViewModels/AssistantViewModel.swift b/apps/macos/Sequins/ViewModels/AssistantViewModel.swift new file mode 100644 index 00000000..7529588e --- /dev/null +++ b/apps/macos/Sequins/ViewModels/AssistantViewModel.swift @@ -0,0 +1,330 @@ +import Foundation +import SwiftUI +import SequinsData + +/// A lightweight summary of a persisted conversation (read from the `conversations` +/// DataFusion table via SQL). +struct ConversationSummary: Identifiable, Hashable { + let id: String + let title: String? + let updatedAtNs: UInt64 + let itemCount: Int + + init?(row: [Any?]) { + guard let id = row.first.flatMap({ $0 as? String }) else { return nil } + self.id = id + self.title = row.count > 1 ? row[1] as? String : nil + self.updatedAtNs = row.count > 2 ? ((row[2] as? NSNumber)?.uint64Value ?? 0) : 0 + self.itemCount = row.count > 3 ? ((row[3] as? NSNumber)?.intValue ?? 0) : 0 + } + + var displayTitle: String { + if let title, !title.isEmpty { return title } + return "Untitled chat" + } +} + +/// One rendered item in a chat transcript. +struct ChatItem: Identifiable { + enum Kind { + case userText(String) + case assistantText(String) + case toolActivity(AssistantToolActivity) + case visualization(SavedVisualization) + } + let id: UUID + var kind: Kind + init(id: UUID = UUID(), kind: Kind) { + self.id = id + self.kind = kind + } +} + +/// Drives the Assistant chat tab: the conversation list, the active transcript, and a +/// streaming turn. Conversation history is read from the `messages`/`conversations` +/// tables via SQL; turns are sent through the normalized assistant FFI. +@MainActor +@Observable +final class AssistantViewModel { + private(set) var conversations: [ConversationSummary] = [] + private(set) var transcript: [ChatItem] = [] + private(set) var isStreaming = false + var selectedConversationId: String? + var inputText: String = "" + var errorMessage: String? + + private var activeStream: AssistantChatStream? + private var assistant: Assistant? + private var assistantConfigKey: String? + private var lastResponseId: String? + + // MARK: - Conversation list + + func refreshConversations(dataSource: DataSource) { + dataSource.fetchAppStateSQL( + "SELECT id, title, updated_at_ns, item_count FROM conversations ORDER BY updated_at_ns DESC" + ) { [weak self] result in + guard let self else { return } + switch result { + case .success(let payload): + self.conversations = payload.rows.compactMap { ConversationSummary(row: $0) } + case .failure(let error): + self.errorMessage = error.localizedDescription + } + } + } + + // MARK: - Open / new + + func openConversation(_ id: String, dataSource: DataSource) { + selectedConversationId = id + transcript = [] + lastResponseId = nil + errorMessage = nil + let escaped = id.replacingOccurrences(of: "'", with: "''") + let sql = """ + SELECT role, item_type, text, tool_name, tool_arguments, tool_output, response_id, position \ + FROM messages WHERE conversation_id = '\(escaped)' ORDER BY position + """ + dataSource.fetchAppStateSQL(sql) { [weak self] result in + guard let self else { return } + guard case .success(let payload) = result else { + if case .failure(let error) = result { self.errorMessage = error.localizedDescription } + return + } + self.transcript = payload.rows.compactMap { self.chatItem(fromMessageRow: $0) } + self.lastResponseId = payload.rows + .compactMap { $0.count > 6 ? $0[6] as? String : nil } + .last + } + } + + func newChat() { + activeStream?.cancel() + activeStream = nil + selectedConversationId = nil + transcript = [] + lastResponseId = nil + isStreaming = false + errorMessage = nil + } + + // MARK: - Sending + + func send(dataSource: DataSource, config: AssistantConfig) { + let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty, !isStreaming else { return } + inputText = "" + errorMessage = nil + transcript.append(ChatItem(kind: .userText(text))) + isStreaming = true + + do { + let assistant = try makeOrReuseAssistant(dataSource: dataSource, config: config) + let request = buildRequestJSON(userText: text, model: config.model) + let stream = try assistant.chat(requestJSON: request) + stream.onText = { [weak self] delta in self?.appendTextDelta(delta) } + stream.onToolActivity = { [weak self] activity in + self?.transcript.append(ChatItem(kind: .toolActivity(activity))) + } + stream.onToolCall = { [weak self] call in + guard let self else { return } + switch call.name { + case "render_visualization": + if let viz = self.parseVisualization(from: call.arguments) { + self.transcript.append(ChatItem(kind: .visualization(viz))) + } + case "add_to_dashboard": + self.handleAddToDashboard(arguments: call.arguments, dataSource: dataSource) + default: + break + } + } + stream.onDone = { [weak self] responseId, conversationId in + self?.handleDone(responseId: responseId, conversationId: conversationId, dataSource: dataSource) + } + activeStream = stream + } catch { + errorMessage = error.localizedDescription + isStreaming = false + } + } + + func cancelStreaming() { + activeStream?.cancel() + activeStream = nil + isStreaming = false + } + + // MARK: - Internals + + private func makeOrReuseAssistant(dataSource: DataSource, config: AssistantConfig) throws -> Assistant { + let key = "\(config.baseURL ?? "")|\(config.model ?? "")|\(config.apiKey?.isEmpty == false)" + if let assistant, assistantConfigKey == key { + return assistant + } + let created = try dataSource.makeAssistant(config) + assistant = created + assistantConfigKey = key + return created + } + + private func handleDone(responseId: String?, conversationId: String?, dataSource: DataSource) { + lastResponseId = responseId + if let conversationId { selectedConversationId = conversationId } + isStreaming = false + activeStream = nil + refreshConversations(dataSource: dataSource) + } + + private func appendTextDelta(_ delta: String) { + if let last = transcript.last, case .assistantText(let existing) = last.kind { + transcript[transcript.count - 1] = ChatItem(id: last.id, kind: .assistantText(existing + delta)) + } else { + transcript.append(ChatItem(kind: .assistantText(delta))) + } + } + + private func chatItem(fromMessageRow row: [Any?]) -> ChatItem? { + func str(_ i: Int) -> String? { i < row.count ? row[i] as? String : nil } + let role = str(0) ?? "" + let itemType = str(1) ?? "message" + switch itemType { + case "message": + guard let text = str(2), !text.isEmpty else { return nil } + return role == "user" + ? ChatItem(kind: .userText(text)) + : ChatItem(kind: .assistantText(text)) + case "sequins.tool_result": + return ChatItem(kind: .toolActivity(AssistantToolActivity( + name: str(3) ?? "", arguments: str(4) ?? "", output: str(5) ?? ""))) + case "function_call": + if str(3) == "render_visualization", let viz = parseVisualization(from: str(4) ?? "") { + return ChatItem(kind: .visualization(viz)) + } + return ChatItem(kind: .toolActivity(AssistantToolActivity( + name: str(3) ?? "", arguments: str(4) ?? "", output: ""))) + default: + return nil + } + } + + /// Handle an `add_to_dashboard` tool call: find the named dashboard (or create it) + /// and append the visualization as a new full-width row, then persist. + private func handleAddToDashboard(arguments: String, dataSource: DataSource) { + guard let viz = parseVisualization(from: arguments), + let obj = jsonObject(arguments) else { return } + let dashboardName = (obj["dashboard"] as? String) + ?? (obj["dashboard_name"] as? String) + ?? "Assistant" + do { + let existing = try dataSource.listDashboards() + var dashboard = existing.first { $0.title.caseInsensitiveCompare(dashboardName) == .orderedSame } + ?? Dashboard(title: dashboardName) + dashboard.rows.append(DashboardRow(panels: [RowPanel(visualization: viz)])) + _ = try dataSource.saveDashboard(dashboard) + // Show the chart inline plus a confirmation of where it went. + transcript.append(ChatItem(kind: .visualization(viz))) + transcript.append(ChatItem(kind: .toolActivity(AssistantToolActivity( + name: "add_to_dashboard", + arguments: arguments, + output: "Added “\(viz.title)” to dashboard “\(dashboardName)”.")))) + } catch { + errorMessage = error.localizedDescription + } + } + + private func jsonObject(_ json: String) -> [String: Any]? { + guard let data = json.data(using: .utf8) else { return nil } + return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + } + + /// Parse `render_visualization` arguments (`{ query|seql, title, chart_type? }`) + /// into a `SavedVisualization`. + func parseVisualization(from argsJSON: String) -> SavedVisualization? { + guard let data = argsJSON.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + else { return nil } + let seql = (obj["query"] as? String) ?? (obj["seql"] as? String) ?? "" + guard !seql.isEmpty else { return nil } + let title = (obj["title"] as? String) ?? "Visualization" + let shape = (obj["chart_type"] as? String) ?? (obj["shape"] as? String) + return SavedVisualization(seql: seql, title: title, shape: shape) + } + + private func buildRequestJSON(userText: String, model: String?) -> String { + var req: [String: Any] = [ + "model": model ?? "default", + "input": [["type": "message", "role": "user", "content": userText]], + "stream": true, + "store": true, + "tools": [renderVisualizationTool, addToDashboardTool], + ] + if let lastResponseId { + req["previous_response_id"] = lastResponseId + } + let data = (try? JSONSerialization.data(withJSONObject: req)) ?? Data("{}".utf8) + return String(decoding: data, as: UTF8.self) + } + + private var renderVisualizationTool: [String: Any] { + [ + "name": "render_visualization", + "description": "Render a chart, table, or other visualization in the client UI from a " + + "SeQL query. Call this whenever the user would benefit from seeing data plotted.", + "parameters": [ + "type": "object", + "properties": [ + "query": [ + "type": "string", + "description": "The SeQL query whose results should be visualized.", + ], + "title": [ + "type": "string", + "description": "A short, descriptive title for the visualization.", + ], + "chart_type": [ + "type": "string", + "enum": VizType.allCases.map { $0.rawValue }, + "description": "Optional chart type. Omit to let the client choose.", + ], + ], + "required": ["query", "title"], + ], + ] + } + + private var addToDashboardTool: [String: Any] { + [ + "name": "add_to_dashboard", + "description": "Save a visualization to a dashboard (by name). If a dashboard with " + + "that name exists the chart is appended as a new row; otherwise a new dashboard " + + "with that name is created. Use this when the user asks to add a chart to, or " + + "build, a dashboard — as opposed to render_visualization which only shows a chart " + + "inline in the chat.", + "parameters": [ + "type": "object", + "properties": [ + "query": [ + "type": "string", + "description": "The SeQL query whose results the chart shows.", + ], + "title": [ + "type": "string", + "description": "A short, descriptive title for the chart.", + ], + "dashboard": [ + "type": "string", + "description": "Name of the dashboard to add the chart to (created if missing).", + ], + "chart_type": [ + "type": "string", + "enum": VizType.allCases.map { $0.rawValue }, + "description": "Optional chart type. Omit to let the client choose.", + ], + ], + "required": ["query", "title", "dashboard"], + ], + ] + } +} diff --git a/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift b/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift new file mode 100644 index 00000000..0379128e --- /dev/null +++ b/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift @@ -0,0 +1,176 @@ +import Foundation +import SwiftUI +import SequinsData + +/// Drives the Dashboards tab: the dashboard list, the selected dashboard's working +/// copy, and row/panel edits (resize rows, adjust panel ratios, add/remove/configure +/// panels, add rows) persisted via the dashboard FFI. +@MainActor +@Observable +final class DashboardsViewModel { + private(set) var dashboards: [Dashboard] = [] + var selectedDashboardId: String? + /// A mutable working copy of the selected dashboard (edited in place). + var selected: Dashboard? + var errorMessage: String? + + // MARK: - List / selection + + func refresh(dataSource: DataSource) { + do { + dashboards = try dataSource.listDashboards() + if let id = selectedDashboardId { + selected = dashboards.first { $0.id == id } + } else { + selected = nil + } + } catch { + errorMessage = error.localizedDescription + } + } + + func select(_ id: String) { + selectedDashboardId = id + selected = dashboards.first { $0.id == id } + } + + func createDashboard(title: String, dataSource: DataSource) { + do { + let name = title.trimmingCharacters(in: .whitespaces) + let saved = try dataSource.saveDashboard(Dashboard(title: name.isEmpty ? "New Dashboard" : name)) + refresh(dataSource: dataSource) + select(saved.id) + } catch { + errorMessage = error.localizedDescription + } + } + + func deleteSelected(dataSource: DataSource) { + guard let id = selectedDashboardId else { return } + do { + try dataSource.deleteDashboard(id: id) + selectedDashboardId = nil + selected = nil + refresh(dataSource: dataSource) + } catch { + errorMessage = error.localizedDescription + } + } + + // MARK: - Row / panel edits + // + // During an active drag, pass `persist: false` (updates the working copy only, so + // the gesture stays smooth); on drag/edit end pass `persist: true` to save. + + /// Set a row's height (row-resize drag). + func setRowHeight(_ rowIndex: Int, height: Double, persist: Bool, dataSource: DataSource) { + guard var d = selected, d.rows.indices.contains(rowIndex) else { return } + d.rows[rowIndex].height = max(120, height) + commit(d, persist: persist, dataSource: dataSource) + } + + /// Replace the weights of a row's panels (ratio drag between two panels). + func setPanelWeights(_ rowIndex: Int, weights: [Double], persist: Bool, dataSource: DataSource) { + guard var d = selected, d.rows.indices.contains(rowIndex), + d.rows[rowIndex].panels.count == weights.count else { return } + for i in d.rows[rowIndex].panels.indices { + d.rows[rowIndex].panels[i].weight = max(0.05, weights[i]) + } + commit(d, persist: persist, dataSource: dataSource) + } + + /// Append a panel to an existing row (splitting its width). + func addPanel(toRow rowIndex: Int, visualization: SavedVisualization, dataSource: DataSource) { + guard var d = selected, d.rows.indices.contains(rowIndex) else { return } + d.rows[rowIndex].panels.append(RowPanel(visualization: visualization, weight: 1.0)) + commit(d, persist: true, dataSource: dataSource) + } + + /// Add a new full-width row at the bottom, holding `visualization`. + func addRow(with visualization: SavedVisualization, dataSource: DataSource) { + guard var d = selected else { return } + d.rows.append(DashboardRow(panels: [RowPanel(visualization: visualization)])) + commit(d, persist: true, dataSource: dataSource) + } + + /// Replace a panel's visualization (chart editor "save"). + func updatePanel(row rowIndex: Int, panel panelIndex: Int, visualization: SavedVisualization, dataSource: DataSource) { + guard var d = selected, d.rows.indices.contains(rowIndex), + d.rows[rowIndex].panels.indices.contains(panelIndex) else { return } + d.rows[rowIndex].panels[panelIndex].visualization = visualization + commit(d, persist: true, dataSource: dataSource) + } + + /// Move a panel (identified by its stable id) to `destRow`, inserted at `destIndex` + /// within that row's *current* layout (nil = append to the end). Handles reordering + /// within a row and moving across rows; if the source row empties it is removed. + /// Drag-and-drop reorder entry point. + func movePanel(_ panelId: UUID, toRow destRow: Int, at destIndex: Int?, dataSource: DataSource) { + guard var d = selected, let src = locate(panelId, in: d), d.rows.indices.contains(destRow) else { return } + + var dest = destRow + var insert = destIndex ?? d.rows[dest].panels.count + + // Dropping a panel back onto its own slot (either side) is a no-op. + if src.row == dest && (insert == src.panel || insert == src.panel + 1) { return } + + let panel = d.rows[src.row].panels.remove(at: src.panel) + + // Same-row move: removing the source shifts later indices left by one. + if src.row == dest && src.panel < insert { insert -= 1 } + + // If the source row emptied, drop it and fix up the destination index. + if d.rows[src.row].panels.isEmpty { + d.rows.remove(at: src.row) + if src.row < dest { dest -= 1 } + } + + guard d.rows.indices.contains(dest) else { return } + insert = min(max(0, insert), d.rows[dest].panels.count) + d.rows[dest].panels.insert(panel, at: insert) + commit(d, persist: true, dataSource: dataSource) + } + + /// Find a panel's (row, panel) position by its stable id. + private func locate(_ panelId: UUID, in dashboard: Dashboard) -> (row: Int, panel: Int)? { + for (ri, row) in dashboard.rows.enumerated() { + if let pi = row.panels.firstIndex(where: { $0.id == panelId }) { return (ri, pi) } + } + return nil + } + + /// Remove a panel; drops the row if it becomes empty. + func removePanel(row rowIndex: Int, panel panelIndex: Int, dataSource: DataSource) { + guard var d = selected, d.rows.indices.contains(rowIndex), + d.rows[rowIndex].panels.indices.contains(panelIndex) else { return } + d.rows[rowIndex].panels.remove(at: panelIndex) + if d.rows[rowIndex].panels.isEmpty { + d.rows.remove(at: rowIndex) + } + commit(d, persist: true, dataSource: dataSource) + } + + // MARK: - Internals + + private func commit(_ dashboard: Dashboard, persist: Bool, dataSource: DataSource) { + selected = dashboard + guard persist else { return } + save(dashboard, dataSource: dataSource) + } + + private func save(_ dashboard: Dashboard, dataSource: DataSource) { + do { + let saved = try dataSource.saveDashboard(dashboard) + if let idx = dashboards.firstIndex(where: { $0.id == saved.id }) { + dashboards[idx] = saved + } else { + dashboards.append(saved) + } + // Preserve the working copy's live edits but adopt the saved id/timestamps. + selected?.id = saved.id + selectedDashboardId = saved.id + } catch { + errorMessage = error.localizedDescription + } + } +} diff --git a/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift b/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift new file mode 100644 index 00000000..95bb4b0c --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift @@ -0,0 +1,77 @@ +import SwiftUI +import SequinsData + +// MARK: - Content Only Wrapper + +/// Wrapper following the *ContentOnly pattern — refreshes the conversation list when +/// the data source changes. +struct AssistantContentOnly: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: AssistantViewModel + + var body: some View { + AssistantContentView(viewModel: viewModel) + .task(id: appState.dataSourceId) { + if let ds = appState.dataSource { + viewModel.refreshConversations(dataSource: ds) + } + } + } +} + +// MARK: - Assistant tab + +/// The Assistant tab: a conversation list on the left, the active chat on the right. +struct AssistantContentView: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: AssistantViewModel + + var body: some View { + HSplitView { + ChatListPanel(viewModel: viewModel) + .frame(minWidth: 200, idealWidth: 240, maxWidth: 340) + + chatDetail + .frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity) + } + } + + @ViewBuilder + private var chatDetail: some View { + if appState.dataSource == nil { + VizMessage(icon: "bolt.slash", text: "Not connected to a data source") + } else if appState.assistantConfig() == nil { + configPrompt + } else { + VStack(spacing: 0) { + ChatTranscriptView(viewModel: viewModel) + Divider() + ChatInputBar(viewModel: viewModel, onSend: sendMessage) + } + } + } + + private var configPrompt: some View { + VStack(spacing: 12) { + Image(systemName: "key.horizontal") + .font(.system(size: 44)) + .foregroundStyle(.secondary) + Text("Assistant not configured") + .font(.title3) + Text("Add an LLM model and API key for this environment in Settings to start chatting.") + .font(.callout) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .frame(maxWidth: 320) + Button("Open Settings") { appState.showSettings = true } + .buttonStyle(.borderedProminent) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding() + } + + private func sendMessage() { + guard let ds = appState.dataSource, let config = appState.assistantConfig() else { return } + viewModel.send(dataSource: ds, config: config) + } +} diff --git a/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift b/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift new file mode 100644 index 00000000..0758495b --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift @@ -0,0 +1,45 @@ +import SwiftUI + +/// The chat composer: a growing text field plus send/stop control. +struct ChatInputBar: View { + @Bindable var viewModel: AssistantViewModel + let onSend: () -> Void + + private var canSend: Bool { + !viewModel.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var body: some View { + HStack(alignment: .bottom, spacing: 8) { + TextField("Ask about your telemetry…", text: $viewModel.inputText, axis: .vertical) + .textFieldStyle(.plain) + .lineLimit(1...6) + .padding(8) + .background(Color(nsColor: .textBackgroundColor)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .onSubmit { + if canSend { onSend() } + } + + if viewModel.isStreaming { + Button { + viewModel.cancelStreaming() + } label: { + Image(systemName: "stop.circle.fill") + .font(.title2) + } + .buttonStyle(.borderless) + .help("Stop") + } else { + Button(action: onSend) { + Image(systemName: "arrow.up.circle.fill") + .font(.title2) + } + .buttonStyle(.borderless) + .disabled(!canSend) + .help("Send") + } + } + .padding(8) + } +} diff --git a/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift b/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift new file mode 100644 index 00000000..59762d28 --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift @@ -0,0 +1,67 @@ +import SwiftUI +import SequinsData + +/// Sidebar list of past conversations plus a "New chat" action. +struct ChatListPanel: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: AssistantViewModel + + var body: some View { + VStack(spacing: 0) { + HStack { + Text("Chats") + .font(.headline) + Spacer() + Button { + viewModel.newChat() + } label: { + Image(systemName: "square.and.pencil") + } + .buttonStyle(.borderless) + .help("New chat") + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + + Divider() + + if viewModel.conversations.isEmpty { + VStack(spacing: 6) { + Image(systemName: "bubble.left.and.text.bubble.right") + .font(.title2) + .foregroundStyle(.tertiary) + Text("No chats yet") + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + List(selection: selectionBinding) { + ForEach(viewModel.conversations) { convo in + VStack(alignment: .leading, spacing: 2) { + Text(convo.displayTitle) + .lineLimit(1) + Text("\(convo.itemCount) message\(convo.itemCount == 1 ? "" : "s")") + .font(.caption) + .foregroundStyle(.secondary) + } + .tag(convo.id) + } + } + .listStyle(.sidebar) + } + } + .background(Color(nsColor: .controlBackgroundColor).opacity(0.5)) + } + + private var selectionBinding: Binding { + Binding( + get: { viewModel.selectedConversationId }, + set: { newValue in + if let id = newValue, let ds = appState.dataSource { + viewModel.openConversation(id, dataSource: ds) + } + } + ) + } +} diff --git a/apps/macos/Sequins/Views/Assistant/ChatMessageRow.swift b/apps/macos/Sequins/Views/Assistant/ChatMessageRow.swift new file mode 100644 index 00000000..d4afbe38 --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/ChatMessageRow.swift @@ -0,0 +1,120 @@ +import SwiftUI +import SequinsData + +/// Renders a single transcript item: a user/assistant message, a server tool-activity +/// card, or an inline visualization. +struct ChatMessageRow: View { + let item: ChatItem + let dataSource: DataSource? + + var body: some View { + switch item.kind { + case .userText(let text): + messageBubble(text, role: .user) + case .assistantText(let text): + messageBubble(text, role: .assistant) + case .toolActivity: + // A lone tool call still renders in the shared full-width group container. + ToolActivityGroup(items: [item]) + case .visualization(let viz): + InlineVisualizationCard(visualization: viz, dataSource: dataSource) + } + } + + private enum Role { case user, assistant } + + /// A Markdown-rendered message bubble: user messages tint-filled and trailing, + /// assistant messages neutral and leading. Both go through ``MarkdownText``. + private func messageBubble(_ text: String, role: Role) -> some View { + HStack { + if role == .user { Spacer(minLength: 40) } + MarkdownText(text: text) + .textSelection(.enabled) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background(bubbleColor(role), in: RoundedRectangle(cornerRadius: 12)) + .overlay( + RoundedRectangle(cornerRadius: 12) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 1) + ) + if role == .assistant { Spacer(minLength: 40) } + } + } + + private func bubbleColor(_ role: Role) -> Color { + switch role { + // Distinct from the window background so the bubble reads as a bubble in both + // light and dark (`controlBackgroundColor` blends into the transcript). + case .user: return Color.accentColor.opacity(0.18) + case .assistant: return Color.secondary.opacity(0.12) + } + } +} + +/// Groups a run of consecutive tool calls into one full-width, contained block — +/// visually separating the model's tool work from the message bubbles around it. +struct ToolActivityGroup: View { + let items: [ChatItem] + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(items.enumerated()), id: \.element.id) { index, item in + if case .toolActivity(let activity) = item.kind { + if index > 0 { + Divider().opacity(0.4) + } + ToolActivityRow(activity: activity) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 10)) + } +} + +/// One expandable tool call + its output. Background-less — the enclosing +/// ``ToolActivityGroup`` provides the shared container. +struct ToolActivityRow: View { + let activity: AssistantToolActivity + @State private var expanded = false + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Button { + expanded.toggle() + } label: { + HStack(spacing: 6) { + Image(systemName: "wrench.and.screwdriver") + .font(.caption) + .foregroundStyle(.secondary) + Text(activity.name.isEmpty ? "tool" : activity.name) + .font(.caption.weight(.medium)) + Spacer() + Image(systemName: expanded ? "chevron.down" : "chevron.right") + .font(.caption2) + .foregroundStyle(.secondary) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if expanded { + if !activity.arguments.isEmpty { + Text(activity.arguments) + .font(.system(.caption2, design: .monospaced)) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + if !activity.output.isEmpty { + Text(activity.output) + .font(.system(.caption2, design: .monospaced)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} diff --git a/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift b/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift new file mode 100644 index 00000000..f9e382e4 --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift @@ -0,0 +1,102 @@ +import SwiftUI +import SequinsData + +/// Virtualized, auto-scrolling chat transcript (mirrors the log terminal): a +/// `LazyVStack` in a `ScrollView` pinned to the bottom, scrolling to the newest +/// content as it streams in. +struct ChatTranscriptView: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: AssistantViewModel + + /// A cheap signal that changes as new items arrive AND as the streaming assistant + /// text grows (its item id is stable), so we keep scrolling during a long reply. + private var scrollSignal: String { + let count = viewModel.transcript.count + var lastLen = 0 + if let last = viewModel.transcript.last, case .assistantText(let t) = last.kind { + lastLen = t.count + } + return "\(count)-\(lastLen)-\(viewModel.isStreaming)" + } + + /// A transcript run: either a standalone message, or a group of consecutive tool + /// calls that render together in one full-width container. + private enum TranscriptSegment: Identifiable { + case message(ChatItem) + case toolRun([ChatItem]) + + var id: String { + switch self { + case .message(let item): return "m-\(item.id)" + case .toolRun(let items): return "t-\(items.first?.id.uuidString ?? "")" + } + } + } + + /// Collapse maximal runs of consecutive `.toolActivity` items into `.toolRun` + /// segments; everything else stays a standalone `.message`. + private var segments: [TranscriptSegment] { + var out: [TranscriptSegment] = [] + var run: [ChatItem] = [] + func flush() { + if !run.isEmpty { + out.append(.toolRun(run)) + run.removeAll() + } + } + for item in viewModel.transcript { + if case .toolActivity = item.kind { + run.append(item) + } else { + flush() + out.append(.message(item)) + } + } + flush() + return out + } + + var body: some View { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 14) { + ForEach(segments) { segment in + switch segment { + case .message(let item): + ChatMessageRow(item: item, dataSource: appState.dataSource) + .id(item.id) + case .toolRun(let items): + ToolActivityGroup(items: items) + .id(segment.id) + } + } + + if viewModel.isStreaming { + HStack(spacing: 6) { + ProgressView().scaleEffect(0.6) + Text("Thinking…") + .font(.caption) + .foregroundStyle(.secondary) + } + .id("streaming-indicator") + } + + if let error = viewModel.errorMessage { + Label(error, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundStyle(.red) + } + + Color.clear.frame(height: 1).id("bottom-anchor") + } + .padding() + } + .defaultScrollAnchor(.bottom) + .onChange(of: scrollSignal) { _, _ in + withAnimation(.easeOut(duration: 0.15)) { + proxy.scrollTo("bottom-anchor", anchor: .bottom) + } + } + } + } +} diff --git a/apps/macos/Sequins/Views/Assistant/InlineVisualizationCard.swift b/apps/macos/Sequins/Views/Assistant/InlineVisualizationCard.swift new file mode 100644 index 00000000..197b9c6b --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/InlineVisualizationCard.swift @@ -0,0 +1,61 @@ +import SwiftUI +import SequinsData + +/// An inline visualization in the chat transcript: a titled card wrapping the shared +/// ``VisualizationView``, with a type picker and an "Add to dashboard" action. +struct InlineVisualizationCard: View { + let visualization: SavedVisualization + let dataSource: DataSource? + + @State private var vizOverride: VizType? + @State private var showingAdd = false + + /// The visualization with the current override folded into `shape`, so saving to a + /// dashboard keeps the user's chosen type. + private var effectiveVisualization: SavedVisualization { + var v = visualization + if let vizOverride { v.shape = vizOverride.rawValue } + return v + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "chart.bar.xaxis") + .foregroundStyle(.secondary) + Text(visualization.title) + .font(.subheadline.weight(.semibold)) + .lineLimit(1) + Spacer() + VizTypePicker(selection: $vizOverride) + Button { + showingAdd = true + } label: { + Image(systemName: "plus.rectangle.on.rectangle") + } + .buttonStyle(.borderless) + .help("Add to dashboard") + } + + VisualizationView( + visualization: visualization, + dataSource: dataSource, + isLive: false, + vizTypeOverride: vizOverride + ) + .frame(height: 260) + .background(Color(nsColor: .textBackgroundColor)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } + .padding(10) + .background(Color(nsColor: .controlBackgroundColor)) + .clipShape(RoundedRectangle(cornerRadius: 12)) + .overlay( + RoundedRectangle(cornerRadius: 12) + .stroke(Color.secondary.opacity(0.15), lineWidth: 1) + ) + .sheet(isPresented: $showingAdd) { + AddToDashboardSheet(visualization: effectiveVisualization, dataSource: dataSource) + } + } +} diff --git a/apps/macos/Sequins/Views/Assistant/MarkdownText.swift b/apps/macos/Sequins/Views/Assistant/MarkdownText.swift new file mode 100644 index 00000000..4fc2a58b --- /dev/null +++ b/apps/macos/Sequins/Views/Assistant/MarkdownText.swift @@ -0,0 +1,193 @@ +import SwiftUI + +/// A lightweight block-level Markdown renderer for chat messages — headings, bullet and +/// numbered lists, fenced code blocks, and paragraphs, with inline emphasis/`code`/links +/// rendered via `AttributedString`. Enough for assistant and user chat text without +/// pulling in a Markdown dependency, and it degrades gracefully on the partial Markdown +/// produced while an assistant reply is still streaming. +struct MarkdownText: View { + let text: String + + var body: some View { + let blocks = Self.parse(text) + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in + view(for: block) + } + } + } + + // MARK: - Block views + + @ViewBuilder + private func view(for block: Block) -> some View { + switch block { + case .heading(let level, let content): + Self.inline(content) + .font(Self.headingFont(level)) + .fontWeight(.semibold) + case .paragraph(let content): + // `inlineOnlyPreservingWhitespace` keeps soft line breaks within a paragraph. + Self.inline(content) + case .bullet(let items): + VStack(alignment: .leading, spacing: 3) { + ForEach(Array(items.enumerated()), id: \.offset) { _, item in + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("•").foregroundStyle(.secondary) + Self.inline(item) + } + } + } + case .ordered(let items): + VStack(alignment: .leading, spacing: 3) { + ForEach(Array(items.enumerated()), id: \.offset) { idx, item in + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("\(idx + 1).").monospacedDigit().foregroundStyle(.secondary) + Self.inline(item) + } + } + } + case .code(let code): + Text(code) + .font(.system(.caption, design: .monospaced)) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(8) + .background(Color.primary.opacity(0.06)) + .clipShape(RoundedRectangle(cornerRadius: 6)) + } + } + + private static func headingFont(_ level: Int) -> Font { + switch level { + case 1: return .title3 + case 2: return .headline + default: return .subheadline + } + } + + // MARK: - Inline + + /// Render one span of inline Markdown (bold/italic/`code`/links), preserving the + /// original whitespace and newlines. Falls back to plain text on a parse failure. + static func inline(_ s: String) -> Text { + if let attributed = try? AttributedString( + markdown: s, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + ) { + return Text(attributed) + } + return Text(s) + } + + // MARK: - Parsing + + enum Block { + case heading(level: Int, content: String) + case paragraph(String) + case bullet([String]) + case ordered([String]) + case code(String) + } + + static func parse(_ text: String) -> [Block] { + var blocks: [Block] = [] + let lines = text.components(separatedBy: "\n") + var para: [String] = [] + var i = 0 + + func flushParagraph() { + if !para.isEmpty { + blocks.append(.paragraph(para.joined(separator: "\n"))) + para.removeAll() + } + } + + while i < lines.count { + let raw = lines[i] + let line = raw.trimmingCharacters(in: .whitespaces) + + // Fenced code block: ``` … ``` + if line.hasPrefix("```") { + flushParagraph() + i += 1 + var code: [String] = [] + while i < lines.count, !lines[i].trimmingCharacters(in: .whitespaces).hasPrefix("```") { + code.append(lines[i]) + i += 1 + } + i += 1 // consume the closing fence (or run off the end while streaming) + blocks.append(.code(code.joined(separator: "\n"))) + continue + } + + // ATX heading: #, ##, ### followed by a space. + if let level = headingLevel(line) { + flushParagraph() + let content = String(line.drop(while: { $0 == "#" })) + .trimmingCharacters(in: .whitespaces) + blocks.append(.heading(level: level, content: content)) + i += 1 + continue + } + + // Unordered list run. + if isBullet(line) { + flushParagraph() + var items: [String] = [] + while i < lines.count { + let t = lines[i].trimmingCharacters(in: .whitespaces) + guard isBullet(t) else { break } + items.append(String(t.dropFirst(2))) + i += 1 + } + blocks.append(.bullet(items)) + continue + } + + // Ordered list run (`1. `, `2. `, …). + if orderedDrop(line) != nil { + flushParagraph() + var items: [String] = [] + while i < lines.count { + let t = lines[i].trimmingCharacters(in: .whitespaces) + guard let drop = orderedDrop(t) else { break } + items.append(String(t.dropFirst(drop))) + i += 1 + } + blocks.append(.ordered(items)) + continue + } + + // Blank line ends a paragraph. + if line.isEmpty { + flushParagraph() + i += 1 + continue + } + + para.append(raw) + i += 1 + } + flushParagraph() + return blocks + } + + private static func headingLevel(_ line: String) -> Int? { + guard line.hasPrefix("#") else { return nil } + let hashes = line.prefix(while: { $0 == "#" }).count + guard hashes <= 3, line.dropFirst(hashes).first == " " else { return nil } + return hashes + } + + private static func isBullet(_ line: String) -> Bool { + line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("+ ") + } + + /// If `line` starts an ordered-list item (`12. `), the number of leading characters + /// to drop to reach the item text; otherwise `nil`. + private static func orderedDrop(_ line: String) -> Int? { + let digits = line.prefix(while: { $0.isNumber }) + guard !digits.isEmpty, line.dropFirst(digits.count).hasPrefix(". ") else { return nil } + return digits.count + 2 + } +} diff --git a/apps/macos/Sequins/Views/Dashboards/AddToDashboardSheet.swift b/apps/macos/Sequins/Views/Dashboards/AddToDashboardSheet.swift new file mode 100644 index 00000000..c6c97c6e --- /dev/null +++ b/apps/macos/Sequins/Views/Dashboards/AddToDashboardSheet.swift @@ -0,0 +1,108 @@ +import SwiftUI +import SequinsData + +/// Sheet to add a visualization to a new or existing dashboard. Shared by the +/// Assistant tab (inline viz cards) and the Dashboards tab. +struct AddToDashboardSheet: View { + let visualization: SavedVisualization + let dataSource: DataSource? + + @Environment(\.dismiss) private var dismiss + @State private var dashboards: [Dashboard] = [] + @State private var mode: Mode = .existing + @State private var selectedId: String? + @State private var newTitle: String = "" + @State private var error: String? + + enum Mode: Hashable { case existing, new } + + private var canAdd: Bool { + switch mode { + case .existing: return selectedId != nil + case .new: return !newTitle.trimmingCharacters(in: .whitespaces).isEmpty + } + } + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + Text("Add to Dashboard") + .font(.headline) + + Picker("", selection: $mode) { + Text("Existing").tag(Mode.existing) + Text("New").tag(Mode.new) + } + .pickerStyle(.segmented) + .labelsHidden() + .disabled(dashboards.isEmpty && mode == .existing) + + switch mode { + case .existing: + if dashboards.isEmpty { + Text("No dashboards yet — create one.") + .font(.caption) + .foregroundStyle(.secondary) + } else { + Picker("Dashboard", selection: $selectedId) { + ForEach(dashboards) { d in + Text(d.title).tag(Optional(d.id)) + } + } + } + case .new: + TextField("Dashboard name", text: $newTitle) + .textFieldStyle(.roundedBorder) + } + + if let error { + Text(error) + .font(.caption) + .foregroundStyle(.red) + } + + HStack { + Spacer() + Button("Cancel") { dismiss() } + Button("Add") { add() } + .keyboardShortcut(.defaultAction) + .disabled(!canAdd) + } + } + .padding() + .frame(width: 360) + .task { loadDashboards() } + } + + private func loadDashboards() { + guard let ds = dataSource else { return } + do { + dashboards = try ds.listDashboards() + if selectedId == nil { selectedId = dashboards.first?.id } + if dashboards.isEmpty { mode = .new } + } catch { + self.error = error.localizedDescription + } + } + + private func add() { + guard let ds = dataSource else { return } + do { + var dashboard: Dashboard + switch mode { + case .new: + let title = newTitle.trimmingCharacters(in: .whitespaces) + dashboard = Dashboard(title: title.isEmpty ? "New Dashboard" : title) + case .existing: + guard let id = selectedId, + let existing = dashboards.first(where: { $0.id == id }) else { return } + dashboard = existing + } + // Add the visualization as a new full-width row at the bottom. + dashboard.rows.append(DashboardRow(panels: [RowPanel(visualization: visualization)])) + _ = try ds.saveDashboard(dashboard) + dismiss() + } catch { + self.error = error.localizedDescription + } + } +} diff --git a/apps/macos/Sequins/Views/Dashboards/ChartEditorSheet.swift b/apps/macos/Sequins/Views/Dashboards/ChartEditorSheet.swift new file mode 100644 index 00000000..4f920e86 --- /dev/null +++ b/apps/macos/Sequins/Views/Dashboards/ChartEditorSheet.swift @@ -0,0 +1,149 @@ +import SwiftUI +import SequinsData + +/// Create or configure a dashboard chart: edit its SeQL query, title, and visualization +/// type with a live preview, then add it (to a row or a new row) or save an existing one. +struct ChartEditorSheet: View { + let target: ChartEditorTarget + @Bindable var viewModel: DashboardsViewModel + let dataSource: DataSource? + let timeRange: TimeRange + + @Environment(\.dismiss) private var dismiss + + @State private var seql = "" + @State private var title = "" + @State private var vizType: VizType? + @State private var previewSeql = "" + @State private var loaded = false + @State private var previewDebounce: Task? + + private var isEditing: Bool { + if case .edit = target { return true } + return false + } + + private var canSave: Bool { + !seql.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private var previewVisualization: SavedVisualization { + SavedVisualization( + seql: previewSeql, + title: title.isEmpty ? "Preview" : title, + shape: vizType?.rawValue + ) + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text(isEditing ? "Edit Chart" : "New Chart") + .font(.headline) + + TextField("Title", text: $title) + .textFieldStyle(.roundedBorder) + + VStack(alignment: .leading, spacing: 4) { + Text("SeQL query") + .font(.caption) + .foregroundStyle(.secondary) + TextEditor(text: $seql) + .font(.system(.body, design: .monospaced)) + .scrollContentBackground(.hidden) + .padding(6) + .frame(height: 72) + .background(Color(nsColor: .textBackgroundColor)) + .clipShape(RoundedRectangle(cornerRadius: 6)) + .overlay( + RoundedRectangle(cornerRadius: 6) + .stroke(Color.secondary.opacity(0.2), lineWidth: 1) + ) + .onChange(of: seql) { _, newValue in schedulePreview(newValue) } + } + + HStack(spacing: 8) { + Text("Type") + .font(.caption) + .foregroundStyle(.secondary) + VizTypePicker(selection: $vizType) + Spacer() + } + + VStack(alignment: .leading, spacing: 4) { + Text("Preview") + .font(.caption) + .foregroundStyle(.secondary) + VisualizationView( + visualization: previewVisualization, + dataSource: dataSource, + timeRange: timeRange, + isLive: false, + applyTimeRange: true, + vizTypeOverride: vizType + ) + .frame(height: 220) + .background(Color(nsColor: .textBackgroundColor)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } + + HStack { + Spacer() + Button("Cancel") { dismiss() } + Button(isEditing ? "Save" : "Add") { save() } + .keyboardShortcut(.defaultAction) + .disabled(!canSave) + } + } + .padding() + .frame(width: 540) + .task { loadIfNeeded() } + } + + private func loadIfNeeded() { + guard !loaded else { return } + loaded = true + if case .edit(let r, let p) = target, + let dashboard = viewModel.selected, + dashboard.rows.indices.contains(r), + dashboard.rows[r].panels.indices.contains(p) { + let viz = dashboard.rows[r].panels[p].visualization + seql = viz.seql + title = viz.title + vizType = viz.vizType + } else { + seql = "spans last 15m | group by { ts() bin 1m as bucket } { count() as n }" + title = "New Chart" + } + previewSeql = seql + } + + /// Debounce preview re-runs so we don't execute a query on every keystroke. + private func schedulePreview(_ value: String) { + previewDebounce?.cancel() + previewDebounce = Task { + try? await Task.sleep(nanoseconds: 600_000_000) + if !Task.isCancelled { + previewSeql = value + } + } + } + + private func save() { + guard let ds = dataSource else { return } + let cleanTitle = title.trimmingCharacters(in: .whitespaces) + let viz = SavedVisualization( + seql: seql.trimmingCharacters(in: .whitespacesAndNewlines), + title: cleanTitle.isEmpty ? "Chart" : cleanTitle, + shape: vizType?.rawValue + ) + switch target { + case .addToRow(let r): + viewModel.addPanel(toRow: r, visualization: viz, dataSource: ds) + case .newRow: + viewModel.addRow(with: viz, dataSource: ds) + case .edit(let r, let p): + viewModel.updatePanel(row: r, panel: p, visualization: viz, dataSource: ds) + } + dismiss() + } +} diff --git a/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift b/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift new file mode 100644 index 00000000..a9b6c18d --- /dev/null +++ b/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift @@ -0,0 +1,499 @@ +import SwiftUI +import SequinsData +import UniformTypeIdentifiers + +// A dragged panel is carried as its stable id (a UUID string) via a plain-text +// `NSItemProvider` (a registered system type, so it round-trips reliably). Drops use a +// `DropDelegate` so we get the live cursor location (`dropUpdated`) and can show an +// insertion bar in the exact gap/edge where the chart will land, rather than +// highlighting a whole target chart. Insertion index `k` (0...panelCount) means "before +// panel k"; `panelCount` is the trailing edge of the row. + +/// The single gap a dragged chart would drop into, shared across all rows so exactly one +/// insertion bar shows at a time and it clears globally on drop (per-row `dropExited` is +/// not reliably delivered, which otherwise left stale guides behind after a drop). +private struct DropSlot: Equatable { + let row: Int + let gap: Int +} + +/// What the chart-editor sheet is currently targeting. +enum ChartEditorTarget: Identifiable { + case addToRow(Int) + case newRow + case edit(row: Int, panel: Int) + + var id: String { + switch self { + case .addToRow(let r): return "add-\(r)" + case .newRow: return "newrow" + case .edit(let r, let p): return "edit-\(r)-\(p)" + } + } +} + +/// A dashboard as a vertical stack of full-width rows. Each row splits its width among +/// its panels by weight. Rows are resized by the bars between them; panels within a row +/// are re-proportioned by the bars between them; panels can be added (right-edge slot or +/// a new row) removed, and configured. Panels honor the dashboard's live toggle + +/// time-range controls. +struct DashboardGridView: View { + @Bindable var viewModel: DashboardsViewModel + let dataSource: DataSource? + let timeRange: TimeRange + let isLive: Bool + + @State private var editorTarget: ChartEditorTarget? + /// The gap a chart is currently being dragged over (shared across rows), or nil. + @State private var activeDropSlot: DropSlot? + /// True only while a chart is mid-drag. `dropEntered` sets it, `performDrop` clears + /// it — the insertion bar is gated on this, so the stray `dropUpdated` SwiftUI fires + /// AFTER a drop (which re-sets `activeDropSlot`) can't make the guide reappear. + @State private var dragActive = false + + private let handleThickness: CGFloat = 10 + + var body: some View { + ScrollView(.vertical) { + VStack(spacing: 0) { + if let dashboard = viewModel.selected { + ForEach(Array(dashboard.rows.enumerated()), id: \.element.id) { rowIndex, row in + DashboardRowView( + row: row, + rowIndex: rowIndex, + viewModel: viewModel, + dataSource: dataSource, + timeRange: timeRange, + isLive: isLive, + activeDropSlot: $activeDropSlot, + dragActive: $dragActive, + onAddChart: { editorTarget = .addToRow(rowIndex) }, + onEditPanel: { panelIndex in editorTarget = .edit(row: rowIndex, panel: panelIndex) } + ) + .frame(height: row.height) + + RowResizeHandle( + thickness: handleThickness, + onChanged: { dy in + if let ds = dataSource { + viewModel.setRowHeight(rowIndex, height: row.height + dy, persist: false, dataSource: ds) + } + }, + onEnded: { dy in + if let ds = dataSource { + viewModel.setRowHeight(rowIndex, height: row.height + dy, persist: true, dataSource: ds) + } + } + ) + } + + addRowButton + } + } + .padding(8) + } + .sheet(item: $editorTarget) { target in + ChartEditorSheet( + target: target, + viewModel: viewModel, + dataSource: dataSource, + timeRange: timeRange + ) + } + } + + private var addRowButton: some View { + Button { + editorTarget = .newRow + } label: { + HStack { + Image(systemName: "plus") + Text("Add row") + } + .font(.caption) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + .frame(height: 34) + .background( + RoundedRectangle(cornerRadius: 8) + .strokeBorder(style: StrokeStyle(lineWidth: 1, dash: [4])) + .foregroundStyle(.secondary.opacity(0.4)) + ) + } + .buttonStyle(.plain) + .padding(.top, 6) + } +} + +// MARK: - Row + +private struct DashboardRowView: View { + let row: DashboardRow + let rowIndex: Int + @Bindable var viewModel: DashboardsViewModel + let dataSource: DataSource? + let timeRange: TimeRange + let isLive: Bool + @Binding var activeDropSlot: DropSlot? + @Binding var dragActive: Bool + let onAddChart: () -> Void + let onEditPanel: (Int) -> Void + + /// Transient weights during a ratio drag (nil when not dragging). + @State private var dragWeights: [Double]? + @State private var hoveringAddSlot = false + + private let panelHandleWidth: CGFloat = 8 + private let addSlotCollapsed: CGFloat = 12 + private let addSlotExpanded: CGFloat = 120 + + private var weights: [Double] { + dragWeights ?? row.panels.map { $0.weight } + } + + /// This row's active insertion gap — only while a drag is actually in progress + /// (`dragActive`), so a post-drop stray `dropUpdated` can't resurrect the guide. + private var dropInsertion: Int? { + guard dragActive else { return nil } + return activeDropSlot.flatMap { $0.row == rowIndex ? $0.gap : nil } + } + + /// Set this row's insertion gap into the shared slot; nil clears it (only if the + /// shared slot currently belongs to this row, so leaving one row can't wipe the + /// indicator another row just claimed). + private func setInsertion(_ gap: Int?) { + if let gap { + activeDropSlot = DropSlot(row: rowIndex, gap: gap) + } else if activeDropSlot?.row == rowIndex { + activeDropSlot = nil + } + } + + var body: some View { + GeometryReader { geo in + let addSlotWidth = hoveringAddSlot ? addSlotExpanded : addSlotCollapsed + let handlesWidth = panelHandleWidth * CGFloat(max(0, row.panels.count - 1)) + let panelsWidth = max(0, geo.size.width - handlesWidth - addSlotWidth) + let total = max(0.0001, weights.reduce(0, +)) + + HStack(spacing: 0) { + ForEach(Array(row.panels.enumerated()), id: \.element.id) { panelIndex, panel in + let panelWidth = panelsWidth * CGFloat(weights[panelIndex] / total) + DashboardPanelView( + panel: panel, + dataSource: dataSource, + timeRange: timeRange, + isLive: isLive, + onEdit: { onEditPanel(panelIndex) }, + onRemove: { + if let ds = dataSource { + viewModel.removePanel(row: rowIndex, panel: panelIndex, dataSource: ds) + } + }, + onVizTypeChange: { newType in + updatePanelType(panelIndex, newType) + } + ) + .frame(width: panelWidth) + // Insertion bar in the gap on this panel's leading edge. + .overlay(alignment: .leading) { insertionBar(active: dropInsertion == panelIndex) } + // Last panel also shows the bar on its trailing edge (the final gap). + .overlay(alignment: .trailing) { + insertionBar(active: panelIndex == row.panels.count - 1 && dropInsertion == row.panels.count) + } + + // Ratio handle between this panel and the next. + if panelIndex < row.panels.count - 1 { + PanelRatioHandle( + width: panelHandleWidth, + onChanged: { dx in ratioDrag(after: panelIndex, dx: dx, panelsWidth: panelsWidth, commit: false) }, + onEnded: { dx in ratioDrag(after: panelIndex, dx: dx, panelsWidth: panelsWidth, commit: true) } + ) + } + } + + addSlot(width: addSlotWidth) + } + // ONE contiguous drop target across the whole row — no dead zones (the + // 8pt resize handles between charts were gaps that swallowed drops and left + // the guide stuck). The insertion gap is derived from the cursor's x. + .onDrop(of: [.text], delegate: RowDropDelegate( + panelWidths: (0.. some View { + if active { + RoundedRectangle(cornerRadius: 2) + .fill(Color.accentColor) + .frame(width: 4) + .padding(.vertical, 4) + .shadow(color: .accentColor.opacity(0.7), radius: 3) + .transition(.opacity) + } + } + + /// Perform a validated drop: move the dragged panel into this row at `index`. + private func moveDroppedPanel(_ panelId: UUID, to index: Int) { + activeDropSlot = nil + guard let ds = dataSource else { return } + viewModel.movePanel(panelId, toRow: rowIndex, at: index, dataSource: ds) + } + + private func addSlot(width: CGFloat) -> some View { + Button(action: onAddChart) { + ZStack { + RoundedRectangle(cornerRadius: 8) + .strokeBorder(style: StrokeStyle(lineWidth: 1, dash: [4])) + .foregroundStyle(.secondary.opacity(hoveringAddSlot ? 0.6 : 0.25)) + if hoveringAddSlot { + VStack(spacing: 4) { + Image(systemName: "plus") + Text("Add chart").font(.caption2) + } + .foregroundStyle(.secondary) + } else { + Image(systemName: "plus") + .font(.caption2) + .foregroundStyle(.secondary.opacity(0.5)) + } + } + .frame(width: width) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .padding(.leading, 4) + .onHover { hoveringAddSlot = $0 } + .animation(.easeOut(duration: 0.12), value: hoveringAddSlot) + } + + /// Shift weight between panel `i` and `i+1` by a pixel delta. + private func ratioDrag(after i: Int, dx: CGFloat, panelsWidth: CGFloat, commit: Bool) { + guard panelsWidth > 0, row.panels.indices.contains(i), row.panels.indices.contains(i + 1) else { return } + let base = row.panels.map { $0.weight } + let total = max(0.0001, base.reduce(0, +)) + // Convert pixel delta to a weight delta (weights are in the same units as widths + // once scaled by total/panelsWidth). + let deltaWeight = Double(dx) / Double(panelsWidth) * total + var next = base + let pairSum = base[i] + base[i + 1] + next[i] = min(pairSum - 0.05, max(0.05, base[i] + deltaWeight)) + next[i + 1] = pairSum - next[i] + + if commit { + dragWeights = nil + if let ds = dataSource { + viewModel.setPanelWeights(rowIndex, weights: next, persist: true, dataSource: ds) + } + } else { + dragWeights = next + if let ds = dataSource { + viewModel.setPanelWeights(rowIndex, weights: next, persist: false, dataSource: ds) + } + } + } + + private func updatePanelType(_ panelIndex: Int, _ newType: VizType?) { + guard let ds = dataSource, row.panels.indices.contains(panelIndex) else { return } + var viz = row.panels[panelIndex].visualization + viz.shape = newType?.rawValue + viewModel.updatePanel(row: rowIndex, panel: panelIndex, visualization: viz, dataSource: ds) + } +} + +// MARK: - Panel + +private struct DashboardPanelView: View { + let panel: RowPanel + let dataSource: DataSource? + let timeRange: TimeRange + let isLive: Bool + let onEdit: () -> Void + let onRemove: () -> Void + let onVizTypeChange: (VizType?) -> Void + + @State private var hovering = false + + private var vizTypeBinding: Binding { + Binding(get: { panel.visualization.vizType }, set: { onVizTypeChange($0) }) + } + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 6) { + HStack(spacing: 4) { + Image(systemName: "line.3.horizontal") + .font(.caption2) + .foregroundStyle(.secondary) + .opacity(hovering ? 1 : 0.4) + Text(panel.visualization.title) + .font(.caption.weight(.semibold)) + .lineLimit(1) + // Fill the rest of the title bar (up to the controls) so the whole + // empty area is a drag handle, not just the text + grip. + Spacer(minLength: 0) + } + .contentShape(Rectangle()) + .onDrag { + NSItemProvider(object: panel.id.uuidString as NSString) + } preview: { + Label(panel.visualization.title, systemImage: "chart.bar.doc.horizontal") + .font(.caption) + .padding(6) + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 6)) + } + .onHover { inside in + if inside { NSCursor.openHand.push() } else { NSCursor.pop() } + } + .help("Drag to reorder within the row or move to another row") + if hovering { + VizTypePicker(selection: vizTypeBinding) + Button(action: onEdit) { Image(systemName: "pencil") } + .buttonStyle(.borderless).help("Edit chart") + Button(action: onRemove) { Image(systemName: "xmark.circle") } + .buttonStyle(.borderless).help("Remove chart") + } + } + .font(.caption) + .padding(.horizontal, 8) + .padding(.vertical, 5) + + Divider() + + VisualizationView( + visualization: panel.visualization, + dataSource: dataSource, + timeRange: timeRange, + isLive: isLive, + applyTimeRange: true, + vizTypeOverride: panel.visualization.vizType + ) + } + .background(Color(nsColor: .controlBackgroundColor)) + .clipShape(RoundedRectangle(cornerRadius: 10)) + .overlay( + RoundedRectangle(cornerRadius: 10) + .stroke(Color.secondary.opacity(0.2), lineWidth: 1) + ) + .padding(4) + .onHover { hovering = $0 } + } +} + +// MARK: - Handles + +/// A vertical bar dragged left/right to re-proportion two adjacent panels. +private struct PanelRatioHandle: View { + let width: CGFloat + let onChanged: (CGFloat) -> Void + let onEnded: (CGFloat) -> Void + + var body: some View { + Rectangle() + .fill(Color.secondary.opacity(0.001)) + .overlay( + RoundedRectangle(cornerRadius: 1.5) + .fill(Color.secondary.opacity(0.35)) + .frame(width: 3) + ) + .frame(width: width) + .contentShape(Rectangle()) + .onHover { inside in + if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } + } + .gesture( + DragGesture() + .onChanged { onChanged($0.translation.width) } + .onEnded { onEnded($0.translation.width) } + ) + } +} + +/// A horizontal bar dragged up/down to resize the row above it. +private struct RowResizeHandle: View { + let thickness: CGFloat + let onChanged: (CGFloat) -> Void + let onEnded: (CGFloat) -> Void + + var body: some View { + Rectangle() + .fill(Color.secondary.opacity(0.001)) + .overlay( + RoundedRectangle(cornerRadius: 1.5) + .fill(Color.secondary.opacity(0.35)) + .frame(height: 3) + .padding(.horizontal, 40) + ) + .frame(height: thickness) + .contentShape(Rectangle()) + .onHover { inside in + if inside { NSCursor.resizeUpDown.push() } else { NSCursor.pop() } + } + .gesture( + DragGesture() + .onChanged { onChanged($0.translation.height) } + .onEnded { onEnded($0.translation.height) } + ) + } +} + +// MARK: - Drop + +/// Drop handling for a whole dashboard row — one contiguous target (no dead zones), so +/// the insertion guide always clears on drop. `dropUpdated` gives the live cursor +/// location (which `.dropDestination`'s `isTargeted` can't), from which the insertion +/// gap is computed: the number of panel centers left of the cursor (0…panelCount). +private struct RowDropDelegate: DropDelegate { + let panelWidths: [CGFloat] + let handleWidth: CGFloat + let setDragActive: (Bool) -> Void + let setInsertion: (Int?) -> Void + let move: (UUID, Int) -> Void + + /// Insertion index for a cursor at `x`: count of panels whose center is left of `x`. + private func gap(at x: CGFloat) -> Int { + var left: CGFloat = 0 + for (i, w) in panelWidths.enumerated() { + if x < left + w / 2 { return i } + left += w + handleWidth + } + return panelWidths.count + } + + func validateDrop(info: DropInfo) -> Bool { + info.hasItemsConforming(to: [.text]) + } + + func dropEntered(info: DropInfo) { + setDragActive(true) + setInsertion(gap(at: info.location.x)) + } + + func dropUpdated(info: DropInfo) -> DropProposal? { + setInsertion(gap(at: info.location.x)) + return DropProposal(operation: .move) + } + + func dropExited(info: DropInfo) { setInsertion(nil) } + + func performDrop(info: DropInfo) -> Bool { + let index = gap(at: info.location.x) + // End the drag first: the guide is gated on this, so the stray `dropUpdated` + // SwiftUI fires right after can't bring the bar back. + setDragActive(false) + setInsertion(nil) + guard let provider = info.itemProviders(for: [.text]).first else { return false } + _ = provider.loadObject(ofClass: NSString.self) { value, _ in + guard let string = value as? String, let uuid = UUID(uuidString: string) else { return } + DispatchQueue.main.async { move(uuid, index) } + } + return true + } +} diff --git a/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift b/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift new file mode 100644 index 00000000..99fa4492 --- /dev/null +++ b/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift @@ -0,0 +1,88 @@ +import SwiftUI +import SequinsData + +/// Sidebar list of dashboards with create/delete. +struct DashboardListPanel: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: DashboardsViewModel + + @State private var showingNew = false + @State private var newName = "" + + var body: some View { + VStack(spacing: 0) { + HStack { + Text("Dashboards") + .font(.headline) + Spacer() + Button { + newName = "" + showingNew = true + } label: { + Image(systemName: "plus") + } + .buttonStyle(.borderless) + .help("New dashboard") + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + + Divider() + + if viewModel.dashboards.isEmpty { + VStack(spacing: 6) { + Image(systemName: "square.grid.2x2") + .font(.title2) + .foregroundStyle(.tertiary) + Text("No dashboards") + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + List(selection: selectionBinding) { + ForEach(viewModel.dashboards) { dashboard in + HStack(spacing: 6) { + Image(systemName: "square.grid.2x2") + .foregroundStyle(.secondary) + Text(dashboard.title) + .lineLimit(1) + } + .tag(dashboard.id) + .contextMenu { + Button("Delete", role: .destructive) { + delete(dashboard.id) + } + } + } + } + .listStyle(.sidebar) + } + } + .background(Color(nsColor: .controlBackgroundColor).opacity(0.5)) + .alert("New Dashboard", isPresented: $showingNew) { + TextField("Name", text: $newName) + Button("Create") { + if let ds = appState.dataSource { + viewModel.createDashboard(title: newName, dataSource: ds) + } + } + Button("Cancel", role: .cancel) {} + } + } + + private var selectionBinding: Binding { + Binding( + get: { viewModel.selectedDashboardId }, + set: { newValue in + if let id = newValue { viewModel.select(id) } + } + ) + } + + private func delete(_ id: String) { + guard let ds = appState.dataSource else { return } + viewModel.select(id) + viewModel.deleteSelected(dataSource: ds) + } +} diff --git a/apps/macos/Sequins/Views/Dashboards/DashboardsContentView.swift b/apps/macos/Sequins/Views/Dashboards/DashboardsContentView.swift new file mode 100644 index 00000000..585505d8 --- /dev/null +++ b/apps/macos/Sequins/Views/Dashboards/DashboardsContentView.swift @@ -0,0 +1,72 @@ +import SwiftUI +import SequinsData + +// MARK: - Content Only Wrapper + +struct DashboardsContentOnly: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: DashboardsViewModel + + var body: some View { + DashboardsContentView(viewModel: viewModel) + .task(id: appState.dataSourceId) { + if let ds = appState.dataSource { + viewModel.refresh(dataSource: ds) + } + } + .onAppear { + // Pick up dashboards created elsewhere (e.g. by the assistant) when + // switching to this tab. + if let ds = appState.dataSource { + viewModel.refresh(dataSource: ds) + } + } + } +} + +// MARK: - Dashboards tab + +/// The Dashboards tab: a dashboard list on the left, the selected dashboard's grid on +/// the right. The grid honors the universal live toggle + time-range controls. +struct DashboardsContentView: View { + @Environment(AppStateViewModel.self) private var appState + @Bindable var viewModel: DashboardsViewModel + + var body: some View { + HSplitView { + DashboardListPanel(viewModel: viewModel) + .frame(minWidth: 180, idealWidth: 220, maxWidth: 320) + + detail + .frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity) + } + } + + @ViewBuilder + private var detail: some View { + if appState.dataSource == nil { + VizMessage(icon: "bolt.slash", text: "Not connected to a data source") + } else if viewModel.selected == nil { + VStack(spacing: 12) { + Image(systemName: "square.grid.2x2") + .font(.system(size: 44)) + .foregroundStyle(.secondary) + Text("No dashboard selected") + .font(.title3) + Text("Select a dashboard, or add a visualization from the Assistant.") + .font(.callout) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .frame(maxWidth: 320) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + DashboardGridView( + viewModel: viewModel, + dataSource: appState.dataSource, + timeRange: appState.timeRangeState.timeRange, + isLive: appState.isLive + ) + } + } +} diff --git a/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift b/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift index 55aa4e81..ca36b3e6 100644 --- a/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift +++ b/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift @@ -1,34 +1,58 @@ import SwiftUI +import SequinsData -/// Large centered display for a single scalar value +/// Large centered single-value (stat) display: an aliased, title-cased label; the value +/// formatted with thousands separators / units (durations ns→ms/s); and an optional +/// delta versus the previous period. struct ExploreScalarView: View { let columnName: String let rows: [[Any?]] + var columnType: NodeTypeLabel = .number + /// Value for the same query one window earlier (for the delta), if available. + var previousValue: Double? - private var value: String { + private var currentValue: Double? { + rows.first?.compactMap { VizFormat.numeric($0) }.first + } + + private var display: String { guard let first = rows.first, let cell = first.first else { return "—" } - guard let cell else { return "null" } - switch cell { - case let s as String: return s - case let n as NSNumber: return n.stringValue - case let b as Bool: return b ? "true" : "false" - default: return String(describing: cell) + if let v = VizFormat.numeric(cell) { + switch columnType { + case .duration: return VizFormat.durationNs(v) + default: return VizFormat.number(v) + } } + return VizFormat.string(cell) + } + + private var delta: (text: String, up: Bool)? { + guard let cur = currentValue, let prev = previousValue, prev != 0 else { return nil } + let pct = (cur - prev) / abs(prev) * 100 + let arrow = pct >= 0 ? "▲" : "▼" + return ("\(arrow) \(VizFormat.percent(abs(pct)))", pct >= 0) } var body: some View { - VStack(spacing: 16) { - Text(columnName) + VStack(spacing: 10) { + Text(VizFormat.label(columnName)) .font(.caption) .foregroundStyle(.secondary) .textCase(.uppercase) - Text(value) - .font(.system(size: 56, weight: .bold, design: .monospaced)) + Text(display) + .font(.system(size: 52, weight: .bold, design: .rounded)) .foregroundStyle(.primary) .minimumScaleFactor(0.3) .lineLimit(1) + + if let delta { + Text("\(delta.text) vs prev") + .font(.caption.weight(.medium)) + .foregroundStyle(delta.up ? Color.green : Color.red) + } } .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding() } } diff --git a/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift b/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift index 6dec4767..03c58e39 100644 --- a/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift +++ b/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift @@ -1,63 +1,15 @@ import SwiftUI -import Charts +import SequinsData -/// Time-series chart for SeQL results where first column is a time value +/// Time-series line chart for SeQL results (first column = time/x). Delegates to the +/// shared `TimeSeriesChart` (temporal axis, hover, formatted y, alias legend). struct ExploreTimeSeriesView: View { let columns: [String] let rows: [[Any?]] - - private struct DataPoint: Identifiable { - let id = UUID() - let time: Double - let value: Double - let series: String - } - - private var dataPoints: [DataPoint] { - guard columns.count >= 2 else { return [] } - var points: [DataPoint] = [] - let seriesColumns = columns.dropFirst() - - for row in rows { - guard let timeCell = row.first, - let timeVal = numericValue(of: timeCell) else { continue } - - for (offset, col) in seriesColumns.enumerated() { - let colIdx = offset + 1 - guard colIdx < row.count else { continue } - if let numVal = numericValue(of: row[colIdx]) { - points.append(DataPoint(time: timeVal, value: numVal, series: col)) - } - } - } - return points - } + var columnTypes: [NodeTypeLabel] = [] var body: some View { - if dataPoints.isEmpty { - Text("No time-series data") - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } else { - Chart(dataPoints) { point in - LineMark( - x: .value(columns.first ?? "time", point.time), - y: .value(point.series, point.value) - ) - .foregroundStyle(by: .value("Series", point.series)) - } - .chartXAxisLabel(columns.first ?? "time") + TimeSeriesChart(columns: columns, rows: rows, columnTypes: columnTypes) .padding() - } - } - - private func numericValue(of value: Any?) -> Double? { - guard let value else { return nil } - switch value { - case let n as NSNumber: return n.doubleValue - case let d as Double: return d - case let i as Int: return Double(i) - default: return nil - } } } diff --git a/apps/macos/Sequins/Views/Main/MainWindow.swift b/apps/macos/Sequins/Views/Main/MainWindow.swift index 617941b6..36619a8e 100644 --- a/apps/macos/Sequins/Views/Main/MainWindow.swift +++ b/apps/macos/Sequins/Views/Main/MainWindow.swift @@ -13,6 +13,8 @@ struct MainWindow: View { @State private var logsViewModel = LogsViewModel() @State private var healthViewModel = HealthViewModel() @State private var exploreViewModel = ExploreViewModel() + @State private var assistantViewModel = AssistantViewModel() + @State private var dashboardsViewModel = DashboardsViewModel() @State private var logsSearchText = "" @State private var metricsSearchText = "" @@ -28,14 +30,16 @@ struct MainWindow: View { .navigationSplitViewColumnWidth(min: 160, ideal: 220, max: 300) } detail: { VStack(spacing: 0) { - if let service = appState.selectedService { - // Expandable resource attributes panel - if appState.isServiceAttributesExpanded { - ResourceAttributesPanel(service: service) - Divider() - } + // Expandable resource attributes panel (service tabs only) + if let service = appState.selectedService, appState.isServiceAttributesExpanded { + ResourceAttributesPanel(service: service) + Divider() + } - // Unified filter bar (universal + tab-specific controls) + // Unified filter bar (universal + tab-specific controls). Shown for the + // service tabs and for Dashboards (which uses the universal live + + // time-range controls). Not shown for Assistant. + if appState.selectedService != nil || selectedTab == .dashboards { UnifiedFilterBar( selectedTab: selectedTab, tracesViewModel: tracesViewModel, @@ -60,6 +64,8 @@ struct MainWindow: View { logsViewModel: logsViewModel, healthViewModel: healthViewModel, exploreViewModel: exploreViewModel, + assistantViewModel: assistantViewModel, + dashboardsViewModel: dashboardsViewModel, logsSearchText: $logsSearchText, metricsSearchText: $metricsSearchText ) @@ -160,13 +166,20 @@ struct DetailContentView: View { @Bindable var logsViewModel: LogsViewModel @Bindable var healthViewModel: HealthViewModel @Bindable var exploreViewModel: ExploreViewModel + @Bindable var assistantViewModel: AssistantViewModel + @Bindable var dashboardsViewModel: DashboardsViewModel @Binding var logsSearchText: String @Binding var metricsSearchText: String + /// Tabs that work without a selected service. + private var serviceOptional: Bool { + selectedTab == .explore || selectedTab == .assistant || selectedTab == .dashboards + } + var body: some View { Group { - if appState.selectedService == nil && selectedTab != .explore { - // No service selected - show empty state (Explore doesn't need a service) + if appState.selectedService == nil && !serviceOptional { + // No service selected - show empty state (some tabs don't need a service) NoServiceSelectedView() } else { switch selectedTab { @@ -182,6 +195,10 @@ struct DetailContentView: View { ProfilesContentOnly(viewModel: profilesViewModel) case .explore: ExploreContentOnly(viewModel: exploreViewModel) + case .assistant: + AssistantContentOnly(viewModel: assistantViewModel) + case .dashboards: + DashboardsContentOnly(viewModel: dashboardsViewModel) } } } diff --git a/apps/macos/Sequins/Views/Main/UnifiedFilterBar.swift b/apps/macos/Sequins/Views/Main/UnifiedFilterBar.swift index e506743d..02dfb801 100644 --- a/apps/macos/Sequins/Views/Main/UnifiedFilterBar.swift +++ b/apps/macos/Sequins/Views/Main/UnifiedFilterBar.swift @@ -58,6 +58,10 @@ struct UnifiedFilterBar: View { ProfilesFilterControls(viewModel: profilesViewModel) case .explore: ExploreFilterControls(viewModel: exploreViewModel) + case .assistant, .dashboards: + // Assistant has no tab-specific filters; Dashboards uses the universal + // live + time-range controls above. + EmptyView() } Spacer() diff --git a/apps/macos/Sequins/Views/Settings/AddEnvironmentView.swift b/apps/macos/Sequins/Views/Settings/AddEnvironmentView.swift index b98a9811..abf8611e 100644 --- a/apps/macos/Sequins/Views/Settings/AddEnvironmentView.swift +++ b/apps/macos/Sequins/Views/Settings/AddEnvironmentView.swift @@ -5,8 +5,10 @@ struct AddEnvironmentView: View { @Environment(\.dismiss) private var dismiss @State private var name = "" - @State private var queryURL = "http://localhost:8080/query" - @State private var managementURL = "http://localhost:8080/management" + // The query URL is the daemon's Arrow Flight SQL origin (host:port, no path); the + // management URL is its HTTP API. Defaults match the daemon's default ports. + @State private var queryURL = "http://localhost:4319" + @State private var managementURL = "http://localhost:8081" @State private var connectAfterAdd = true private var isValid: Bool { @@ -41,16 +43,23 @@ struct AddEnvironmentView: View { .textFieldStyle(.roundedBorder) } - Section("Connection") { + Section { LabeledContent("Query URL") { - TextField("URL", text: $queryURL) + TextField("http://host:4319", text: $queryURL) .textFieldStyle(.roundedBorder) } LabeledContent("Management URL") { - TextField("URL", text: $managementURL) + TextField("http://host:8081", text: $managementURL) .textFieldStyle(.roundedBorder) } + } header: { + Text("Connection") + } footer: { + Text("Query URL is the Arrow Flight SQL endpoint (host:port, no path). " + + "Management URL is the HTTP API.") + .font(.caption) + .foregroundStyle(.secondary) } Section { diff --git a/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift b/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift index cbcaa60a..79c94909 100644 --- a/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift +++ b/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift @@ -7,6 +7,9 @@ struct EditEnvironmentView: View { @Bindable var environment: ConnectionEnvironment @State private var needsReconnect = false + /// The assistant API key / bearer token — loaded from and saved to the Keychain + /// (never stored in the SwiftData model). + @State private var assistantSecret = "" private var isValid: Bool { if environment.isLocal { @@ -59,6 +62,9 @@ struct EditEnvironmentView: View { } .formStyle(.grouped) .scrollContentBackground(.hidden) + .task { + assistantSecret = KeychainStore.shared.assistantSecret(environmentId: environment.id) ?? "" + } Divider() @@ -86,7 +92,7 @@ struct EditEnvironmentView: View { } .padding() } - .frame(width: 500, height: environment.isLocal ? 400 : 350) + .frame(width: 500, height: environment.isLocal ? 580 : 520) } @ViewBuilder @@ -154,6 +160,8 @@ struct EditEnvironmentView: View { .font(.caption.monospaced()) .foregroundStyle(.secondary) } + + assistantSection } @ViewBuilder @@ -188,10 +196,56 @@ struct EditEnvironmentView: View { .textFieldStyle(.roundedBorder) } } + + assistantSection + } + + /// Assistant (AI) configuration. Base URL + model persist on the environment; the + /// secret is stored in the Keychain. + @ViewBuilder + private var assistantSection: some View { + Section("Assistant (AI)") { + LabeledContent(environment.isLocal ? "Provider Base URL" : "Daemon /v1 URL") { + TextField( + environment.isLocal ? "https://api.openai.com/v1" : "http://host:8082/v1", + text: optionalBinding(\.assistantBaseURL) + ) + .textFieldStyle(.roundedBorder) + } + + LabeledContent("Model") { + TextField( + environment.isLocal ? "gpt-5.5" : "(optional)", + text: optionalBinding(\.assistantModel) + ) + .textFieldStyle(.roundedBorder) + } + + LabeledContent(environment.isLocal ? "API Key" : "Bearer Token") { + SecureField("", text: $assistantSecret) + .textFieldStyle(.roundedBorder) + } + + Text(environment.isLocal + ? "Stored securely in your Keychain. Required to chat with the assistant." + : "Bearer token for the daemon's assistant endpoint. Stored in your Keychain.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + + private func optionalBinding( + _ keyPath: ReferenceWritableKeyPath + ) -> Binding { + Binding( + get: { environment[keyPath: keyPath] ?? "" }, + set: { environment[keyPath: keyPath] = $0.isEmpty ? nil : $0 } + ) } private func save() { appState.environmentManager.updateEnvironment(environment) + KeychainStore.shared.setAssistantSecret(assistantSecret, environmentId: environment.id) if needsReconnect && environment.isSelected { appState.reconnect() diff --git a/apps/macos/Sequins/Views/Visualization/DataTableView.swift b/apps/macos/Sequins/Views/Visualization/DataTableView.swift new file mode 100644 index 00000000..af3c1006 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/DataTableView.swift @@ -0,0 +1,117 @@ +import SwiftUI +import SequinsData + +/// A columnar, sortable, type-aware table for tabular results. Header click sorts; +/// cells are formatted by their semantic type (timestamps, durations, monospaced ids, +/// grouped numbers) via `VizFormat`. Shows an explicit "showing N of M" when capped. +struct DataTableView: View { + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + + /// Rows rendered before capping (charts stay responsive on huge results). + private let rowCap = 500 + + @State private var sortColumn: Int? + @State private var ascending = true + + private func type(_ i: Int) -> NodeTypeLabel { + i < columnTypes.count ? columnTypes[i] : .unknown + } + + private var sortedRows: [[Any?]] { + guard let col = sortColumn else { return rows } + let sorted = rows.sorted { a, b in + lessThan(a.count > col ? a[col] : nil, b.count > col ? b[col] : nil) + } + return ascending ? sorted : sorted.reversed() + } + + /// a < b, nils last. + private func lessThan(_ a: Any?, _ b: Any?) -> Bool { + switch (a, b) { + case (nil, nil): return false + case (nil, _): return false + case (_, nil): return true + default: break + } + if let an = VizFormat.numeric(a), let bn = VizFormat.numeric(b) { + return an < bn + } + return VizFormat.string(a).localizedCaseInsensitiveCompare(VizFormat.string(b)) == .orderedAscending + } + + var body: some View { + if rows.isEmpty { + VizMessage(icon: "tablecells", text: "No results") + } else { + VStack(spacing: 0) { + ScrollView([.horizontal, .vertical]) { + Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) { + headerRow + ForEach(Array(sortedRows.prefix(rowCap).enumerated()), id: \.offset) { rowIdx, row in + GridRow { + ForEach(columns.indices, id: \.self) { col in + cell(row, col) + .background(rowIdx.isMultiple(of: 2) ? Color.clear : Color.secondary.opacity(0.04)) + } + } + } + } + } + if rows.count > rowCap { + Text("Showing \(rowCap) of \(rows.count) rows") + .font(.caption2) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(6) + .background(Color(nsColor: .controlBackgroundColor)) + } + } + } + } + + private var headerRow: some View { + GridRow { + ForEach(columns.indices, id: \.self) { col in + Button { + if sortColumn == col { ascending.toggle() } else { sortColumn = col; ascending = true } + } label: { + HStack(spacing: 3) { + Text(VizFormat.label(columns[col])) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + if sortColumn == col { + Image(systemName: ascending ? "chevron.up" : "chevron.down") + .font(.system(size: 8)) + } + Spacer(minLength: 0) + } + .foregroundStyle(.secondary) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .frame(minWidth: 90, alignment: .leading) + .background(Color(nsColor: .controlBackgroundColor)) + } + .buttonStyle(.plain) + .overlay(alignment: .bottom) { Divider() } + } + } + } + + @ViewBuilder + private func cell(_ row: [Any?], _ col: Int) -> some View { + let value = col < row.count ? row[col] : nil + let t = type(col) + let text = VizFormat.cell(value, type: t, column: columns[col]) + Text(text) + .font(.system(size: 12, design: (t == .id) ? .monospaced : .default)) + .foregroundStyle(t == .null ? .secondary : .primary) + .lineLimit(1) + .truncationMode(.middle) + .padding(.horizontal, 12) + .padding(.vertical, 5) + .frame(minWidth: 90, maxWidth: 320, alignment: .leading) + .textSelection(.enabled) + } +} diff --git a/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift b/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift new file mode 100644 index 00000000..e44a31d5 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift @@ -0,0 +1,182 @@ +import SwiftUI +import Charts +import SequinsData + +/// A time-series line/area chart shared by the `line` and `area` viz types (and the +/// Explore time-series shape). When the first column is a timestamp it renders a real +/// temporal x-axis (HH:mm ticks) with a hover crosshair + tooltip; otherwise it plots +/// the numeric first column. Y values are unit-formatted; the legend uses the SeQL +/// aliases (now the real column names). +struct TimeSeriesChart: View { + let columns: [String] + let rows: [[Any?]] + let columnTypes: [NodeTypeLabel] + /// Fill under the line (area) vs. a plain line. + var filled: Bool = false + /// Stack the areas/series (area only). + var stacked: Bool = false + + private struct Datum: Identifiable { + let id = UUID() + let date: Date + let num: Double + let series: String + let y: Double + } + + @State private var hoverDate: Date? + @State private var plotFrame: CGRect = .zero + + private var isTemporal: Bool { + if columnTypes.first == .timestamp { return true } + // Fall back to the data: the backend now emits time buckets as Arrow timestamps, + // which arrive as `Date`. + return rows.first?.first is Date + } + + /// Numeric "value" columns (every column after the first that carries numbers). + private var seriesColumns: [(index: Int, name: String)] { + guard columns.count > 1 else { return [] } + return (1.. idx && VizFormat.numeric($0[idx]) != nil } + return numeric ? (idx, columns[idx]) : nil + } + } + + private var data: [Datum] { + guard !columns.isEmpty else { return [] } + let cols = seriesColumns + var out: [Datum] = [] + for row in rows { + guard let xCell = row.first else { continue } + let date = VizFormat.date(xCell, column: columns[0]) ?? (xCell as? Date) ?? Date(timeIntervalSince1970: 0) + let num = VizFormat.numeric(xCell) ?? 0 + for (idx, name) in cols where idx < row.count { + if let y = VizFormat.numeric(row[idx]) { + out.append(Datum(date: date, num: num, series: name, y: y)) + } + } + } + // Sort so each series' line runs left-to-right in time (rows aren't guaranteed + // to arrive time-ordered), otherwise the polyline zig-zags. + return out.sorted { isTemporal ? $0.date < $1.date : $0.num < $1.num } + } + + var body: some View { + let points = data + if points.isEmpty { + VizMessage(icon: "chart.xyaxis.line", text: "No numeric data") + } else if isTemporal { + temporalChart(points) + } else { + numericChart(points) + } + } + + // MARK: - Temporal + + private func temporalChart(_ points: [Datum]) -> some View { + Chart { + ForEach(points) { p in + if filled { + AreaMark( + x: .value("Time", p.date), + y: .value("value", p.y), + stacking: stacked ? .standard : .unstacked + ) + .foregroundStyle(by: .value("Series", p.series)) + .interpolationMethod(.monotone) + .opacity(0.55) + } + LineMark(x: .value("Time", p.date), y: .value("value", p.y)) + .foregroundStyle(by: .value("Series", p.series)) + .interpolationMethod(.monotone) + if points.count <= 60 { + PointMark(x: .value("Time", p.date), y: .value("value", p.y)) + .foregroundStyle(by: .value("Series", p.series)) + .symbolSize(18) + } + } + if let hoverDate { + RuleMark(x: .value("Time", hoverDate)) + .foregroundStyle(.secondary.opacity(0.4)) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [3])) + } + } + .chartYAxis { + AxisMarks { value in + AxisGridLine() + AxisValueLabel { + if let v = value.as(Double.self) { Text(VizFormat.compact(v)) } + } + } + } + .chartLegend(seriesColumns.count > 1 ? .visible : .hidden) + .chartOverlay { proxy in + GeometryReader { geo in + let frame = proxy.plotFrame.map { geo[$0] } ?? .zero + Color.clear + .contentShape(Rectangle()) + .onContinuousHover { phase in + switch phase { + case .active(let loc): + let x = loc.x - frame.origin.x + hoverDate = (x >= 0 && x <= frame.width) ? proxy.value(atX: x) as Date? : nil + case .ended: + hoverDate = nil + } + } + if let hoverDate { + tooltip(near: hoverDate, points: points, frame: frame, proxy: proxy, size: geo.size) + .allowsHitTesting(false) + } + } + } + .padding(.vertical, 4) + } + + @ViewBuilder + private func tooltip(near date: Date, points: [Datum], frame: CGRect, proxy: ChartProxy, size: CGSize) -> some View { + // Nearest actual x present in the data. + let uniqueDates = Array(Set(points.map(\.date))).sorted() + if let nearest = uniqueDates.min(by: { abs($0.timeIntervalSince(date)) < abs($1.timeIntervalSince(date)) }) { + let atX = points.filter { $0.date == nearest } + let rows = seriesColumns.map { col -> (String, Double) in + (col.name, atX.first { $0.series == col.name }?.y ?? 0) + } + let xPos = (proxy.position(forX: nearest) ?? 0) + frame.origin.x + VStack(alignment: .leading, spacing: 3) { + Text(VizFormat.axisTime(nearest, includeSeconds: true)) + .font(.caption2).foregroundStyle(.secondary) + ForEach(rows, id: \.0) { name, y in + Text("\(name): \(VizFormat.number(y))").font(.caption2) + } + } + .padding(6) + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 6)) + .fixedSize() + .position( + x: min(max(xPos, 60), size.width - 60), + y: 34 + ) + } + } + + // MARK: - Numeric fallback + + private func numericChart(_ points: [Datum]) -> some View { + Chart(points) { p in + LineMark(x: .value(columns.first ?? "x", p.num), y: .value("value", p.y)) + .foregroundStyle(by: .value("Series", p.series)) + .interpolationMethod(.monotone) + } + .chartYAxis { + AxisMarks { value in + AxisGridLine() + AxisValueLabel { if let v = value.as(Double.self) { Text(VizFormat.compact(v)) } } + } + } + .chartLegend(seriesColumns.count > 1 ? .visible : .hidden) + .padding(.vertical, 4) + } +} diff --git a/apps/macos/Sequins/Views/Visualization/TraceVizView.swift b/apps/macos/Sequins/Views/Visualization/TraceVizView.swift new file mode 100644 index 00000000..a4b07381 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/TraceVizView.swift @@ -0,0 +1,100 @@ +import SwiftUI +import SequinsData + +/// Renders a span/trace query as a real waterfall: decodes `[Span]` from the result +/// columns (timestamps arrive as `Date`), picks the largest trace, and hands it to the +/// existing `TraceWaterfallView`. Shows a clear message when the result isn't +/// trace-shaped (no `trace_id`/`span_id`). +struct TraceVizView: View { + let columns: [String] + let rows: [[Any?]] + + @State private var selectedSpanId: String? + + private func index(_ names: String...) -> Int? { + for name in names { + if let i = columns.firstIndex(where: { $0.lowercased() == name }) { return i } + } + return nil + } + + private func nanos(_ row: [Any?], _ idx: Int?) -> Int64 { + guard let i = idx, i < row.count else { return 0 } + if let d = row[i] as? Date { return Int64(d.timeIntervalSince1970 * 1_000_000_000) } + if let n = VizFormat.numeric(row[i]) { return Int64(n) } + return 0 + } + + private var spans: [Span] { + guard let traceIdx = index("trace_id", "traceid"), + let spanIdx = index("span_id", "spanid") else { return [] } + let parentIdx = index("parent_span_id", "parentspanid") + let nameIdx = index("name", "operation_name", "span_name") + let startIdx = index("start_time_unix_nano", "start_time", "start") + let endIdx = index("end_time_unix_nano", "end_time", "end") + let durIdx = index("duration_ns", "duration") + let svcIdx = index("service_name", "service") + let statusIdx = index("status", "status_code") + let kindIdx = index("kind", "span_kind") + + var out: [Span] = [] + for row in rows { + guard traceIdx < row.count, spanIdx < row.count else { continue } + let spanId = VizFormat.string(row[spanIdx]) + guard !spanId.isEmpty else { continue } + let parent = parentIdx.flatMap { $0 < row.count ? row[$0] as? String : nil } + .flatMap { $0.isEmpty ? nil : $0 } + let startNs = nanos(row, startIdx) + let endNs = nanos(row, endIdx) + let durNs: Int64 = { + if let d = durIdx, d < row.count, let n = VizFormat.numeric(row[d]) { return Int64(n) } + return max(0, endNs - startNs) + }() + let statusRaw = statusIdx.flatMap { $0 < row.count ? VizFormat.numeric(row[$0]) : nil } ?? 0 + let kindRaw = kindIdx.flatMap { $0 < row.count ? VizFormat.numeric(row[$0]) : nil } ?? 0 + out.append(Span( + traceId: VizFormat.string(row[traceIdx]), + spanId: spanId, + parentSpanId: parent, + serviceName: svcIdx.map { VizFormat.string(row[$0]) } ?? "", + operationName: nameIdx.map { VizFormat.string(row[$0]) } ?? spanId, + startTime: Timestamp(nanoseconds: startNs), + endTime: Timestamp(nanoseconds: endNs > 0 ? endNs : startNs + durNs), + duration: NanoDuration(nanoseconds: durNs), + attributes: [:], + events: [], + status: SpanStatus(rawValue: UInt32(max(0, statusRaw))) ?? .unset, + spanKind: SpanKind(rawValue: UInt32(max(0, kindRaw))) ?? .unspecified + )) + } + return out + } + + var body: some View { + let all = spans + if all.isEmpty { + VizMessage( + icon: "arrow.triangle.branch", + text: "Not trace-shaped — query spans with trace_id/span_id (e.g. `traces last 15m`)." + ) + } else { + let byTrace = Dictionary(grouping: all, by: \.traceId) + let chosen = byTrace.max { $0.value.count < $1.value.count }?.value ?? all + let root = chosen.first { span in + span.parentSpanId == nil || !chosen.contains { $0.spanId == span.parentSpanId } + } ?? chosen.min { $0.startTime.nanoseconds < $1.startTime.nanoseconds } ?? chosen[0] + + VStack(spacing: 4) { + if byTrace.count > 1 { + Text("Showing the largest of \(byTrace.count) traces (\(chosen.count) spans)") + .font(.caption2) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 8) + .padding(.top, 4) + } + TraceWaterfallView(rootSpan: root, allSpans: chosen, selectedSpanId: $selectedSpanId) + } + } + } +} diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift b/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift new file mode 100644 index 00000000..784d2367 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift @@ -0,0 +1,115 @@ +import Foundation +import SequinsData + +/// Runs the query behind a ``VisualizationView`` and exposes its schema, rows, per-column +/// semantic types, and the raw batches reactively. Supports a one-shot snapshot +/// (`executeSeQL`) and a continuously updating live stream (`executeLiveSeQL`). +@MainActor +@Observable +final class VisualizationRunner: SeQLSink { + private(set) var schema: SeQLSchema? + private(set) var rows: [[Any?]] = [] + private(set) var recordTrees: [RecordNode] = [] + /// Semantic type per column (temporal/duration/number/id/…), from the Arrow schema. + private(set) var columnTypes: [NodeTypeLabel] = [] + /// The raw primary-table batches (kept for renderers that need typed decode, e.g. the + /// trace waterfall). + private(set) var primaryBatches: [RecordBatch] = [] + private(set) var errorMessage: String? + private(set) var isLoading = false + + private var snapshotStream: SeQLStream? + private var liveStream: LiveSeQLStream? + + var columns: [String] { schema?.columnNames ?? [] } + var shape: ResponseShape { schema?.shape ?? .table } + + /// (Re)start the query. Cancels any prior stream first. + func start(dataSource: DataSource, query: String, isLive: Bool) { + stop() + errorMessage = nil + rows = [] + recordTrees = [] + columnTypes = [] + primaryBatches = [] + isLoading = true + + guard !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + isLoading = false + return + } + + do { + if isLive { + let stream = try dataSource.executeLiveSeQL(query) + stream.onSchemaCallback = { [weak self] s in + Task { @MainActor in self?.schema = s } + } + stream.onBatchCallback = { [weak self] _, _ in + Task { @MainActor in self?.rebuildFromLive() } + } + stream.onDeltaCallback = { [weak self] _ in + Task { @MainActor in self?.rebuildFromLive() } + } + liveStream = stream + if let s = stream.schema { schema = s } + rebuildFromLive() + isLoading = false + } else { + snapshotStream = try dataSource.executeSeQL(query, sink: self) + } + } catch { + errorMessage = error.localizedDescription + isLoading = false + } + } + + func stop() { + snapshotStream?.cancel() + snapshotStream = nil + liveStream?.cancel() + liveStream = nil + } + + private func rebuildFromLive() { + guard let stream = liveStream else { return } + if let s = stream.schema { schema = s } + let batches = stream.batches + primaryBatches = batches + rows = batches.flatMap { $0.toRows() } + recordTrees = batches.flatMap { $0.toRecordTrees() } + if let first = batches.first { columnTypes = first.columnTypeLabels() } + } + + // MARK: - SeQLSink (snapshot; callbacks arrive off the main thread) + + nonisolated func onSchema(_ schema: SeQLSchema) { + Task { @MainActor in self.schema = schema } + } + + nonisolated func onBatch(_ batch: RecordBatch, table: String?) { + guard table == nil else { return } + let newRows = batch.toRows() + let newTrees = batch.toRecordTrees() + let types = batch.columnTypeLabels() + Task { @MainActor in + self.rows.append(contentsOf: newRows) + self.recordTrees.append(contentsOf: newTrees) + self.primaryBatches.append(batch) + if self.columnTypes.isEmpty { self.columnTypes = types } + } + } + + nonisolated func onComplete(_ stats: SeQLStats) { + Task { @MainActor in self.isLoading = false } + } + + nonisolated func onWarning(code: UInt32, message: String) {} + + nonisolated func onError(code: UInt32, message: String) { + Task { @MainActor in + self.errorMessage = message + self.isLoading = false + } + } +} diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift new file mode 100644 index 00000000..121f483c --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift @@ -0,0 +1,159 @@ +import SwiftUI +import SequinsData + +/// The shared visualization component: given a saved visualization descriptor +/// (`{ seql, title, vizType? }`), a data source, a time range, and a live flag, it +/// runs the query and renders the chart/table best suited to the data. Used inline in +/// the Assistant chat and as dashboard panels. +struct VisualizationView: View { + let visualization: SavedVisualization + let dataSource: DataSource? + var timeRange: TimeRange = .relative(duration: 3600) + var isLive: Bool = false + /// Whether to rewrite the query's time-scope with `timeRange` (dashboards) or run it + /// verbatim (chat, where the assistant chose the window). + var applyTimeRange: Bool = false + /// Optional user/model override; falls back to the stored type, then auto-select. + var vizTypeOverride: VizType? = nil + + @State private var runner = VisualizationRunner() + /// Runs the same query one window earlier, to compute a stat delta. + @State private var prevRunner = VisualizationRunner() + + /// The type actually rendered: explicit override → stored `shape` → auto-selected. + var effectiveVizType: VizType { + vizTypeOverride + ?? visualization.vizType + ?? VizType.autoSelect(shape: runner.shape, columns: runner.columns, rows: runner.rows) + } + + /// The prior-period scalar value (for a stat's delta), when loaded. + private var previousStatValue: Double? { + prevRunner.rows.first?.compactMap { VizFormat.numeric($0) }.first + } + + /// The query to execute — time-scope rewritten when `applyTimeRange` is set. + private var effectiveQuery: String { + applyTimeRange ? timeRange.applied(to: visualization.seql) : visualization.seql + } + + /// Restart key — re-runs the query when the query, live flag, or time window change. + /// + /// Must be STABLE across re-renders: a relative range keys on its duration (not the + /// live `bounds`, which advance every render and would restart the query on every + /// frame — freezing the view), an absolute range on its fixed endpoints. + private var reloadKey: String { + let rangeKey: String + switch timeRange { + case .relative(let duration): + rangeKey = "r\(duration)" + case .absolute(let start, let end): + rangeKey = "a\(start.timeIntervalSince1970)-\(end.timeIntervalSince1970)" + } + return "\(effectiveQuery)|\(isLive)|\(rangeKey)" + } + + var body: some View { + Group { + if let error = runner.errorMessage { + VizMessage(icon: "exclamationmark.triangle", text: error) + } else if runner.isLoading && runner.rows.isEmpty { + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if runner.rows.isEmpty && runner.schema != nil { + VizMessage(icon: "tray", text: "No data") + } else { + VizRenderer( + vizType: effectiveVizType, + columns: runner.columns, + rows: runner.rows, + columnTypes: runner.columnTypes, + recordTrees: runner.recordTrees, + previousValue: previousStatValue + ) + } + } + .task(id: reloadKey) { + guard let dataSource else { return } + runner.start(dataSource: dataSource, query: effectiveQuery, isLive: isLive) + } + .task(id: "\(reloadKey)|stat=\(effectiveVizType == .stat)") { + // For a stat, run the same query one window earlier for the delta. + prevRunner.stop() + guard effectiveVizType == .stat, applyTimeRange, let dataSource else { return } + let bounds = timeRange.bounds + let duration = bounds.end.timeIntervalSince(bounds.start) + guard duration > 0 else { return } + let prior = TimeRange.absolute( + start: bounds.start.addingTimeInterval(-duration), + end: bounds.start + ) + prevRunner.start(dataSource: dataSource, query: prior.applied(to: visualization.seql), isLive: false) + } + .onDisappear { + runner.stop() + prevRunner.stop() + } + } +} + +/// Switches to the concrete chart/table view for a `VizType`. Reuses the Explore leaf +/// views for line/stat/table/trace, and the app-side chart views for the rest. +struct VizRenderer: View { + let vizType: VizType + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + let recordTrees: [RecordNode] + var previousValue: Double? + + var body: some View { + switch vizType { + case .line: + ExploreTimeSeriesView(columns: columns, rows: rows, columnTypes: columnTypes) + case .area: + AreaChartView(columns: columns, rows: rows, columnTypes: columnTypes) + case .bar: + BarChartView(columns: columns, rows: rows, stacked: false, columnTypes: columnTypes) + case .stackedBar: + BarChartView(columns: columns, rows: rows, stacked: true, columnTypes: columnTypes) + case .pie: + PieChartView(columns: columns, rows: rows, columnTypes: columnTypes) + case .gauge: + GaugeChartView(columns: columns, rows: rows, columnTypes: columnTypes) + case .stat: + ExploreScalarView( + columnName: columns.first ?? "value", + rows: rows, + columnType: columnTypes.first ?? .number, + previousValue: previousValue + ) + case .table: + DataTableView(columns: columns, rows: rows, columnTypes: columnTypes) + case .heatmap: + HeatmapChartView(columns: columns, rows: rows, columnTypes: columnTypes) + case .trace: + TraceVizView(columns: columns, rows: rows) + } + } +} + +/// A centered icon + message placeholder (empty/error states). +struct VizMessage: View { + let icon: String + let text: String + + var body: some View { + VStack(spacing: 8) { + Image(systemName: icon) + .font(.title2) + .foregroundStyle(.secondary) + Text(text) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding() + } +} diff --git a/apps/macos/Sequins/Views/Visualization/VizCharts.swift b/apps/macos/Sequins/Views/Visualization/VizCharts.swift new file mode 100644 index 00000000..ceb47328 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/VizCharts.swift @@ -0,0 +1,300 @@ +import SwiftUI +import Charts +import SequinsData + +// Chart leaf views for the shared visualization component. Each consumes generic +// `columns` + `rows` (+ per-column `columnTypes`), formats via `VizFormat`, and degrades +// gracefully when the data doesn't fit. + +/// Max categories a bar/pie shows before folding the tail into "Other". +private let categoryCap = 12 + +// MARK: - Area + +struct AreaChartView: View { + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + + var body: some View { + TimeSeriesChart(columns: columns, rows: rows, columnTypes: columnTypes, + filled: true, stacked: true) + } +} + +// MARK: - Bar / Stacked Bar + +struct BarChartView: View { + let columns: [String] + let rows: [[Any?]] + var stacked: Bool = false + var columnTypes: [NodeTypeLabel] = [] + + private struct Bar: Identifiable { + let id = UUID(); let category: String; let value: Double; let series: String + } + + /// Numeric value columns. + private var valueCols: [(index: Int, name: String)] { + guard columns.count > 1 else { return [] } + return (1.. idx && VizFormat.numeric($0[idx]) != nil } ? (idx, columns[idx]) : nil + } + } + + private var singleSeries: Bool { valueCols.count == 1 } + + /// Bars, sorted by total value desc with the tail folded into "Other" (single-series). + private var bars: [Bar] { + let cols = valueCols + guard !cols.isEmpty else { return [] } + var raw: [(category: String, series: [(String, Double)])] = [] + for row in rows { + guard let cat = row.first else { continue } + let category = VizFormat.string(cat) + let series = cols.compactMap { c -> (String, Double)? in + guard c.index < row.count, let v = VizFormat.numeric(row[c.index]) else { return nil } + return (c.name, v) + } + raw.append((category, series)) + } + // Sort + top-N only for the single-series case (where a category ranking is meaningful). + if singleSeries { + raw.sort { ($0.series.first?.1 ?? 0) > ($1.series.first?.1 ?? 0) } + if raw.count > categoryCap { + let head = Array(raw.prefix(categoryCap)) + let tail = raw.dropFirst(categoryCap) + let otherTotal = tail.reduce(0.0) { $0 + ($1.series.first?.1 ?? 0) } + var combined = head + combined.append((category: "Other", series: [(cols[0].name, otherTotal)])) + raw = combined + } + } + return raw.flatMap { entry in + entry.series.map { Bar(category: entry.category, value: $0.1, series: $0.0) } + } + } + + var body: some View { + let bars = self.bars + if bars.isEmpty { + VizMessage(icon: "chart.bar", text: "No numeric data") + } else { + Chart(bars) { bar in + let mark = BarMark( + x: .value(columns.first ?? "category", bar.category), + y: .value("value", bar.value) + ) + .foregroundStyle(by: .value("Series", bar.series)) + if stacked { + mark + } else { + mark.position(by: .value("Series", bar.series)) + } + } + .chartYAxis { + AxisMarks { v in + AxisGridLine() + AxisValueLabel { if let d = v.as(Double.self) { Text(VizFormat.compact(d)) } } + } + } + .chartXAxis { + AxisMarks { _ in + AxisValueLabel(orientation: bars.count > 6 ? .verticalReversed : .horizontal) + } + } + .chartLegend(valueCols.count > 1 ? .visible : .hidden) + .padding() + } + } +} + +// MARK: - Pie / Donut + +struct PieChartView: View { + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + + private struct Slice: Identifiable { + let id = UUID(); let category: String; let value: Double + } + + /// True when the data looks like a time series (pie is the wrong chart for it). + private var looksTemporal: Bool { + columnTypes.first == .timestamp || rows.first?.first is Date + } + + private var slices: [Slice] { + guard columns.count >= 2 else { return [] } + let valueIdx = (1.. idx && VizFormat.numeric($0[idx]) != nil } + } ?? 1 + var out: [Slice] = rows.compactMap { row in + guard !row.isEmpty, valueIdx < row.count, let v = VizFormat.numeric(row[valueIdx]) else { return nil } + return Slice(category: VizFormat.string(row.first ?? nil), value: v) + } + out.sort { $0.value > $1.value } + if out.count > categoryCap { + let head = Array(out.prefix(categoryCap)) + let other = out.dropFirst(categoryCap).reduce(0.0) { $0 + $1.value } + out = head + [Slice(category: "Other", value: other)] + } + return out + } + + var body: some View { + let slices = self.slices + let total = slices.reduce(0.0) { $0 + $1.value } + if looksTemporal { + VizMessage(icon: "chart.pie", text: "Pie needs categorical data — try a line or bar chart for a time series.") + } else if slices.isEmpty || total <= 0 { + VizMessage(icon: "chart.pie", text: "No data") + } else { + Chart(slices) { slice in + SectorMark( + angle: .value("value", slice.value), + innerRadius: .ratio(0.6), + angularInset: 1.5 + ) + .foregroundStyle(by: .value("category", slice.category)) + .cornerRadius(3) + .annotation(position: .overlay) { + let pct = slice.value / total + if pct >= 0.05 { + Text(VizFormat.percent(pct * 100)) + .font(.caption2).bold() + .foregroundStyle(.white) + } + } + } + .chartBackground { _ in + // Center KPI (donut hole): the total. + VStack(spacing: 0) { + Text(VizFormat.compact(total)).font(.headline) + Text("total").font(.caption2).foregroundStyle(.secondary) + } + } + .padding() + } + } +} + +// MARK: - Gauge + +struct GaugeChartView: View { + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + + private var value: Double? { + rows.first?.compactMap { VizFormat.numeric($0) }.first + } + + /// A "max" from a second numeric column named max/limit/total, else a nice upper bound. + private var upperBound: Double { + if let row = rows.first { + for (i, name) in columns.enumerated() where i > 0 { + let n = name.lowercased() + if (n.contains("max") || n.contains("limit") || n.contains("total")), + i < row.count, let m = VizFormat.numeric(row[i]), m > 0 { + return m + } + } + } + guard let v = value, v > 0 else { return 1 } + // Round up to a "nice" bound above the value. + let magnitude = pow(10, floor(log10(v))) + return (ceil(v / magnitude) * magnitude).nice() + } + + var body: some View { + if let value { + let upper = max(upperBound, value) + Gauge(value: value, in: 0...upper) { + Text(VizFormat.label(columns.first ?? "value")) + } currentValueLabel: { + Text(VizFormat.number(value)) + } minimumValueLabel: { + Text(VizFormat.compact(0)).font(.caption2) + } maximumValueLabel: { + Text(VizFormat.compact(upper)).font(.caption2) + } + .gaugeStyle(.accessoryCircular) + .tint(Gradient(colors: [.green, .yellow, .orange, .red])) + .scaleEffect(1.8) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(40) + } else { + VizMessage(icon: "gauge.medium", text: "No numeric value") + } + } +} + +private extension Double { + /// Round a bound up to 1/2/5×10ⁿ. + func nice() -> Double { + guard self > 0 else { return 1 } + let mag = pow(10, floor(log10(self))) + let norm = self / mag + let n: Double = norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 5 ? 5 : 10 + return n * mag + } +} + +// MARK: - Heatmap + +struct HeatmapChartView: View { + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + + private struct Cell: Identifiable { + let id = UUID(); let date: Date?; let x: String; let y: String; let value: Double + } + + private var isTemporalX: Bool { + columnTypes.first == .timestamp || rows.first?.first is Date + } + + private var cells: [Cell] { + guard columns.count >= 3 else { return [] } + return rows.compactMap { row in + guard row.count >= 3, let v = VizFormat.numeric(row[2]) else { return nil } + return Cell( + date: VizFormat.date(row[0], column: columns[0]) ?? row[0] as? Date, + x: VizFormat.string(row[0]), + y: VizFormat.string(row[1]), + value: v + ) + } + } + + var body: some View { + let cells = self.cells + if cells.isEmpty { + VizMessage(icon: "square.grid.3x3.fill", text: "Heatmap needs 3 columns (x, y, value)") + } else { + Chart(cells) { c in + if isTemporalX, let date = c.date { + RectangleMark( + x: .value(columns[0], date, unit: .minute), + y: .value(columns[1], c.y) + ) + .foregroundStyle(by: .value(columns[2], c.value)) + } else { + RectangleMark(x: .value(columns[0], c.x), y: .value(columns[1], c.y)) + .foregroundStyle(by: .value(columns[2], c.value)) + } + } + .chartForegroundStyleScale( + range: Gradient(colors: [ + Color(.sRGB, red: 0.1, green: 0.15, blue: 0.35), + .blue, .green, .yellow, .orange, .red, + ]) + ) + .chartLegend(.visible) + .padding() + } + } +} diff --git a/apps/macos/Sequins/Views/Visualization/VizData.swift b/apps/macos/Sequins/Views/Visualization/VizData.swift new file mode 100644 index 00000000..963cf8d4 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/VizData.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Small helpers for mapping loosely-typed SeQL/SQL result rows (`[[Any?]]`) into the +/// numeric/category values the shared visualization charts consume. +enum VizData { + /// Best-effort numeric coercion for a single cell. + static func numeric(_ value: Any?) -> Double? { + guard let value else { return nil } + switch value { + case let n as NSNumber: return n.doubleValue + case let d as Double: return d + case let i as Int: return Double(i) + case let u as UInt64: return Double(u) + case let i as Int64: return Double(i) + case let date as Date: return date.timeIntervalSince1970 + case let s as String: return Double(s) + default: return nil + } + } + + /// Display string for a single cell. + static func string(_ value: Any?) -> String { + guard let value else { return "" } + switch value { + case let s as String: return s + case let n as NSNumber: return n.stringValue + case let b as Bool: return b ? "true" : "false" + case let d as Date: return d.formatted(date: .abbreviated, time: .standard) + default: return String(describing: value) + } + } + + /// The indices/names of numeric "value" columns — every column after the first for + /// which at least one row holds a numeric value. + static func valueColumns(columns: [String], rows: [[Any?]]) -> [(index: Int, name: String)] { + guard columns.count > 1 else { return [] } + return (1.. Double? { + for cell in row { + if let v = numeric(cell) { return v } + } + return nil + } + + /// (category, value) pairs from the first (category) column and the first numeric + /// value column — used by bar and pie charts. + static func categoryValues(columns: [String], rows: [[Any?]]) -> [(category: String, value: Double)] { + guard !columns.isEmpty else { return [] } + let valueIdx = valueColumns(columns: columns, rows: rows).first?.index ?? (columns.count > 1 ? 1 : 0) + return rows.compactMap { row in + guard !row.isEmpty else { return nil } + let category = string(row.first ?? nil) + guard valueIdx < row.count, let value = numeric(row[valueIdx]) else { return nil } + return (category, value) + } + } +} diff --git a/apps/macos/Sequins/Views/Visualization/VizTypePicker.swift b/apps/macos/Sequins/Views/Visualization/VizTypePicker.swift new file mode 100644 index 00000000..16d302ee --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/VizTypePicker.swift @@ -0,0 +1,35 @@ +import SwiftUI +import SequinsData + +/// A compact menu for switching the `VizType` of a rendered visualization. `nil` +/// selection means "auto-select from the data". +struct VizTypePicker: View { + @Binding var selection: VizType? + /// The types offered; defaults to all. + var available: [VizType] = VizType.allCases + + var body: some View { + Menu { + Button { + selection = nil + } label: { + Label("Auto", systemImage: "wand.and.stars") + } + Divider() + ForEach(available, id: \.self) { type in + Button { + selection = type + } label: { + Label(type.displayName, systemImage: type.systemImage) + } + } + } label: { + Image(systemName: (selection ?? .table).systemImage) + .font(.caption) + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() + .help("Change visualization type") + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift new file mode 100644 index 00000000..f5ba2ff8 --- /dev/null +++ b/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift @@ -0,0 +1,276 @@ +import Foundation +import Observation +import SequinsFFI + +// MARK: - Assistant configuration + +/// LLM/provider configuration for constructing an ``Assistant``. +/// +/// - **Local** data source: `baseURL`/`model`/`apiKey` describe the backing +/// OpenAI-compatible provider (`baseURL` nil ⇒ api.openai.com). +/// - **Remote** data source: `baseURL` is the daemon's `/v1` base (e.g. +/// `http://host:8082/v1`), `apiKey` is the bearer token, `model` is ignored. +public struct AssistantConfig: Sendable { + public var baseURL: String? + public var model: String? + public var apiKey: String? + + public init(baseURL: String? = nil, model: String? = nil, apiKey: String? = nil) { + self.baseURL = baseURL + self.model = model + self.apiKey = apiKey + } + + /// Build from `OPENAI_API_KEY` / `OPENAI_BASE_URL` / `OPENAI_MODEL` process + /// environment variables — a dev/CI convenience that mirrors the daemon's + /// auto-enable. Returns `nil` when no key is present. + public static func fromProcessEnvironment() -> AssistantConfig? { + let env = ProcessInfo.processInfo.environment + guard let key = env["OPENAI_API_KEY"], !key.isEmpty else { return nil } + return AssistantConfig( + baseURL: env["OPENAI_BASE_URL"], + model: env["OPENAI_MODEL"] ?? "gpt-5.5", + apiKey: key + ) + } +} + +/// A server-executed tool call and its rendered result (assistant "activity"). +public struct AssistantToolActivity: Identifiable, Hashable, Sendable { + public let id = UUID() + public let name: String + public let arguments: String + public let output: String + + public init(name: String, arguments: String, output: String) { + self.name = name + self.arguments = arguments + self.output = output + } +} + +/// A tool the client is expected to handle — e.g. `render_visualization`. +public struct AssistantToolCall: Identifiable, Hashable, Sendable { + public let id = UUID() + public let name: String + /// Raw JSON string of the tool arguments. + public let arguments: String + + public init(name: String, arguments: String) { + self.name = name + self.arguments = arguments + } +} + +// MARK: - Assistant handle + +/// A constructed assistant (Local in-process middleware model, or Remote daemon). +/// +/// Retains the ``DataSource`` it was built over (the FFI requires the data source to +/// outlive the assistant). Freed on `deinit`. +public final class Assistant { + private let pointer: OpaquePointer + private let dataSource: DataSource + + fileprivate init(pointer: OpaquePointer, dataSource: DataSource) { + self.pointer = pointer + self.dataSource = dataSource + } + + deinit { + sequins_assistant_free(pointer) + } + + /// Start a chat turn. `requestJSON` is an OpenAI Responses-shaped request + /// (`model`, `input`, `tools`, `instructions`, `previous_response_id`, …). + /// Returns an observable stream that emits text, tool activity, client tool + /// calls, and a terminal done/error. + @discardableResult + public func chat(requestJSON: String) throws -> AssistantChatStream { + let stream = AssistantChatStream() + let context = AssistantContext(stream: stream) + let ctxRaw = Unmanaged.passUnretained(context).toOpaque() + + var vtable = CAssistantEventVTable() + + vtable.on_text = { (textPtr, ctxPtr) in + guard let textPtr, let ctxPtr else { return } + let text = String(cString: textPtr) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + DispatchQueue.main.async { ctx.stream?.appendText(text) } + } + + vtable.on_tool_activity = { (actPtr, ctxPtr) in + guard let actPtr, let ctxPtr else { return } + let a = actPtr.pointee + let activity = AssistantToolActivity( + name: a.name.map { String(cString: $0) } ?? "", + arguments: a.arguments.map { String(cString: $0) } ?? "", + output: a.output.map { String(cString: $0) } ?? "" + ) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + DispatchQueue.main.async { ctx.stream?.appendActivity(activity) } + } + + vtable.on_tool_call = { (callPtr, ctxPtr) in + guard let callPtr, let ctxPtr else { return } + let c = callPtr.pointee + let call = AssistantToolCall( + name: c.name.map { String(cString: $0) } ?? "", + arguments: c.arguments.map { String(cString: $0) } ?? "" + ) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + DispatchQueue.main.async { ctx.stream?.appendToolCall(call) } + } + + vtable.on_done = { (donePtr, ctxPtr) in + guard let donePtr, let ctxPtr else { return } + let d = donePtr.pointee + let responseId = d.response_id.map { String(cString: $0) } + let conversationId = d.conversation_id.map { String(cString: $0) } + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + DispatchQueue.main.async { ctx.stream?.finish(responseId: responseId, conversationId: conversationId) } + } + + vtable.on_error = { (msgPtr, ctxPtr) in + guard let ctxPtr else { return } + let message = msgPtr.map { String(cString: $0) } ?? "assistant error" + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + DispatchQueue.main.async { ctx.stream?.fail(message: message) } + } + + let handle = requestJSON.withCString { reqPtr in + sequins_assistant_chat(pointer, reqPtr, vtable, ctxRaw) + } + guard let handle else { + throw SequinsError.ffiError("failed to start assistant chat stream") + } + stream.setHandle(handle) + stream.assistant = self + stream._contextRetainer = context + return stream + } +} + +extension DataSource { + /// Construct an ``Assistant`` over this data source and provider/daemon config. + public func makeAssistant(_ config: AssistantConfig) throws -> Assistant { + // strdup the config strings; `sequins_assistant_new` copies them synchronously, + // so we free right after the call. + let baseURL = config.baseURL.map { strdup($0) } ?? nil + let model = config.model.map { strdup($0) } ?? nil + let apiKey = config.apiKey.map { strdup($0) } ?? nil + defer { + if let baseURL { free(baseURL) } + if let model { free(model) } + if let apiKey { free(apiKey) } + } + + let cConfig = CAssistantConfig(base_url: baseURL, model: model, api_key: apiKey) + var errorPtr: UnsafeMutablePointer? + guard let pointer = sequins_assistant_new(rawPointer, cConfig, &errorPtr) else { + if let errorPtr { + let msg = String(cString: errorPtr) + sequins_string_free(errorPtr) + throw SequinsError.ffiError(msg) + } + throw SequinsError.ffiError("failed to construct assistant") + } + return Assistant(pointer: pointer, dataSource: self) + } +} + +// MARK: - Chat stream + +/// Context bridge for `AssistantChatStream` callbacks (passed as `void*`). +final class AssistantContext { + weak var stream: AssistantChatStream? + init(stream: AssistantChatStream) { self.stream = stream } +} + +/// An `@Observable` streaming chat turn. Text accumulates in `assistantText`; server +/// tool activity and client tool calls are surfaced as they arrive; `isComplete` flips +/// on the terminal `done`/`error`. `deinit` frees the Rust stream (which blocks until +/// the task stops, so no callback fires afterward). +@Observable +public final class AssistantChatStream { + /// Accumulated assistant text for this turn. + public private(set) var assistantText: String = "" + /// Server-executed tool activity (e.g. `run_seql`) surfaced for rendering. + public private(set) var toolActivities: [AssistantToolActivity] = [] + /// Client tool calls the app must handle (e.g. `render_visualization`). + public private(set) var toolCalls: [AssistantToolCall] = [] + /// Continuation ids (set on `done`): pass `responseId` as `previous_response_id`. + public private(set) var responseId: String? + public private(set) var conversationId: String? + /// Last error message, if any. + public private(set) var errorMessage: String? + /// Whether the turn has ended (done or error). + public private(set) var isComplete: Bool = false + + /// Fired for each streamed text delta (in addition to `assistantText`). + public var onText: ((String) -> Void)? + /// Fired when a client tool call (e.g. `render_visualization`) arrives. + public var onToolCall: ((AssistantToolCall) -> Void)? + /// Fired when a server tool activity arrives. + public var onToolActivity: ((AssistantToolActivity) -> Void)? + /// Fired once on completion (`responseId`, `conversationId`). + public var onDone: ((_ responseId: String?, _ conversationId: String?) -> Void)? + + private var handle: OpaquePointer? + /// Retains the assistant (FFI requires it to outlive the stream) and the context. + fileprivate var assistant: Assistant? + var _contextRetainer: AnyObject? + + init() {} + + func setHandle(_ h: OpaquePointer) { handle = h } + + // All `apply*`/`append*` methods below are called on the main thread. + func appendText(_ text: String) { + assistantText += text + onText?(text) + } + + func appendActivity(_ activity: AssistantToolActivity) { + toolActivities.append(activity) + onToolActivity?(activity) + } + + func appendToolCall(_ call: AssistantToolCall) { + toolCalls.append(call) + onToolCall?(call) + } + + func finish(responseId: String?, conversationId: String?) { + self.responseId = responseId + self.conversationId = conversationId + self.isComplete = true + onDone?(responseId, conversationId) + } + + func fail(message: String) { + self.errorMessage = message + self.isComplete = true + } + + public func cancel() { + if let h = handle { + sequins_assistant_cancel(h) + } + } + + deinit { + guard let h = handle else { return } + handle = nil + let retainer = _contextRetainer + _contextRetainer = nil + let keepAssistant = assistant + assistant = nil + DispatchQueue.global(qos: .utility).async { + sequins_assistant_stream_free(h) + _ = retainer + _ = keepAssistant + } + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift new file mode 100644 index 00000000..d8d9fb99 --- /dev/null +++ b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift @@ -0,0 +1,226 @@ +import Foundation +import SequinsFFI + +// MARK: - Dashboard model (mirrors `sequins_metadata::types`) + +/// A saved visualization: a SeQL query plus presentation hints. `shape` is a free-form +/// string holding the app's `VizType` raw value (or a `ResponseShape` string); `nil` +/// lets the client auto-select. +public struct SavedVisualization: Codable, Hashable, Sendable { + public var seql: String + public var title: String + public var shape: String? + + public init(seql: String, title: String, shape: String? = nil) { + self.seql = seql + self.title = title + self.shape = shape + } + + /// The app-side visualization type, backed by the free-form `shape` string. + /// `nil` means "auto-select from the query result". + public var vizType: VizType? { + get { VizType.from(shapeString: shape) } + set { shape = newValue?.rawValue } + } +} + +/// Default dashboard row height, in points (mirrors `DEFAULT_ROW_HEIGHT` in Rust). +public let defaultRowHeight: Double = 280 + +/// A panel within a row: a visualization and its relative width weight. The row +/// normalizes weights across its panels to fill the full width. +public struct RowPanel: Codable, Hashable, Sendable, Identifiable { + /// Client-only stable identity for SwiftUI (not part of the wire format). + public let id: UUID + public var visualization: SavedVisualization + public var weight: Double + + public init(visualization: SavedVisualization, weight: Double = 1.0) { + self.id = UUID() + self.visualization = visualization + self.weight = weight + } + + private enum CodingKeys: String, CodingKey { case visualization, weight } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.id = UUID() + self.visualization = try c.decode(SavedVisualization.self, forKey: .visualization) + self.weight = try c.decodeIfPresent(Double.self, forKey: .weight) ?? 1.0 + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(visualization, forKey: .visualization) + try c.encode(weight, forKey: .weight) + } +} + +/// A full-width dashboard row: a height and an ordered set of panels split by weight. +public struct DashboardRow: Codable, Hashable, Sendable, Identifiable { + public let id: UUID + public var height: Double + public var panels: [RowPanel] + + public init(height: Double = defaultRowHeight, panels: [RowPanel] = []) { + self.id = UUID() + self.height = height + self.panels = panels + } + + private enum CodingKeys: String, CodingKey { case height, panels } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.id = UUID() + self.height = try c.decodeIfPresent(Double.self, forKey: .height) ?? defaultRowHeight + self.panels = try c.decodeIfPresent([RowPanel].self, forKey: .panels) ?? [] + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(height, forKey: .height) + try c.encode(panels, forKey: .panels) + } + + /// Sum of panel weights (>= a small epsilon so division is safe). + public var totalWeight: Double { + max(0.0001, panels.reduce(0) { $0 + $1.weight }) + } +} + +/// A dashboard: an ordered stack of full-width rows. +public struct Dashboard: Codable, Hashable, Sendable, Identifiable { + public var id: String + public var title: String + public var createdAtNs: UInt64 + public var updatedAtNs: UInt64 + public var rows: [DashboardRow] + + public init( + id: String = "", + title: String, + createdAtNs: UInt64 = 0, + updatedAtNs: UInt64 = 0, + rows: [DashboardRow] = [] + ) { + self.id = id + self.title = title + self.createdAtNs = createdAtNs + self.updatedAtNs = updatedAtNs + self.rows = rows + } + + private enum CodingKeys: String, CodingKey { + case id, title, createdAtNs, updatedAtNs, rows + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.id = try c.decode(String.self, forKey: .id) + self.title = try c.decode(String.self, forKey: .title) + self.createdAtNs = try c.decodeIfPresent(UInt64.self, forKey: .createdAtNs) ?? 0 + self.updatedAtNs = try c.decodeIfPresent(UInt64.self, forKey: .updatedAtNs) ?? 0 + self.rows = try c.decodeIfPresent([DashboardRow].self, forKey: .rows) ?? [] + } + + /// Total number of panels across all rows. + public var panelCount: Int { rows.reduce(0) { $0 + $1.panels.count } } +} + +// MARK: - JSON coding (snake_case wire format) + +enum DashboardJSON { + static let encoder: JSONEncoder = { + let e = JSONEncoder() + e.keyEncodingStrategy = .convertToSnakeCase + return e + }() + static let decoder: JSONDecoder = { + let d = JSONDecoder() + d.keyDecodingStrategy = .convertFromSnakeCase + return d + }() +} + +// MARK: - DataSource dashboard CRUD (over the normalized dashboard FFI) + +extension DataSource { + /// List all dashboards (local `Storage` or remote Pro daemon, transparently). + public func listDashboards() throws -> [Dashboard] { + let json = try callJSON { out, err in + sequins_dashboard_list(rawPointer, out, err) + } + return try DashboardJSON.decoder.decode([Dashboard].self, from: Data(json.utf8)) + } + + /// Fetch a dashboard by id, or `nil` if it does not exist. + public func getDashboard(id: String) throws -> Dashboard? { + let json = try id.withCString { idPtr in + try callJSON { out, err in + sequins_dashboard_get(rawPointer, idPtr, out, err) + } + } + if json == "null" { return nil } + return try DashboardJSON.decoder.decode(Dashboard?.self, from: Data(json.utf8)) + } + + /// Create or update a dashboard. Returns the stored dashboard (with id/timestamps). + @discardableResult + public func saveDashboard(_ dashboard: Dashboard) throws -> Dashboard { + let data = try DashboardJSON.encoder.encode(dashboard) + let jsonIn = String(decoding: data, as: UTF8.self) + let json = try jsonIn.withCString { inPtr in + try callJSON { out, err in + sequins_dashboard_save(rawPointer, inPtr, out, err) + } + } + return try DashboardJSON.decoder.decode(Dashboard.self, from: Data(json.utf8)) + } + + /// Delete a dashboard by id. + public func deleteDashboard(id: String) throws { + var errorPtr: UnsafeMutablePointer? + let ok = id.withCString { idPtr in + sequins_dashboard_delete(rawPointer, idPtr, &errorPtr) + } + if !ok { + throw ffiError(errorPtr, fallback: "failed to delete dashboard") + } + } + + // MARK: - Shared JSON out-param helper + + /// Invoke an FFI function shaped `bool f(…, char **out_json, char **error_out)`, + /// returning the owned JSON string (freed here) or throwing the error string. + fileprivate func callJSON( + _ body: (_ out: UnsafeMutablePointer?>, + _ err: UnsafeMutablePointer?>) -> Bool + ) throws -> String { + var outPtr: UnsafeMutablePointer? + var errorPtr: UnsafeMutablePointer? + let ok = body(&outPtr, &errorPtr) + if !ok { + throw ffiError(errorPtr, fallback: "dashboard operation failed") + } + guard let outPtr else { + throw SequinsError.ffiError("dashboard operation returned no data") + } + let json = String(cString: outPtr) + sequins_string_free(outPtr) + return json + } + + fileprivate func ffiError( + _ errorPtr: UnsafeMutablePointer?, fallback: String + ) -> SequinsError { + if let errorPtr { + let msg = String(cString: errorPtr) + sequins_string_free(errorPtr) + return SequinsError.ffiError(msg) + } + return SequinsError.ffiError(fallback) + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/Models/HistogramLine.swift b/apps/macos/SequinsData/Sources/SequinsData/Models/HistogramLine.swift index 95e737f5..283f5c24 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/Models/HistogramLine.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/Models/HistogramLine.swift @@ -131,6 +131,12 @@ public final class HistogramLine: Identifiable { /// on every render. private func recomputeMaxActiveBucket() { let sorted = snapshots.sorted { $0.timestamp < $1.timestamp } + // `1.. 0); with 0 or 1 snapshots + // there are no pairwise deltas anyway, so there's nothing to scan. + guard sorted.count > 1 else { + maxActiveBucket = 0 + return + } var maxB = 0 for i in 1.. String { } return String(format: "%g", d) } + +extension RecordBatch { + /// The semantic [`NodeTypeLabel`] for each column, derived from its Arrow field type + /// and name. Lets chart renderers choose temporal/duration/numeric axes and format + /// cells without sniffing values. Order matches `toRows()` columns. + public func columnTypeLabels() -> [NodeTypeLabel] { + schema.fields.map { nodeTypeLabel(for: $0.name, arrowType: $0.type) } + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift new file mode 100644 index 00000000..b1791480 --- /dev/null +++ b/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift @@ -0,0 +1,220 @@ +import Foundation +import SequinsFFI +@_exported import Arrow + +// MARK: - Read-only plain SQL over the normalized query path + +extension DataSource { + /// Execute a **read-only** plain SQL query (SELECT only) and stream the framed + /// result to `sink`, exactly like ``executeSeQL(_:sink:)`` but over the SQL path. + /// + /// SeQL cannot address the app-state tables (`conversations`, `messages`, + /// `dashboards`); this reads them (and any other registered DataFusion table) + /// via Flight SQL's standard plain-SQL path — in-process locally, or over the + /// wire against a Pro daemon. Results arrive as a `.table`-shaped snapshot + /// (schema → data → complete). DDL/DML are rejected server-side. + /// + /// - Parameters: + /// - sql: A SQL `SELECT` statement. + /// - sink: Receiver for schema, data batches, and completion events. + /// - Returns: A `SeQLStream` that can be cancelled. + /// - Throws: `SequinsError` if the stream handle cannot be created. + @discardableResult + public func executeSQL(_ sql: String, sink: any SeQLSink) throws -> SeQLStream { + try executeFramedSQL(sql, sink: sink, invoke: sequins_sql_query) + } + + /// Like ``executeSQL(_:sink:)`` but reads **only** the app-state tables + /// (`conversations`, `messages`, `dashboards`) via a telemetry-free context, so a + /// signal/cold-tier issue can never block or hang the read. Use this for chat + /// history and dashboard reads. + @discardableResult + public func executeAppStateSQL(_ sql: String, sink: any SeQLSink) throws -> SeQLStream { + try executeFramedSQL(sql, sink: sink, invoke: sequins_app_state_query) + } + + /// Shared framed-SQL driver: builds the callback vtable and starts the stream via + /// `invoke` (either `sequins_sql_query` or `sequins_app_state_query`). + private func executeFramedSQL( + _ sql: String, + sink: any SeQLSink, + invoke: @escaping (OpaquePointer?, UnsafePointer?, CFrameSinkVTable, UnsafeMutableRawPointer?) -> OpaquePointer? + ) throws -> SeQLStream { + let context = SeQLContext(sink: sink) + let ctxRaw = Unmanaged.passUnretained(context).toOpaque() + + var vtable = CFrameSinkVTable() + + vtable.on_schema = { + (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + guard let framePtr, let ctxPtr else { return } + let frame = framePtr.pointee + var names: [String] = [] + for i in 0...fromOpaque(ctxPtr).takeUnretainedValue() + ctx.sink?.onSchema(schema) + } + + vtable.on_data = { + (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + guard let framePtr, let ctxPtr else { return } + let frame = framePtr.pointee + let table: String? = frame.table.map { String(cString: $0) } + let batches = decodeIPC(data: frame.ipc_data, length: Int(frame.ipc_len)) + c_data_frame_free(UnsafeMutablePointer(mutating: framePtr)) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + for batch in batches { + ctx.sink?.onBatch(batch, table: table) + } + } + + vtable.on_complete = { + (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + guard let framePtr, let ctxPtr else { return } + let frame = framePtr.pointee + let stats = SeQLStats( + executionTimeUs: frame.execution_time_us, + rowsScanned: frame.rows_scanned, + bytesRead: frame.bytes_read, + rowsReturned: frame.rows_returned, + warningCount: frame.warning_count + ) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + ctx.sink?.onComplete(stats) + } + + vtable.on_warning = { + (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + guard let framePtr, let ctxPtr else { return } + let frame = framePtr.pointee + let code = UInt32(frame.code) + let message = frame.message.map { String(cString: $0) } ?? "warning" + c_warning_frame_free(UnsafeMutablePointer(mutating: framePtr)) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + ctx.sink?.onWarning(code: code, message: message) + } + + vtable.on_error = { + (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + guard let framePtr, let ctxPtr else { return } + let frame = framePtr.pointee + let code = UInt32(frame.code) + let message = frame.message.map { String(cString: $0) } ?? "query error" + c_query_error_free(UnsafeMutablePointer(mutating: framePtr)) + let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() + ctx.sink?.onError(code: code, message: message) + } + + let streamHandle = sql.withCString { sqlPtr in + invoke(rawPointer, sqlPtr, vtable, ctxRaw) + } + guard let streamHandle else { + throw SequinsError.ffiError("failed to start SQL query stream") + } + return SeQLStream(streamHandle, context: context) + } + + /// Run a read-only SQL query and collect all result rows once it completes. + /// + /// A convenience over ``executeSQL(_:sink:)`` for one-shot metadata reads (e.g. + /// listing conversations). Delivers `(columns, rows)` on the main actor. + public func fetchSQL( + _ sql: String, + completion: @escaping (Result<(columns: [String], rows: [[Any?]]), Error>) -> Void + ) { + let collector = SQLRowCollector(completion: completion) + do { + collector.stream = try executeSQL(sql, sink: collector) + } catch { + collector.startFailed(error) + } + } + + /// Like ``fetchSQL(_:completion:)`` but over the telemetry-free app-state path + /// (``executeAppStateSQL(_:sink:)``). Use for one-shot conversation/message reads + /// so they never hang on a signal/cold-tier issue. + public func fetchAppStateSQL( + _ sql: String, + completion: @escaping (Result<(columns: [String], rows: [[Any?]]), Error>) -> Void + ) { + let collector = SQLRowCollector(completion: completion) + do { + collector.stream = try executeAppStateSQL(sql, sink: collector) + } catch { + collector.startFailed(error) + } + } +} + +/// One-shot SQL result collector: accumulates rows across batches and reports them +/// (with the schema's column names) on completion or error. +/// +/// The stream's ``SeQLContext`` holds its sink **weakly** (to avoid leaking streaming +/// sinks the caller already owns). A one-shot collector, though, is created as a local +/// with no other owner, so it would be deallocated the instant the `fetch…` call +/// returns — before the async query delivers any frames, leaving the callbacks to +/// no-op against a nil sink and the completion to never fire. So it retains **itself** +/// for the query's lifetime (`selfRetain`), releasing exactly once in ``finish(_:)``. +final class SQLRowCollector: SeQLSink { + private let completion: (Result<(columns: [String], rows: [[Any?]]), Error>) -> Void + private var columns: [String] = [] + private var rows: [[Any?]] = [] + private var finished = false + var stream: SeQLStream? + /// Strong self-reference keeping the collector alive across the async query. + private var selfRetain: SQLRowCollector? + + init(completion: @escaping (Result<(columns: [String], rows: [[Any?]]), Error>) -> Void) { + self.completion = completion + self.selfRetain = self + } + + /// Report a failure to even start the stream (no frames will arrive). + func startFailed(_ error: Error) { + finish(.failure(error)) + } + + func onSchema(_ schema: SeQLSchema) { + columns = schema.columnNames + } + + func onBatch(_ batch: RecordBatch, table: String?) { + // Only the primary result table (auxiliary tables are unused for SQL reads). + guard table == nil else { return } + rows.append(contentsOf: batch.toRows()) + } + + func onComplete(_ stats: SeQLStats) { + finish(.success((columns, rows))) + } + + func onWarning(code: UInt32, message: String) {} + + func onError(code: UInt32, message: String) { + finish(.failure(SequinsError.ffiError(message))) + } + + private func finish(_ result: Result<(columns: [String], rows: [[Any?]]), Error>) { + guard !finished else { return } + finished = true + let cb = completion + DispatchQueue.main.async { + cb(result) + // Release the retained stream after delivery. + } + stream = nil + // Drop the self-reference last, so `self` stays alive until delivery is queued. + selfRetain = nil + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift b/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift index cf830ba1..e57b25f7 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift @@ -72,3 +72,97 @@ extension TimeRange { .absolute(start: Date(timeIntervalSince1970: 0), end: Date()) } } + +// MARK: - SeQL time-scope rewriting + +extension TimeRange { + /// SeQL scan-position signal keywords (the mandatory leading token of a query). + private static let signalKeywords: Set = [ + "spans", "span_links", "logs", "datapoints", "histograms", "metrics", + "samples", "traces", "profiles", "stacks", "frames", "mappings", + "resources", "scopes", + ] + + /// The SeQL scan-level time-scope clause for this range: + /// `last ` for relative, `between(, )` for absolute. + public var seqlTimeScope: String { + switch self { + case .relative(let duration): + return "last \(TimeRange.durationClause(duration))" + case .absolute(let start, let end): + let startNs = Int64(start.timeIntervalSince1970 * 1_000_000_000) + let endNs = Int64(end.timeIntervalSince1970 * 1_000_000_000) + return "between(\(startNs), \(endNs))" + } + } + + /// Format a duration as a single SeQL duration literal (``), picking the + /// largest exact unit. SeQL has no compound durations, so a non-exact duration + /// falls back to whole seconds. + private static func durationClause(_ seconds: TimeInterval) -> String { + let total = max(1, Int(seconds.rounded())) + if total % 86_400 == 0 { return "\(total / 86_400)d" } + if total % 3_600 == 0 { return "\(total / 3_600)h" } + if total % 60 == 0 { return "\(total / 60)m" } + return "\(total)s" + } + + /// Rewrite `seql` so its leading ` ` uses this range. + /// + /// SeQL requires a time-scope immediately after the signal keyword, so we replace + /// that token. Returns the query unchanged when it doesn't begin with a recognized + /// ` ` (e.g. the `signal(id)` shorthand), so a query we can't + /// safely rewrite is never corrupted. + public func applied(to seql: String) -> String { + let full = Substring(seql) + let leadingWS = full.prefix { $0.isWhitespace } + var rest = full.dropFirst(leadingWS.count) + + let signal = rest.prefix { $0.isLetter || $0 == "_" } + guard !signal.isEmpty, TimeRange.signalKeywords.contains(String(signal)) else { + return seql + } + rest = rest.dropFirst(signal.count) + + // `signal(id)` shorthand carries no time-scope — leave untouched. + if rest.first == "(" { return seql } + + let midWS = rest.prefix { $0.isWhitespace } + guard !midWS.isEmpty else { return seql } + rest = rest.dropFirst(midWS.count) + + guard let tail = TimeRange.dropTimeScope(rest) else { return seql } + return "\(leadingWS)\(signal)\(midWS)\(seqlTimeScope)\(tail)" + } + + /// If `s` begins with a SeQL time-scope token, return the remainder after it; + /// otherwise `nil`. + private static func dropTimeScope(_ s: Substring) -> Substring? { + for keyword in ["today", "yesterday"] where s.hasPrefix(keyword) { + let tail = s.dropFirst(keyword.count) + if tail.isEmpty || tail.first!.isWhitespace || tail.first! == "|" { + return tail + } + } + + if s.hasPrefix("between") { + let t = s.dropFirst("between".count).drop { $0.isWhitespace } + guard t.first == "(", let close = t.firstIndex(of: ")") else { return nil } + return t[t.index(after: close)...] + } + + if s.hasPrefix("last") { + var t = s.dropFirst("last".count) + guard let boundary = t.first, boundary.isWhitespace else { return nil } + t = t.drop { $0.isWhitespace } + let digits = t.prefix { $0.isNumber } + guard !digits.isEmpty else { return nil } + t = t.dropFirst(digits.count) + if t.hasPrefix("ms") { return t.dropFirst(2) } + guard let unit = t.first, "smhd".contains(unit) else { return nil } + return t.dropFirst(1) + } + + return nil + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift b/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift new file mode 100644 index 00000000..94e0ead8 --- /dev/null +++ b/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift @@ -0,0 +1,184 @@ +import Foundation + +/// One home for value/label formatting across every chart and table renderer: +/// grouped/compact numbers, bytes, percents, durations (ns→µs/ms/s), timestamps, and a +/// type-aware cell formatter. Consolidates logic previously duplicated in the Metrics +/// charts, `RecordBatchTree`, and `ExploreTableView`. +public enum VizFormat { + + // MARK: - Numbers + + private static let grouped: NumberFormatter = { + let f = NumberFormatter() + f.numberStyle = .decimal + f.maximumFractionDigits = 0 + return f + }() + + /// Full-precision number for stats/tables/tooltips: whole numbers get thousands + /// separators ("6,784"), fractions get two decimals. + public static func number(_ value: Double) -> String { + if value.rounded() == value, abs(value) < 1e15 { + return grouped.string(from: NSNumber(value: Int64(value))) ?? "\(Int64(value))" + } + return String(format: "%.2f", value) + } + + /// Compact number for dense axis ticks: k / M / B. + public static func compact(_ value: Double) -> String { + let a = abs(value) + if a >= 1_000_000_000 { return String(format: "%.1fB", value / 1_000_000_000) } + if a >= 1_000_000 { return String(format: "%.1fM", value / 1_000_000) } + if a >= 1_000 { return String(format: "%.1fk", value / 1_000) } + if a >= 1 || a == 0 { return String(format: "%.0f", value) } + return String(format: "%.2f", value) + } + + /// Bytes (base 1024) → B/KB/MB/GB/TB. + public static func bytes(_ value: Double) -> String { + let a = abs(value) + if a >= 1_099_511_627_776 { return String(format: "%.1f TB", value / 1_099_511_627_776) } + if a >= 1_073_741_824 { return String(format: "%.1f GB", value / 1_073_741_824) } + if a >= 1_048_576 { return String(format: "%.1f MB", value / 1_048_576) } + if a >= 1_024 { return String(format: "%.0f KB", value / 1_024) } + return String(format: "%.0f B", value) + } + + public static func percent(_ value: Double) -> String { + String(format: "%.1f%%", value) + } + + /// Duration given in nanoseconds → ns/µs/ms/s (reuses `NanoDuration.formatted`). + public static func durationNs(_ ns: Double) -> String { + NanoDuration(nanoseconds: Int64(ns.rounded())).formatted + } + + // MARK: - Time + + private static let timestampFormatter: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + return f + }() + + private static let clockFormatter: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm:ss" + return f + }() + + private static let clockShortFormatter: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm" + return f + }() + + public static func timestamp(_ date: Date) -> String { + timestampFormatter.string(from: date) + } + + /// Axis/tick time label. `includeSeconds` for windows under a few minutes. + public static func axisTime(_ date: Date, includeSeconds: Bool = false) -> String { + (includeSeconds ? clockFormatter : clockShortFormatter).string(from: date) + } + + // MARK: - Coercion + + /// Best-effort numeric value of a cell (does not preserve timestamp identity — use + /// `date(_:column:)` for the time axis). + public static func numeric(_ value: Any?) -> Double? { + switch value { + case let n as NSNumber: return n.doubleValue + case let d as Double: return d + case let f as Float: return Double(f) + case let i as Int: return Double(i) + case let i as Int64: return Double(i) + case let u as UInt64: return Double(u) + case let i as Int32: return Double(i) + case let u as UInt32: return Double(u) + case let date as Date: return date.timeIntervalSince1970 + case let s as String: return Double(s) + default: return nil + } + } + + /// A `Date` for a cell that represents a time — either an Arrow `Date`, or an + /// integer that looks like epoch nanoseconds (>~1e15) when the column name is timey. + public static func date(_ value: Any?, column: String) -> Date? { + if let date = value as? Date { return date } + guard isTimeColumn(column), let n = numeric(value) else { return nil } + // Heuristic: epoch nanoseconds are ~1.7e18 today; treat large integers as ns. + if n > 1_000_000_000_000_000 { + return Date(timeIntervalSince1970: n / 1_000_000_000) + } + return nil + } + + public static func string(_ value: Any?) -> String { + switch value { + case .none: return "" + case let s as String: return s + case let d as Date: return timestamp(d) + case let b as Bool: return b ? "true" : "false" + case let n as NSNumber: return number(n.doubleValue) + default: return String(describing: value ?? "") + } + } + + // MARK: - Type-aware cell + + /// Format a cell for display given its semantic type + column name. + public static func cell(_ value: Any?, type: NodeTypeLabel, column: String) -> String { + if value == nil { return "—" } + switch type { + case .id, .string, .binary: + return string(value) + case .boolean: + if let b = value as? Bool { return b ? "true" : "false" } + return string(value) + case .timestamp: + if let d = date(value, column: column) ?? value as? Date { return timestamp(d) } + return string(value) + case .duration: + if let n = numeric(value) { return durationNs(n) } + return string(value) + case .number: + if let n = numeric(value) { return number(n) } + return string(value) + case .null: + return "—" + default: + return string(value) + } + } + + // MARK: - Column-name heuristics (unified) + + public static func isIdColumn(_ name: String) -> Bool { + let n = name.lowercased() + return n == "id" || n.hasSuffix("_id") || n == "trace_id" || n == "span_id" + } + + public static func isDurationColumn(_ name: String) -> Bool { + let n = name.lowercased() + return n.contains("duration") || n.hasSuffix("_ns") || n == "elapsed_ns" || n == "latency" + } + + public static func isTimeColumn(_ name: String) -> Bool { + let n = name.lowercased() + return n == "bucket" || n == "time" || n == "timestamp" || n == "ts" + || n.hasSuffix("_time") || n.hasSuffix("_unix_nano") || n.contains("time_") + } + + /// A human-readable label for a raw column name (snake/camel → Title Case). + public static func label(_ raw: String) -> String { + let spaced = raw + .replacingOccurrences(of: "_", with: " ") + .replacingOccurrences(of: "-", with: " ") + let words = spaced.split(separator: " ").map { word -> String in + let w = String(word) + return w.prefix(1).uppercased() + w.dropFirst() + } + return words.joined(separator: " ") + } +} diff --git a/apps/macos/SequinsData/Sources/SequinsData/VizType.swift b/apps/macos/SequinsData/Sources/SequinsData/VizType.swift new file mode 100644 index 00000000..00deb3bb --- /dev/null +++ b/apps/macos/SequinsData/Sources/SequinsData/VizType.swift @@ -0,0 +1,107 @@ +import Foundation + +/// App-side visualization type — a superset of the Rust-inferred ``ResponseShape``. +/// +/// A visualization descriptor may pin a `VizType` (via a model hint or the user's +/// choice); when unset, ``autoSelect(shape:columns:rows:)`` derives a sensible default +/// from the query's `ResponseShape` and result columns. Rows are mapped to the chosen +/// chart regardless of the Rust shape, so the same result can be shown several ways. +/// +/// The raw value is what persists in `SavedVisualization.shape`. +public enum VizType: String, CaseIterable, Codable, Sendable { + case line + case area + case bar + case stackedBar + case pie + case gauge + case stat + case table + case heatmap + case trace + + /// Human-readable label for pickers. + public var displayName: String { + switch self { + case .line: return "Line" + case .area: return "Area" + case .bar: return "Bar" + case .stackedBar: return "Stacked Bar" + case .pie: return "Pie" + case .gauge: return "Gauge" + case .stat: return "Stat" + case .table: return "Table" + case .heatmap: return "Heatmap" + case .trace: return "Trace" + } + } + + /// SF Symbol name for pickers/menus. + public var systemImage: String { + switch self { + case .line: return "chart.xyaxis.line" + case .area: return "chart.line.uptrend.xyaxis" + case .bar: return "chart.bar" + case .stackedBar: return "chart.bar.doc.horizontal" + case .pie: return "chart.pie" + case .gauge: return "gauge.medium" + case .stat: return "number" + case .table: return "tablecells" + case .heatmap: return "square.grid.3x3.fill" + case .trace: return "arrow.triangle.branch" + } + } + + /// Whether this type is a good fit for the given result (used to gray out + /// obviously-wrong choices in the picker). Permissive by default. + public func isSuitable(columnCount: Int, rowCount: Int) -> Bool { + switch self { + case .stat, .gauge: return columnCount >= 1 + case .pie: return columnCount >= 2 + case .line, .area, .bar, .stackedBar: return columnCount >= 2 + case .heatmap: return columnCount >= 3 + case .table, .trace: return true + } + } + + /// Parse a stored `shape` string into a `VizType`, accepting both `VizType` raw + /// values and legacy `ResponseShape` strings (e.g. "timeseries", "trace_tree"). + public static func from(shapeString: String?) -> VizType? { + guard let raw = shapeString, !raw.isEmpty else { return nil } + // Exact raw value (preserves camelCase like "stackedBar")… + if let direct = VizType(rawValue: raw) { return direct } + let lower = raw.lowercased() + // …then a case-insensitive match against the raw values… + if let ci = VizType.allCases.first(where: { $0.rawValue.lowercased() == lower }) { + return ci + } + // …then legacy `ResponseShape` string aliases. + switch lower { + case "timeseries", "time_series": return .line + case "scalar": return .stat + case "trace_tree", "trace_timeline", "tracetimeline", "tracetree": return .trace + case "pattern_groups", "patterngroups": return .table + default: return nil + } + } + + /// Choose a default `VizType` from the Rust-inferred shape and the result columns. + public static func autoSelect( + shape: ResponseShape, columns: [String], rows: [[Any?]] + ) -> VizType { + switch shape { + case .timeSeries: return .line + case .scalar: return .stat + case .traceTimeline, .traceTree: return .trace + case .heatmap: return .heatmap + case .patternGroups: return .table + case .table: + // A compact two-column (category + one value) result reads well as a bar + // chart; anything wider or larger stays a table. + if columns.count == 2, rows.count <= 24, rows.count > 1 { + return .bar + } + return .table + } + } +} diff --git a/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift b/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift new file mode 100644 index 00000000..1c55fdf3 --- /dev/null +++ b/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift @@ -0,0 +1,82 @@ +import XCTest +@testable import SequinsData + +final class DashboardVizTests: XCTestCase { + + func testDashboardJSONRoundTrip() throws { + let dashboard = Dashboard( + id: "d1", + title: "Errors", + createdAtNs: 1, + updatedAtNs: 2, + rows: [ + DashboardRow(height: 300, panels: [ + RowPanel(visualization: SavedVisualization(seql: "logs last 1h", title: "Logs", shape: "bar"), weight: 2), + RowPanel(visualization: SavedVisualization(seql: "spans last 1h", title: "Spans"), weight: 1), + ]) + ] + ) + + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + + let data = try encoder.encode(dashboard) + let json = String(decoding: data, as: UTF8.self) + XCTAssertTrue(json.contains("created_at_ns")) + XCTAssertTrue(json.contains("\"rows\"")) + XCTAssertFalse(json.contains("\"x\""), "no legacy grid coordinates") + + let back = try decoder.decode(Dashboard.self, from: data) + XCTAssertEqual(back.id, "d1") + XCTAssertEqual(back.rows.count, 1) + XCTAssertEqual(back.rows.first?.height, 300) + XCTAssertEqual(back.rows.first?.panels.count, 2) + XCTAssertEqual(back.rows.first?.panels.first?.weight, 2) + XCTAssertEqual(back.rows.first?.panels.first?.visualization.vizType, .bar) + XCTAssertEqual(back.panelCount, 2) + } + + func testDecodesLegacyRowsAbsentDefaultsToEmpty() throws { + // A dashboard JSON without `rows` (e.g. a freshly created empty dashboard) decodes. + let json = #"{"id":"d2","title":"Empty","created_at_ns":0,"updated_at_ns":0}"# + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + let back = try decoder.decode(Dashboard.self, from: Data(json.utf8)) + XCTAssertEqual(back.rows.count, 0) + XCTAssertEqual(back.panelCount, 0) + } + + func testSavedVisualizationVizTypeMapping() { + var v = SavedVisualization(seql: "x", title: "t", shape: nil) + XCTAssertNil(v.vizType) + + v.vizType = .stackedBar + XCTAssertEqual(v.shape, "stackedBar") + XCTAssertEqual(v.vizType, .stackedBar) + + // Legacy ResponseShape strings map onto the VizType superset. + XCTAssertEqual(SavedVisualization(seql: "x", title: "t", shape: "timeseries").vizType, .line) + XCTAssertEqual(SavedVisualization(seql: "x", title: "t", shape: "scalar").vizType, .stat) + XCTAssertEqual(SavedVisualization(seql: "x", title: "t", shape: "trace_tree").vizType, .trace) + } + + func testVizTypeAutoSelect() { + XCTAssertEqual(VizType.autoSelect(shape: .timeSeries, columns: ["t", "v"], rows: []), .line) + XCTAssertEqual(VizType.autoSelect(shape: .scalar, columns: ["c"], rows: [[1]]), .stat) + XCTAssertEqual(VizType.autoSelect(shape: .heatmap, columns: ["x", "y", "v"], rows: []), .heatmap) + XCTAssertEqual(VizType.autoSelect(shape: .traceTimeline, columns: [], rows: []), .trace) + + // A compact two-column category+value table auto-selects a bar chart… + XCTAssertEqual( + VizType.autoSelect(shape: .table, columns: ["svc", "count"], rows: [["a", 1], ["b", 2]]), + .bar + ) + // …but a wider table stays a table. + XCTAssertEqual( + VizType.autoSelect(shape: .table, columns: ["a", "b", "c", "d"], rows: [[1, 2, 3, 4]]), + .table + ) + } +} diff --git a/apps/macos/SequinsData/Tests/SequinsDataTests/HistogramLineTests.swift b/apps/macos/SequinsData/Tests/SequinsDataTests/HistogramLineTests.swift new file mode 100644 index 00000000..ff038d69 --- /dev/null +++ b/apps/macos/SequinsData/Tests/SequinsDataTests/HistogramLineTests.swift @@ -0,0 +1,77 @@ +// +// HistogramLineTests.swift +// SequinsDataTests +// +// Regression coverage for HistogramLine.maxActiveBucket recomputation, whose +// `1.. 0). +// + +import XCTest +@testable import SequinsData + +final class HistogramLineTests: XCTestCase { + private func makeLine() -> HistogramLine { + HistogramLine( + id: "abc", + rowId: 0, + name: "latency", + description: "", + unit: "ms", + serviceName: "svc" + ) + } + + private func snap(_ ts: Double, _ buckets: [UInt64]) -> HistogramSnapshot { + HistogramSnapshot( + timestamp: Date(timeIntervalSince1970: ts), + count: buckets.reduce(0, +), + sum: 0, + bucketCounts: buckets, + explicitBounds: [1, 2, 3] + ) + } + + /// The crash: a live stream delivering an empty histogram set drove + /// `replaceWithCumulatives([])` → `recomputeMaxActiveBucket()` → `1..<0` trap. + func testReplaceWithEmptyDoesNotCrash() { + let line = makeLine() + line.replaceWithCumulatives([]) + XCTAssertEqual(line.maxActiveBucket, 0) + XCTAssertTrue(line.snapshots.isEmpty) + } + + /// A single snapshot has no pairwise delta — must not trap and leaves max at 0. + func testReplaceWithSingleSnapshotDoesNotCrash() { + let line = makeLine() + line.replaceWithCumulatives([snap(1, [0, 0, 5, 0])]) + XCTAssertEqual(line.maxActiveBucket, 0) + } + + /// Two cumulative snapshots: the delta's highest non-zero bucket is index 2. + func testReplaceWithCumulativesComputesMaxActiveBucket() { + let line = makeLine() + line.replaceWithCumulatives([ + snap(1, [1, 0, 0, 0]), + snap(2, [1, 0, 3, 0]), + ]) + XCTAssertEqual(line.maxActiveBucket, 2) + } + + /// Pruning that drops the snapshot count triggers `recomputeMaxActiveBucket()` + /// (the actual crash site). Starting from two snapshots and pruning down to one + /// must recompute over a single-element array without trapping, yielding 0. + func testPruneTriggersRecomputeToOneDoesNotCrash() { + let line = makeLine() + line.replaceWithCumulatives([snap(1, [1, 0, 0, 0]), snap(2, [1, 0, 5, 0])]) + XCTAssertEqual(line.maxActiveBucket, 2) + + // Append snap3 and prune everything older than ts=3 → only snap3 remains. + // count (1) < countBefore (2) → recompute runs on a single snapshot. + line.appendCumulativeAndPrune( + [snap(3, [1, 0, 0, 0])], + olderThan: Date(timeIntervalSince1970: 3) + ) + XCTAssertEqual(line.snapshots.count, 1) + XCTAssertEqual(line.maxActiveBucket, 0) + } +} diff --git a/apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift b/apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift new file mode 100644 index 00000000..8c1b9b93 --- /dev/null +++ b/apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift @@ -0,0 +1,57 @@ +import XCTest +@testable import SequinsData + +final class TimeRangeSeQLTests: XCTestCase { + + func testRelativeReplacesLastClause() { + let range = TimeRange.relative(duration: 1800) // 30 minutes + XCTAssertEqual( + range.applied(to: "logs last 1h | where severity_number >= 9 | take 500"), + "logs last 30m | where severity_number >= 9 | take 500" + ) + } + + func testRelativeUnitSelection() { + XCTAssertEqual(TimeRange.relative(duration: 3600).seqlTimeScope, "last 1h") + XCTAssertEqual(TimeRange.relative(duration: 86_400).seqlTimeScope, "last 1d") + XCTAssertEqual(TimeRange.relative(duration: 300).seqlTimeScope, "last 5m") + XCTAssertEqual(TimeRange.relative(duration: 45).seqlTimeScope, "last 45s") + // 90 minutes is not a whole number of hours → minutes. + XCTAssertEqual(TimeRange.relative(duration: 5400).seqlTimeScope, "last 90m") + } + + func testAbsoluteBecomesBetween() { + let start = Date(timeIntervalSince1970: 1) // 1e9 ns + let end = Date(timeIntervalSince1970: 2) // 2e9 ns + let range = TimeRange.absolute(start: start, end: end) + XCTAssertEqual( + range.applied(to: "spans last 1h | take 5"), + "spans between(1000000000, 2000000000) | take 5" + ) + } + + func testReplacesTodayAndBetween() { + let range = TimeRange.relative(duration: 3600) + XCTAssertEqual(range.applied(to: "logs today | where x == 1"), "logs last 1h | where x == 1") + XCTAssertEqual( + range.applied(to: "spans between(1000, 2000) | take 5"), + "spans last 1h | take 5" + ) + XCTAssertEqual(range.applied(to: "logs yesterday"), "logs last 1h") + } + + func testLeavesUnrewritableQueriesUntouched() { + let range = TimeRange.relative(duration: 3600) + // Not a signal keyword. + XCTAssertEqual(range.applied(to: "foobar last 1h"), "foobar last 1h") + // `signal(id)` shorthand has no time-scope. + XCTAssertEqual(range.applied(to: "span(abc123)"), "span(abc123)") + // Signal with no time-scope (malformed) — left as-is rather than corrupted. + XCTAssertEqual(range.applied(to: "resources"), "resources") + } + + func testPreservesLeadingWhitespace() { + let range = TimeRange.relative(duration: 3600) + XCTAssertEqual(range.applied(to: " spans last 30m"), " spans last 1h") + } +} diff --git a/apps/macos/SequinsData/Tests/SequinsDataTests/VizFormatTests.swift b/apps/macos/SequinsData/Tests/SequinsDataTests/VizFormatTests.swift new file mode 100644 index 00000000..31338055 --- /dev/null +++ b/apps/macos/SequinsData/Tests/SequinsDataTests/VizFormatTests.swift @@ -0,0 +1,66 @@ +import XCTest +@testable import SequinsData + +final class VizFormatTests: XCTestCase { + + func testNumberGroupsThousands() { + XCTAssertEqual(VizFormat.number(6784), "6,784") + XCTAssertEqual(VizFormat.number(1_234_567), "1,234,567") + XCTAssertEqual(VizFormat.number(42), "42") + XCTAssertEqual(VizFormat.number(3.14159), "3.14") + } + + func testCompact() { + XCTAssertEqual(VizFormat.compact(1_500), "1.5k") + XCTAssertEqual(VizFormat.compact(2_000_000), "2.0M") + XCTAssertEqual(VizFormat.compact(3_000_000_000), "3.0B") + XCTAssertEqual(VizFormat.compact(42), "42") + } + + func testBytes() { + XCTAssertEqual(VizFormat.bytes(1_048_576), "1.0 MB") + XCTAssertEqual(VizFormat.bytes(1_073_741_824), "1.0 GB") + XCTAssertEqual(VizFormat.bytes(512), "512 B") + } + + func testDurationNs() { + XCTAssertEqual(VizFormat.durationNs(500), "500 ns") + XCTAssertEqual(VizFormat.durationNs(1_500_000), "1.50 ms") + XCTAssertEqual(VizFormat.durationNs(2_500_000_000), "2.50 s") + } + + func testPercent() { + XCTAssertEqual(VizFormat.percent(12.5), "12.5%") + } + + func testColumnHeuristics() { + XCTAssertTrue(VizFormat.isTimeColumn("bucket")) + XCTAssertTrue(VizFormat.isTimeColumn("start_time_unix_nano")) + XCTAssertTrue(VizFormat.isDurationColumn("duration_ns")) + XCTAssertTrue(VizFormat.isIdColumn("trace_id")) + XCTAssertFalse(VizFormat.isIdColumn("count")) + } + + func testLabelTitleCases() { + XCTAssertEqual(VizFormat.label("total_spans"), "Total Spans") + XCTAssertEqual(VizFormat.label("n"), "N") + XCTAssertEqual(VizFormat.label("error_rate"), "Error Rate") + } + + func testCellDispatch() { + XCTAssertEqual(VizFormat.cell(6784 as Int64, type: .number, column: "total"), "6,784") + XCTAssertEqual(VizFormat.cell(1_500_000 as Int64, type: .duration, column: "duration_ns"), "1.50 ms") + XCTAssertEqual(VizFormat.cell(nil, type: .number, column: "x"), "—") + XCTAssertEqual(VizFormat.cell(true, type: .boolean, column: "ok"), "true") + } + + func testDateFromNanos() { + // A large integer in a time column is treated as epoch nanoseconds. + let nanos = 1_700_000_000_000_000_000 as Int64 + let date = VizFormat.date(nanos, column: "bucket") + XCTAssertNotNil(date) + XCTAssertEqual(date!.timeIntervalSince1970, 1_700_000_000, accuracy: 1) + // A plain number in a non-time column is not a date. + XCTAssertNil(VizFormat.date(42 as Int64, column: "count")) + } +} diff --git a/apps/macos/build-ffi.sh b/apps/macos/build-ffi.sh new file mode 100755 index 00000000..2691297c --- /dev/null +++ b/apps/macos/build-ffi.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# +# Rebuild the SequinsFFI.xcframework consumed by the SequinsData SPM package. +# +# Builds the `sequins-ffi` staticlib for both macOS architectures, lipos them +# into a universal `libsequins_ffi.a`, and refreshes the xcframework slice's +# library + headers (the cbindgen build script regenerates `sequins.h` on build). +# +# Run from anywhere; paths are resolved relative to the repo. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +XCFRAMEWORK="$SCRIPT_DIR/SequinsData/SequinsFFI.xcframework" +SLICE="$XCFRAMEWORK/macos-arm64_x86_64" +PROFILE="${1:-release}" + +if [[ "$PROFILE" == "release" ]]; then + CARGO_PROFILE_FLAG="--release" + TARGET_SUBDIR="release" +else + CARGO_PROFILE_FLAG="" + TARGET_SUBDIR="debug" +fi + +echo "==> Building sequins-ffi ($PROFILE) for aarch64 + x86_64…" +cd "$REPO_ROOT" +cargo build -p sequins-ffi $CARGO_PROFILE_FLAG --target aarch64-apple-darwin +cargo build -p sequins-ffi $CARGO_PROFILE_FLAG --target x86_64-apple-darwin + +ARM64_LIB="$REPO_ROOT/target/aarch64-apple-darwin/$TARGET_SUBDIR/libsequins_ffi.a" +X86_64_LIB="$REPO_ROOT/target/x86_64-apple-darwin/$TARGET_SUBDIR/libsequins_ffi.a" + +echo "==> Creating universal static library…" +mkdir -p "$SLICE/Headers" +lipo -create "$ARM64_LIB" "$X86_64_LIB" -output "$SLICE/libsequins_ffi.a" + +echo "==> Refreshing headers…" +cp "$REPO_ROOT/crates/sequins-ffi/include/sequins.h" "$SLICE/Headers/sequins.h" +cp "$REPO_ROOT/crates/sequins-ffi/include/module.modulemap" "$SLICE/Headers/module.modulemap" + +echo "==> Done. xcframework refreshed at:" +echo " $XCFRAMEWORK" +lipo -info "$SLICE/libsequins_ffi.a" From e02d3c6215a820f96f1c060d7dc13fd5ebffaabc Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 16 Jul 2026 22:08:26 +0800 Subject: [PATCH 03/10] chore(tooling): env-configurable OTLP endpoints, scripts, docs - example/test-app: honor OTEL_EXPORTER_OTLP_ENDPOINT and a profiles endpoint override so the sample app can target a containerized daemon. - Add scripts/ and docs/. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs/architecture/api-surface-audit.md | 369 ++++++++++++++++++ docs/architecture/code-quality-roadmap.md | 206 ++++++++++ .../subsystems/contracts-and-schemas.md | 250 ++++++++++++ docs/architecture/subsystems/indexing.md | 193 +++++++++ .../subsystems/ingest-and-storage.md | 294 ++++++++++++++ .../subsystems/query-view-and-runtime.md | 299 ++++++++++++++ docs/architecture/subsystems/seql.md | 207 ++++++++++ example/src/profiler.rs | 18 +- example/src/telemetry.rs | 13 +- scripts/codex-assistant.sh | 94 +++++ scripts/opencode-assistant.sh | 108 +++++ 11 files changed, 2047 insertions(+), 4 deletions(-) create mode 100644 docs/architecture/api-surface-audit.md create mode 100644 docs/architecture/code-quality-roadmap.md create mode 100644 docs/architecture/subsystems/contracts-and-schemas.md create mode 100644 docs/architecture/subsystems/indexing.md create mode 100644 docs/architecture/subsystems/ingest-and-storage.md create mode 100644 docs/architecture/subsystems/query-view-and-runtime.md create mode 100644 docs/architecture/subsystems/seql.md create mode 100755 scripts/codex-assistant.sh create mode 100755 scripts/opencode-assistant.sh diff --git a/docs/architecture/api-surface-audit.md b/docs/architecture/api-surface-audit.md new file mode 100644 index 00000000..16471bf4 --- /dev/null +++ b/docs/architecture/api-surface-audit.md @@ -0,0 +1,369 @@ +# Workspace API Surface Audit + +This document summarizes a read-only review of the public API surface of each +workspace crate and the downstream users inside this workspace. It is intended +to guide API narrowing work, not to preserve the current shape. + +The core architectural goal is to make each component replaceable behind a +small contract. Public exports should describe what a crate promises, not the +current internal module layout. + +OpenTelemetry is Sequins' ingest/domain model. This audit treats OTLP ingest, +OTLP-aligned WAL behavior, and OTEL-shaped Arrow schemas as intentional product +architecture. The API issue is when generated protobuf plumbing, broad facade +exports, or protocol-specific helper modules leak through crates that claim a +smaller contract. + +## Audit Method + +The review used `cargo metadata`, crate root exports, public item searches, and +workspace call-site searches. Findings were grouped by subsystem and checked +against downstream Rust, Swift/FFI, CLI, and app usage where visible. + +This audit is scoped to in-workspace usage. These crates are treated as internal +workspace components, so cleanup work may migrate downstream workspace users and +remove old crate surfaces in the same change set. + +## Summary Findings + +The largest API-contract problems are umbrella facades and implementation module +leaks: + +- `sequins-query` is a broad facade over `seql-*`, `sequins-flight`, and + `sequins-traits`, while stale duplicate source files remain in the crate. +- `sequins-types` re-exports schema and trait crates, making domain models a + dependency hub. +- `sequins-storage` re-exports hot tier, cold tier, WAL, and live-query crates, + allowing downstream code to bypass storage boundaries. +- `sequins-cold-tier`, `sequins-hot-tier`, `sequins-companion-index`, and + `sequins-vortex-indexed-layout` expose implementation modules as public API. +- `sequins-traits` claims to be light but exposes Flight retrieval and generated + OTLP protobuf types through a protocol-neutral-looking facade. +- `sequins-ffi` exports typed query stubs and model surfaces that appear to + exist primarily for header generation. + +## Query and Language Crates + +Crates covered: `seql-ast`, `seql-parser`, `seql-substrait`, +`sequins-query`, `sequins-flight`, and `sequins-traits`. + +### Intended Contracts + +- `seql-ast`: syntax tree, query modes, signal names, and AST value types. +- `seql-parser`: `parse(&str) -> QueryAst` plus parse error metadata. +- `seql-substrait`: SeQL AST/text to Substrait plan compilation entrypoints. +- `sequins-flight`: query stream wire metadata, FlightData builders, and IPC + frame encoding/decoding. +- `sequins-traits`: protocol-neutral contracts only. +- `sequins-query`: eliminate as a broad umbrella, or reduce to a deliberately + narrow query contract crate with no re-exported lower-level implementation + surfaces. + +### Current Surface Issues + +- `seql-ast/src/lib.rs` wildcard-exports `ast`, `correlation`, and `schema`. + Correlation helpers are only needed by compiler planning. Result schema types + such as `ResponseShape`, `ColumnDef`, `ColumnRole`, and `DataType` are used by + clients, but they are not pure AST syntax. +- `seql-parser` has a clean external surface, but its manifest declares + `sequins-types` even though current parser sources do not use it. +- `seql-substrait` publicly exports stage-level compiler internals such as + `apply_filter`, `apply_project`, `apply_compute`, `apply_aggregate`, + `apply_sort`, `apply_limit`, `apply_unique`, `ast_expr_to_df_expr`, and + `ast_to_logical_plan`. Production callers mainly need `compile`, + `compile_ast`, `schema_context`, and possibly `time_column_for_signal`. +- `seql-substrait` exposes the stream reducer even though reducer behavior is + Flight/client-side stream handling, not Substrait compilation. This is also + why the compiler crate depends on `sequins-flight`. +- `sequins-query` is mostly an umbrella facade. Downstream users currently + import `sequins_query::parser`, `sequins_query::ast`, `sequins_query::schema`, + `sequins_query::flight`, `sequins_query::frame`, query errors, query traits, + and compiler entrypoints. +- `sequins-query` still contains stale duplicate parser, schema, correlation, + and generated proto files that are not the active exports. +- `sequins-flight` wildcard-exports all frame and Flight helpers. It also mixes + canonical wire metadata with callback/data-frame DTOs. +- `sequins-flight::batch_to_ipc` can hide Arrow IPC failures by returning empty + bytes instead of a result. +- `sequins-traits::SeqlStream` is `FlightData`, binding generic query traits to + Arrow Flight. `OtlpIngest` is bound to generated OTLP protobuf + request/response types even though OTLP ingest should be an explicit OTEL + contract. + +### Narrowing Actions + +1. Keep `seql-parser` as the model parser contract and remove its unused + `sequins-types` dependency. +2. Decide whether `sequins-query` owns a narrow query contract at all. If not, + migrate all downstream workspace users to `seql-parser`, `seql-ast`, + `seql-substrait`, `sequins-flight`, and the real trait crate directly, then + remove the umbrella exports and stale duplicate modules. +3. Narrow `seql-substrait` exports to compiler entrypoints and move reducer code + to `sequins-flight`, `sequins-view`, or a dedicated query-client crate. +4. Replace wildcard exports in `seql-ast` and `sequins-flight` with explicit + root exports. +5. Move Flight-coupled query traits out of `sequins-traits`; move OTLP ingest + traits behind an explicit OTEL ingest contract or feature. +6. Make IPC encoding helpers return `Result` and propagate encoding errors + through query execution. + +## Contracts, Schemas, and Ingest + +Crates covered: `sequins-types`, `sequins-arrow-schema`, +`sequins-attribute-codec`, `sequins-otlp`, and `sequins-pprof`. + +### Intended Contracts + +- `sequins-types`: passive domain models, IDs, time values, health config, and + model serialization. +- `sequins-arrow-schema`: canonical table schemas, `SchemaCatalog`, + `PromotedAttribute`, and logical `SignalType`. +- `sequins-attribute-codec`: overflow attribute map construction and optional + DataFusion UDF registration. +- `sequins-otlp`: OTLP protobuf to Arrow `RecordBatch` conversion. +- `sequins-pprof`: pprof parser entrypoint, if the crate remains integrated. + +### Current Surface Issues + +- `sequins-types` re-exports all Arrow schema modules and `sequins-traits`. + Many downstream users still import schemas through + `sequins_types::arrow_schema`, `sequins_types::schema_catalog`, and + `sequins_types::SignalType`. +- `sequins-types::metric_grouping` appears to have no non-test Rust callers in + the scan. It is behavior/policy code rather than core model definition. +- `sequins-arrow-schema` exposes every module publicly. `column_names` and + `ext_dtypes` are implementation/policy helpers, and several schema helper + functions look legacy or internal. +- `sequins-arrow-schema::SignalType` includes hot-tier array dispatch details + such as `COUNT` and `index`, which are storage implementation concerns. +- `sequins-attribute-codec` exposes raw CBOR encode/decode helpers, + `OverflowMapBuilder`, and domain-model overflow construction. In-workspace + production usage is routed through `sequins-otlp`. +- `sequins-otlp` exposes converter implementation modules and helper internals. + Storage mainly needs top-level conversion functions and limited + resource/scope conversion helpers. +- `sequins-otlp` currently routes DataFusion overflow UDF registration, causing + query execution to depend on OTLP conversion. +- `sequins-pprof` exposes a module containing one parser function and appears + unused by downstream workspace crates. + +### Narrowing Actions + +1. Migrate schema imports from `sequins-types` to `sequins-arrow-schema`, and + trait imports from `sequins-types` to the correct contract crate. +2. Remove `sequins-types` schema/trait re-exports after call-site migration. +3. Keep `sequins-arrow-schema` as a root-level schema facade. Make helper + modules private or `pub(crate)` unless they are explicitly intended as + public policy. +4. Move hot-tier indexing behavior out of `SignalType`. +5. Narrow `sequins-attribute-codec` to overflow map construction and optional + UDF registration. Hide raw CBOR and builder internals. +6. Gate `sequins-attribute-codec/datafusion` through the corresponding + `sequins-otlp/datafusion` feature instead of enabling it unconditionally. +7. Import overflow UDF registration directly from `sequins-attribute-codec` in + query execution code. +8. Make `sequins-otlp` modules private and expose conversion functions plus + `ProfileBatches`. +9. Either root-export `parse_pprof_to_samples` and hide `pprof_parser`, or defer + `sequins-pprof` until there is an integrated caller. + +## Storage, WAL, Tiers, and Indexes + +Crates covered: `sequins-storage`, `sequins-wal`, `sequins-live-query`, +`sequins-batch-chain`, `sequins-hot-tier`, `sequins-cold-tier`, +`sequins-series-index`, `sequins-companion-index`, and +`sequins-vortex-indexed-layout`. + +### Intended Contracts + +- `sequins-storage`: unified storage engine facade plus management and query + access ports. +- `sequins-wal`: durable append/subscribe API, not segment writer internals. +- `sequins-live-query`: heartbeat/subscription support if kept standalone. +- `sequins-batch-chain`: appendable hot table provider abstraction. +- `sequins-hot-tier`: hot storage operations and stats. +- `sequins-cold-tier`: cold storage operations, config, and query file format. +- `sequins-series-index`: series ID and lookup operations. +- `sequins-companion-index`: companion index builders and serialized payloads. +- `sequins-vortex-indexed-layout`: indexed layout registration/strategy. + +### Current Surface Issues + +- `sequins-storage` publicly re-exports `cold_tier`, `hot_tier`, `live_query`, + and `wal`, then re-exports many of their internals. DataFusion backend uses + storage accessors such as `hot_tier_arc`, `cold_tier_arc`, `wal`, and + `live_broadcast_tx`, which means query execution depends on storage internals. +- `Storage::generate_test_data` is part of the main storage surface despite + being test/demo behavior. +- `sequins-wal` exports `WalSegment`, `WalWriter`, `WriterConfig`, and segment + metadata. Production users mainly need `Wal`, `WalConfig`, `WalPayload`, + subscription, and watermark/event behavior. +- `sequins-live-query` exposes implementation modules. Production usage is + mostly `HeartbeatEmitter`; `LiveQueryManager` is held by storage but does not + appear to be a broad standalone contract. +- `sequins-batch-chain::BatchNode` is public because `head_arc` exposes + `Arc>`, leaking lock-free compaction details. +- `sequins-hot-tier` exposes `batch_chain`, `core`, `config`, and `error` + modules, and re-exports `SignalType` from another crate. +- `sequins-cold-tier` publicly exposes helpers, partitioning, record-batch + writing, all write modules, compaction, query, rollups, and index crates. + `ColdTier` also has public fields for config, store, and series index. +- `sequins-series-index::SeriesId(pub u64)` permits arbitrary construction even + though constructor/accessor methods exist. Persistence methods are public + though only cold tier appears to own object-store persistence. +- `sequins-companion-index` exposes bloom, trigram, log, and span modules. + Production cold-tier usage primarily builds indexes and converts them into + serialized `CompanionIndexBytes`. +- `sequins-vortex-indexed-layout` exposes `reader`, public metadata fields, and + re-exports `CompanionIndexBytes` through the strategy module. + +### Narrowing Actions + +1. Define a `sequins-storage` query-facing facade for the DataFusion backend: + hot table provider lookup, cold query/file-format access, WAL watermark or + event subscription, and live broadcast subscription. +2. Migrate backend/tests away from `sequins_storage::{hot_tier,cold_tier,wal}` + module paths before making those modules private. +3. Move `generate_test_data` behind a dev/test feature or out of the main + storage contract. +4. Hide WAL segment and writer internals unless explicit recovery tooling needs + them. +5. Hide batch-chain nodes and compaction internals behind crate-private handles. +6. Make hot-tier and cold-tier modules private while preserving root exports for + real facade types such as `HotTier`, `HotTierConfig`, `ColdTier`, + `ColdTierConfig`, `CompanionIndexConfig`, stats, errors, and storage + operations. +7. Make `ColdTier` fields private and expose accessors only where they are part + of the intended storage/query contract. +8. Make `SeriesId` field private and keep `new`/`as_u64`. +9. Hide companion index implementation modules unless bloom/trigram are meant to + be standalone libraries. +10. Hide indexed-layout reader internals and expose root-level registration and + strategy APIs. + +## Query Execution, View, Client, Server, and Apps + +Crates/apps covered: `sequins-datafusion-backend`, `sequins-view`, +`sequins-client`, `sequins-server`, `sequins-ffi`, `sequins-cli`, `apps/linux`, +and `example`. + +### Intended Contracts + +- `sequins-datafusion-backend`: query execution facade over a storage query + input. +- `sequins-view`: transport-neutral view strategies and deltas. +- `sequins-client`: remote query client, with transport separated from optional + query compilation over time. +- `sequins-server`: server constructors/types, not handler state internals. +- `sequins-ffi`: stable C ABI for data source, management, SeQL streams, views, + and memory release functions. +- `sequins-cli`, `apps/linux`, and `example`: internal apps, not reusable crate + APIs. + +### Current Surface Issues + +- `sequins-datafusion-backend` is relatively tight. The main design issue is + that `DataFusionBackend::new` requires concrete `Storage`, coupling execution + to the storage implementation. +- `sequins-view` exports a concise root API but leaves `delta`, `strategy`, and + `strategies` modules public. Downstream users only need root exports: + `ViewDelta`, `ViewDeltaStream`, `ViewStrategy`, `TableStrategy`, + `AggregateStrategy`, and `FlamegraphStrategy`. +- `sequins-view` also consumes `SeqlStream` directly and decodes Flight/Arrow + frames, coupling view logic to transport. +- `sequins-client` has a small API, but implementing/exposing raw `QueryExec` + lets callers send plan bytes through a client that may only need a SeQL text + contract. +- `sequins-server` exposes whole modules plus root re-exports. `FlightSqlState` + is public with a public `query_exec` field despite being an internal service + wrapper. +- `sequins-ffi` has true public ABI through `#[no_mangle] extern "C"` and the + generated header. Stable usage centers on data source lifecycle, management, + SeQL parse/query/live stream, view creation/cancel/free, and free functions. +- `sequins-ffi` also exports typed query stubs such as + `sequins_query_logs_stub`, `sequins_query_metrics_stub`, + `sequins_query_profiles_stub`, and `sequins_query_spans_stub`; these return + empty results and appear to exist for C header/model generation. +- `sequins-cli` and `apps/linux` expose incidental `pub` items inside binary + crates. These are not workspace library API surfaces. + +### Narrowing Actions + +1. Keep `sequins-datafusion-backend` public API mostly intact while moving its + input from concrete `Storage` toward a narrow storage query trait/facade. +2. Make `sequins-view` modules private and keep root-level re-exports. +3. Add a transport-neutral `ViewInputFrame` before trying to fully decouple view + strategies from Flight. +4. Keep `RemoteClient` as the main `sequins-client` type. Split lower-level + Flight plan transport from text-query compilation if dependency reduction is + needed. +5. Make `sequins-server` modules private and re-export only intended server + constructors/types. Hide `FlightSqlState`. +6. Split `sequins-ffi` into stable ABI and legacy/test ABI. Feature-gate or + remove typed query stubs once Swift/header generation no longer requires + them. +7. Treat `sequins-cli`, `apps/linux`, and `example` as app internals. Narrow + incidental `pub` items opportunistically after library contracts are cleaned + up. + +## Recommended Cleanup Sequence + +1. Remove low-risk manifest and stale-code leaks: + - Remove `seql-parser -> sequins-types`. + - Delete inactive duplicate modules in `sequins-query` after verifying they + are not referenced. + - Replace wildcard root exports where downstream imports already use the + intended direct crates. +2. Migrate umbrella call sites: + - Move schema imports from `sequins_types::*` to `sequins_arrow_schema::*`. + - Move trait imports from `sequins_types::*` to their real contract crate. + - Move Flight/frame imports from `sequins_query::*` to `sequins_flight::*` + and parser/AST/compiler imports to the owning `seql-*` crates. + - Move storage tier imports away from `sequins_storage::{hot_tier,cold_tier, + wal,live_query}`. +3. Introduce missing narrow contracts: + - Storage query facade for DataFusion. + - Query stream/Flight contract outside `sequins-traits`. + - Optional transport-neutral view frame. +4. Make implementation modules private: + - Cold tier write/query/helper modules. + - Hot tier core/batch-chain modules. + - WAL segment/writer modules. + - Companion index bloom/trigram internals. + - Indexed layout reader internals. + - View/server implementation modules. +5. Tighten FFI as a separate ABI cleanup: + - Identify Swift-required symbols from `apps/macos`. + - Move typed query stubs and unused result surfaces behind a legacy feature + or remove them once current Swift users are migrated. + +## Acceptance Checks + +Run these checks after each migration phase: + +- `cargo check --workspace --all-targets` +- `rg "sequins_types::arrow_schema|sequins_types::schema_catalog|sequins_types::SignalType"` +- `rg "sequins_storage::(hot_tier|cold_tier|wal|live_query)"` +- `rg "sequins_query::(flight|frame|schema|parser|ast)"` +- `cargo tree -i sequins-attribute-codec --workspace` + +Expected end state: + +- Schema users import `sequins-arrow-schema` directly. +- Trait users import the true contract crate directly. +- Storage users do not depend on hot/cold/WAL modules unless they are tests or + explicit low-level tooling. +- Query execution does not depend on `sequins-otlp` just to register overflow + UDFs. +- `sequins-traits` no longer requires Arrow Flight or OTLP protobuf for + protocol-neutral consumers. +- Public crate roots expose explicit facade types and functions, not wildcard + module trees. + +## Assumptions + +- No compatibility window is required for Rust workspace crates; migrate + downstream workspace users and remove old surfaces in the same cleanup. +- FFI is still a generated ABI consumed by the macOS app, so removals there + should be coordinated with Swift call-site/header generation updates. +- Binary crates are internal apps and should not drive library API design. diff --git a/docs/architecture/code-quality-roadmap.md b/docs/architecture/code-quality-roadmap.md new file mode 100644 index 00000000..67fd2966 --- /dev/null +++ b/docs/architecture/code-quality-roadmap.md @@ -0,0 +1,206 @@ +# Sequins Code Quality Roadmap + +This document summarizes a read-only, crate-by-crate audit of the Sequins +workspace. It focuses on maintainability, API contracts, module boundaries, and +the places where subsystem purpose has become unclear. + +The companion contract audit is +[`docs/architecture/api-surface-audit.md`](api-surface-audit.md). Use that audit +as the source of truth for public API narrowing: it identifies implementation +module leaks, umbrella exports, stale facades, and protocol-specific types that +cross crate boundaries in ways that make later refactors harder. + +The cleanup goal is not to make Sequins protocol-generic. OpenTelemetry is the +product domain model: OTLP ingest, OTLP-native WAL alignment, and OTEL-shaped +relational tables are intentional architecture. Apache Flight is the separate +retrieval/query plane because query results are Arrow/DataFusion-native. + +## Phase 0: Stabilize This PR + +Subsystem quality work: + +- Keep the CI fix for ephemeral OTLP test ports. +- Keep documentation scoped to sequencing and contract hardening. +- Do not propose non-OTEL ingest or generic telemetry support. +- Do not introduce a reusable production runtime crate in this cleanup plan. + +API/interface hardening: + +- Treat `api-surface-audit.md` as the contract-hardening companion to these + subsystem notes. +- Use the audit to check whether a proposed cleanup removes implementation + leaks or just moves them to a different umbrella crate. + +Acceptance: + +- Docs describe OTLP/OTEL alignment as product architecture, not accidental + coupling. +- Flight remains the retrieval/query interface for Arrow/DataFusion results. +- Runtime extraction is out of scope except for a possible future local-only + embedded setup helper below FFI/Linux app boundaries. + +## Phase 1: Low-Risk API Surface Tightening + +Subsystem quality work: + +- Remove unused or misleading manifest dependencies, such as stale + parser/query/type coupling. +- Delete inactive duplicate implementation files only after workspace imports + have moved to the owning crates. +- Replace broad wildcard root exports with explicit exports where a crate has a + clear public contract. + +API/interface hardening: + +- Remove or deprecate umbrella exports from `sequins-types`, `sequins-query`, + and `sequins-storage` where they only forward implementation details. +- Migrate call sites so schema, parser, AST, Flight, and trait contracts are + imported from their owning crates. +- Prefer direct purpose crates over compatibility paths documented in + `api-surface-audit.md`. + +Acceptance: + +- `seql-parser` no longer depends on broad domain/type crates for parser-only + behavior. +- Schema users import `sequins-arrow-schema` directly. +- Query users import parser, AST, compiler, Flight, and frame types from their + owning crates rather than through `sequins-query`. +- Storage users do not reach through `sequins-storage::{hot_tier,cold_tier,wal, + live_query}` unless they are explicit low-level tooling or tests. + +## Phase 2: Query and Retrieval Boundary + +Subsystem quality work: + +- Narrow `sequins-query` to either a small query contract crate or eliminate it + as a facade. +- Keep `seql-ast`, `seql-parser`, and `seql-substrait` focused on language + syntax, parsing, validation, and compilation. +- Keep `sequins-flight` focused on Flight/Arrow retrieval framing, stream + metadata, and IPC encoding. + +API/interface hardening: + +- Move reducer and query-result helpers out of language/compiler crates when + they belong to Flight, view, or query-client behavior. +- Move Flight-coupled stream traits out of protocol-neutral trait crates. +- Make Flight IPC encoding failures observable through `Result`-returning APIs. + +Acceptance: + +- Compiler consumers do not inherit client-side Flight reduction behavior. +- View/client behavior can consume Flight frames without depending on parser or + Substrait internals unless they explicitly compile text queries. +- Public query crate roots expose explicit facade types and functions, not + wildcard module trees. + +## Phase 3: OTEL Ingest and Schema Boundary + +Subsystem quality work: + +- Preserve OTLP/OTEL-native ingest contracts as intentional product + architecture. +- Keep OTLP-to-Arrow conversion as the core ingest responsibility. +- Keep `sequins-arrow-schema` as the schema authority for OTEL-shaped tables. +- Keep DataFusion-specific UDF registration explicit. + +API/interface hardening: + +- Hide low-level protobuf plumbing, attribute codec builders, raw CBOR helpers, + and converter implementation modules behind narrow OTEL-oriented conversion + APIs. +- Migrate users away from schema re-exports through `sequins-types`. +- Avoid making query execution depend on broad OTLP internals just to access + attribute overflow behavior. + +Acceptance: + +- OTLP conversion APIs are visible at the OTEL ingest boundary, while raw + builders and generated protobuf plumbing are not broad workspace API. +- `sequins-arrow-schema` is the direct source for schema catalog and signal + schema imports. +- Query execution imports attribute-overflow UDF registration from the codec + layer that owns it, not from the OTLP conversion facade. + +## Phase 4: Storage, WAL, and Index Boundary + +Subsystem quality work: + +- Fix P0 indexed-layout pruning correctness for equality predicates on fields + that are not bloom-indexed. +- Keep storage optimized for OTEL-shaped data rather than general-purpose event + storage. +- Preserve OTLP-native WAL alignment while narrowing the public WAL contract to + durable append, replay, watermarks, and subscription behavior. + +API/interface hardening: + +- Define the query-facing `sequins-storage` facade around what DataFusion needs: + hot table lookup, cold access, WAL watermarks/events, and live subscriptions. +- Hide hot-tier, cold-tier, WAL segment/writer, live-query, batch-chain, + compaction, and indexed-layout implementation modules. +- Make structural internals such as `ColdTier` fields and `SeriesId` + representation private unless there is a concrete external contract. + +Acceptance: + +- Indexed-layout pruning has regression tests covering equality predicates on + indexed and non-indexed fields. +- DataFusion uses a storage query facade instead of reaching through storage + implementation modules. +- Companion index writer/reader behavior is owned by the same encoded bundle + contract. +- Storage docs and APIs retain OTEL-shaped table/WAL assumptions. + +## Phase 5: App, FFI, and Local Embedded Boundary + +Subsystem quality work: + +- Keep FFI as the stable ABI surface. +- Treat CLI, Linux app, and examples as app surfaces, not reusable production + server construction APIs. +- Keep remote/local behavior explicit so unsupported remote capabilities are + not implied by stable ABI constructors. + +API/interface hardening: + +- Avoid exporting typed query/test stubs as product API. +- Split legacy/test ABI from stable ABI when Swift/header generation allows. +- Narrow incidental `pub` items in binary/app crates after library contracts are + cleaned up. +- If shared setup code is needed, keep it local-only and below the FFI/Linux app + layer rather than introducing a production runtime crate. + +Acceptance: + +- Swift/header-required symbols are identified before FFI removals. +- Typed query stubs are feature-gated or removed once current Swift/header + generation no longer requires them. +- Local embedded setup is not presented as a general server/runtime API. + +## Verification Gates + +Run these checks after each migration phase: + +- `cargo check --workspace --all-targets` +- `cargo test -p sequins-ffi` +- `swift test` in `apps/macos/SequinsData` +- `rg "sequins_types::arrow_schema|sequins_types::schema_catalog|sequins_types::SignalType"` +- `rg "sequins_storage::(hot_tier|cold_tier|wal|live_query)"` +- `rg "sequins_query::(flight|frame|schema|parser|ast)"` +- `cargo tree -i sequins-attribute-codec --workspace` + +Documentation acceptance: every subsystem section should name its intended +public contract, identify current implementation leaks, and list the smallest +refactor that improves maintainability without weakening OTEL alignment. + +## Assumptions + +- This PR documents and sequences cleanup work; it does not perform every crate + refactor. +- No compatibility window is required for Rust workspace crates; migrate + downstream workspace users and remove old surfaces in the same cleanup. +- FFI is a generated ABI consumed by the macOS app, so removals there should be + coordinated with Swift call-site/header generation updates. +- Binary crates are internal apps and should not drive library API design. diff --git a/docs/architecture/subsystems/contracts-and-schemas.md b/docs/architecture/subsystems/contracts-and-schemas.md new file mode 100644 index 00000000..05c0cf9b --- /dev/null +++ b/docs/architecture/subsystems/contracts-and-schemas.md @@ -0,0 +1,250 @@ +# Contracts and Schemas + +Crates covered: `sequins-types`, `sequins-traits`, `sequins-arrow-schema`, and +`sequins-flight`. + +## Intended Purpose + +The foundation crates should be narrow: + +- `sequins-types`: passive domain models and value types. +- `sequins-traits`: protocol-neutral shared traits and small utility types. +- `sequins-arrow-schema`: Arrow schema definitions and logical schema catalog. +- `sequins-flight`: Flight/query stream wire metadata and encoding helpers. + +Intended public contracts: + +- `sequins-types`: passive domain models and value types without schema or + protocol umbrella exports. +- `sequins-traits`: protocol-neutral shared traits and small utility types. +- `sequins-arrow-schema`: canonical OTEL-shaped Arrow table schemas and signal + schema catalog. +- `sequins-flight`: Flight/query stream metadata, builders, and IPC helpers for + Arrow/DataFusion query results. + +OpenTelemetry remains the domain model for ingest and table shape. These +contracts should avoid accidental umbrella dependencies, but they should not +weaken OTLP ingest or OTEL-shaped schema alignment. + +## Current Weaknesses + +### `sequins-types` Is Both Domain Crate and Compatibility Facade + +`sequins-types` re-exports `sequins-arrow-schema` and `sequins-traits`. + +Why it matters: + +- Downstream code can depend on the broadest crate and accidentally pull schema, + trait, Arrow, and protocol concerns through the model layer. +- The crate manifest contains dependencies that appear unused after these + responsibilities moved elsewhere. + +Direction: + +- Keep passive domain models in `sequins-types`. +- Migrate callers to import schemas from `sequins-arrow-schema` and traits from + `sequins-traits` or the future query protocol crate. +- Keep temporary compatibility exports only behind an explicit module or feature. + +Priority: P1. + +### Time Value Types Depend on Wall Clock + +`TimeRange` and `TimeWindow` constructors call `Timestamp::now()` internally in +some paths. + +Why it matters: + +- Pure value operations become nondeterministic. +- Tests and replay logic must know which APIs secretly read the system clock. + +Direction: + +- Make wall-clock constructors explicit, for example `last_minutes_from(now, + minutes)`. +- Keep convenience helpers with names that clearly signal system time use. + +Priority: P1. + +### Metric Identity Has Competing Definitions + +`MetricId::from_name_and_service` and `MetricId::from_fields` coexist. Health +metric generation still uses legacy identity with placeholder resource/scope +values. + +Why it matters: + +- Generated and ingested metrics may not share stable identity semantics. +- Resource/scope identity becomes implicit and lossy. + +Direction: + +- Introduce a `MetricIdentity` value object. +- Require generated and ingested metric paths to use the same identity inputs. + +Priority: P1. + +### Behavior Modules Live in the Model Crate + +Health metric generation and metric grouping detection live under +`sequins-types`. + +Why it matters: + +- Domain policy and generated telemetry behavior evolve differently from passive + model structs. +- UI/query/storage consumers may want those policies without depending on all + models through one crate. + +Direction: + +- Keep structs, enums, and IDs in `sequins-types`. +- Move generation/grouping policy to storage, view, or a dedicated model-policy + crate once call sites are clear. + +Priority: P2. + +### `sequins-traits` Mixes Protocol-Neutral and Protocol-Specific Contracts + +`sequins-traits` exposes `arrow_flight::FlightData` through `SeqlStream` and OTLP +protobuf request/response types through `OtlpIngest`. + +Why it matters: + +- A supposedly light contract crate pulls Flight retrieval and OTLP ingest + surfaces even for consumers that only need management or time utilities. +- The issue is the umbrella location, not the OTLP ingest contract itself. + +Direction: + +- Move query transport traits and stream types to `sequins-flight` or a dedicated + query protocol crate. +- Move OTLP ingest traits behind an explicit OTEL ingest contract or feature. +- Leave `sequins-traits` with protocol-neutral types such as `Duration`, + `NowTime`, and management contracts. + +Priority: P1. + +### `sequins-traits::Error` Is Too Generic + +The top-level error has only generic string-style behavior. + +Why it matters: + +- API consumers cannot distinguish validation, unavailable, retryable, or + internal failures. + +Direction: + +- Add stable variants where shared traits require shared error semantics. +- Prefer domain-specific errors for richer subsystem APIs. + +Priority: P2. + +### Vortex Leaks Into Arrow Schema + +`sequins-arrow-schema` depends on Vortex and contains Vortex extension dtypes and +encoding hints. + +Why it matters: + +- A crate named and documented as Arrow schema is also a Vortex policy crate. +- Non-Vortex schema consumers inherit storage-format concepts. + +Direction: + +- Gate Vortex-specific dtypes/hints behind a feature or move them to a + `sequins-vortex-schema` crate. +- Keep logical schema and Arrow field construction separate from Vortex encoding + strategy. + +Priority: P1. + +### Column Naming Policy Is Inconsistent + +Custom attribute names use an `attr_` prefix, while built-in promoted attributes +use names like `http_request_method` and `service_name_attr`. + +Why it matters: + +- Attribute promotion, companion indexing, parser field recognition, and view + projection must each learn naming exceptions. + +Direction: + +- Define one `ColumnNamePolicy`. +- Apply it to built-in and custom promoted columns. +- Test that schema, codec, index builders, and query field resolution agree. + +Priority: P1. + +### `SignalType` Mixes Logical Identity and Hot-Tier Indexing + +`sequins-arrow-schema::SignalType` owns schema dispatch and hot-tier array index +constants. + +Why it matters: + +- Logical schema identity knows about hot-tier storage layout. +- Hot-tier implementation choices become schema API surface. + +Direction: + +- Keep logical signal identity and schema dispatch in schema/catalog code. +- Move hot-tier array indexing into hot-tier internals. + +Priority: P2. + +### `sequins-flight` Mixes Wire Metadata and Frame Models + +Flight metadata repeats schema frame concepts and depends on AST schema types and +traits. Its public API wildcard-exports all helpers. + +Why it matters: + +- Wire format, client reducer frames, and query schema metadata are not clearly + owned. +- All helper functions become stable public surface. + +Direction: + +- Make one canonical query stream metadata model. +- Explicitly re-export stable wire types and builders. +- Keep lower-level helpers internal or under named modules. + +Priority: P1. + +### Flight Encoding Silently Swallows Errors + +`batch_to_ipc` ignores Arrow IPC writer construction/write/finish failures and +can return empty bytes. + +Why it matters: + +- Encoding failure can look like a valid empty payload. +- Downstream reducers and views cannot distinguish corruption from no data. + +Direction: + +- Return `Result` from IPC helpers. +- Make FlightData builder APIs return `Result`. +- Propagate encoding failures through query execution errors. + +Priority: P1. + +## Boundary Decisions + +- Do not join `sequins-types` and `sequins-traits`. +- Move query transport out of `sequins-traits`. +- Keep Arrow schemas separate from domain models. +- Gate or split Vortex schema policy. +- Treat `sequins-flight` as the natural owner for query stream wire contracts. + +## Acceptance Checks + +- `sequins-types` builds without Arrow schema or trait dependencies except + compatibility features. +- `sequins-traits` builds without Arrow Flight and OTLP proto unless explicit + features require them. +- One warning code representation is used on both internal and wire metadata. +- Flight IPC encoding failures are observable in tests. diff --git a/docs/architecture/subsystems/indexing.md b/docs/architecture/subsystems/indexing.md new file mode 100644 index 00000000..353ab3d2 --- /dev/null +++ b/docs/architecture/subsystems/indexing.md @@ -0,0 +1,193 @@ +# Indexing and Profile Support + +Crates covered: `sequins-pprof`, `sequins-companion-index`, +`sequins-series-index`, and `sequins-vortex-indexed-layout`. + +## Intended Purpose + +Indexing crates should make pruning and lookup cheaper without changing query +semantics. Profile parsing should isolate pprof dependency cost while exposing +reusable parsed and resolved profile representations. + +Intended public contracts: + +- `sequins-companion-index`: companion index builders, encoded bundle format, + and field-aware lookup helpers. +- `sequins-vortex-indexed-layout`: Vortex registration/strategy integration + that delegates encoded companion-index details to the companion index crate. +- `sequins-series-index`: in-memory series lookup and typed series IDs, with + persistence hidden behind a store/feature boundary. +- `sequins-pprof`: pprof parse, symbol resolution, and sample materialization + as separate entrypoints. + +## Current Weaknesses + +### Vortex Indexed Layout Can Incorrectly Prune Data + +The indexed-layout reader extracts all string equality predicates and checks +them against bloom filters. Fields not present in bloom filters return false, +which can incorrectly skip files for predicates such as `service_name = ...` or +other low-cardinality fields. + +Why it matters: + +- This is a correctness bug. Query results can be incomplete. + +Direction: + +- Persist/read companion index capability metadata. +- Only apply bloom pruning to fields known to have bloom indexes. +- Delegate other predicates to Vortex or Tantivy pruning where supported. +- Add regression tests with predicates on indexed and non-indexed fields. + +Priority: P0. + +### Companion Index Format Ownership Is Split + +`sequins-companion-index` defines `CompanionIndexBytes`, while +`sequins-vortex-indexed-layout` separately bundles, serializes, deserializes, and +opens Tantivy files. + +Why it matters: + +- Format changes require synchronized edits across crates. +- Reader behavior depends on private assumptions about writer output. + +Direction: + +- Let `sequins-companion-index` own the serialized bundle format. +- Expose APIs like `CompanionIndexBundle::encode`, `decode`, and + field-aware search helpers. +- Keep Vortex layout focused on integrating companion indexes with Vortex + pruning. + +Priority: P1. + +### Tantivy Reader Reconstructs Indexes in Tempdirs + +Query-time Tantivy access writes all files to a tempdir and opens a Tantivy index +from disk. + +Why it matters: + +- Pruning can become filesystem-heavy and repeated across splits. +- The Vortex reader owns low-level companion index reconstruction. + +Direction: + +- Cache decoded companion indexes per segment. +- Prefer a RAM-directory reconstruction API owned by `sequins-companion-index`. + +Priority: P1. + +### Span Tantivy Indexes Are Not Used for Span Equality Pruning + +Span index writing emits Tantivy files, but reader-side Tantivy lookup only +searches a `body` field. + +Why it matters: + +- Storage and write complexity may not translate into query pruning benefits. + +Direction: + +- Either teach the reader to query field-specific Tantivy equality/range + predicates, or stop emitting unused span Tantivy segments until supported. + +Priority: P1. + +### Companion Index Generic Strategy Lives in Span Module + +Log indexing imports a strategy enum from `span_index`. + +Why it matters: + +- A generic companion-index concept is hidden in a product-specific module. + +Direction: + +- Move strategy and metadata definitions to neutral modules such as `strategy` + and `metadata`. +- Keep signal-specific builders focused on extracting fields. + +Priority: P1. + +### Log and Span Builders Duplicate Field Extraction Rules + +Log and span index builders duplicate Arrow field extraction and `attr_` naming +logic. + +Why it matters: + +- Schema convention changes require edits in multiple builders. + +Direction: + +- Add a shared `BatchFieldAccess` or `PromotedColumnSet` helper tied to the + shared column naming policy. + +Priority: P2. + +### Series Index Mixes Core Index and Object-Store Persistence + +`sequins-series-index` is otherwise light, but owns async object-store +`persist/load` methods. + +Why it matters: + +- In-memory users inherit object-store and async dependencies. + +Direction: + +- Split persistence into `SeriesIndexStore` or feature-gate object-store support. +- Keep the core index as an in-memory, dependency-light structure. + +Priority: P1. + +### Series Index Load Treats All Get Errors as Missing + +Any object-store `get` error returns a new empty index. + +Why it matters: + +- Permission, transient network, and backend failures can silently reset the + index. + +Direction: + +- Distinguish not-found from other object-store errors. +- Preserve failure for non-not-found errors. + +Priority: P1. + +### Pprof Parser Has Too Many Layers in One API + +`sequins-pprof` parses pprof, resolves symbols, and materializes Sequins +`ProfileSample` values with placeholder storage-normalization IDs. + +Why it matters: + +- Callers cannot reuse parsed/resolved pprof structures without accepting + storage-specific sentinel values. + +Direction: + +- Split into `parse_profile`, `resolve_symbols`, and `to_profile_samples`. +- Keep pprof dependency isolation, but expose lower-level parsed/resolved data. + +Priority: P1. + +## Boundary Decisions + +- Keep companion-index separate from Vortex layout, but move byte-format and + Tantivy bundle operations into companion-index. +- Keep series-index separate from cold-tier, with optional persistence. +- Keep pprof separate as a dependency isolation crate, but split parser stages. + +## Acceptance Checks + +- Indexed-layout tests prove non-indexed predicates do not prune files. +- Companion index writer and reader use the same encoded bundle API. +- Series index load distinguishes not-found from other object-store failures. +- Pprof parsing can be used without immediately producing storage-bound sample + IDs. diff --git a/docs/architecture/subsystems/ingest-and-storage.md b/docs/architecture/subsystems/ingest-and-storage.md new file mode 100644 index 00000000..985c750e --- /dev/null +++ b/docs/architecture/subsystems/ingest-and-storage.md @@ -0,0 +1,294 @@ +# Ingest and Storage + +Crates covered: `sequins-otlp`, `sequins-attribute-codec`, `sequins-wal`, +`sequins-batch-chain`, `sequins-hot-tier`, `sequins-cold-tier`, +`sequins-storage`, and `sequins-live-query`. + +## Intended Purpose + +The ingest/storage subsystem should separate these concerns while preserving +Sequins' OTEL domain model: + +- OTLP decoding and Arrow conversion. +- Attribute encoding and promoted-column handling. +- OTLP-native durable append/replay log. +- Hot in-memory batches. +- Cold object-store layout and compaction. +- Storage orchestration and management APIs. +- Live query subscription and stream coordination. + +Intended public contracts: + +- `sequins-otlp`: OTLP-to-Arrow conversion and OTEL-oriented batch outputs. +- `sequins-attribute-codec`: promoted/overflow attribute encoding helpers and + explicit DataFusion UDF registration. +- `sequins-wal`: durable OTLP-aligned append, replay, watermark, and + subscription behavior. +- `sequins-storage`: storage-level orchestration and query-facing access ports, + not a public umbrella for tier internals. + +## Current Weaknesses + +### OTLP Conversion and Domain Model Conversion Are Mixed + +`sequins-otlp` describes itself as direct Arrow conversion without domain types, +but publicly exports helpers that return `sequins-types` models. + +Why it matters: + +- A conversion crate owns both physical Arrow ingestion and metadata registry + hydration. +- Callers cannot choose only one layer cleanly. + +Direction: + +- Keep OTLP-to-Arrow conversion as the core responsibility. +- Move domain model adapters behind a feature or into a separate adapter module. + +Priority: P1. + +### DataFusion Feature Is Effectively Bypassed in OTLP/Codec + +`sequins-otlp` depends on `sequins-attribute-codec` with the codec's +`datafusion` feature enabled unconditionally, despite having its own optional +feature. + +Why it matters: + +- Plain OTLP conversion consumers inherit DataFusion dependencies. + +Direction: + +- Make `sequins-attribute-codec` dependency feature-neutral by default. +- Wire `sequins-otlp/datafusion` to enable both `dep:datafusion` and + `sequins-attribute-codec/datafusion`. + +Priority: P1. + +### Attribute Codec Exposes OTLP Plumbing Too Broadly + +`sequins-attribute-codec` depends on `opentelemetry-proto` and public APIs accept +OTLP `KeyValue` types. + +Why it matters: + +- Low-level protobuf plumbing becomes part of the codec's broad public surface. +- Callers that only need OTEL-shaped promoted/overflow attributes inherit raw + OTLP request semantics. + +Direction: + +- Keep the codec OTEL-oriented, but expose a narrower attribute value/view API + rather than raw protobuf builders everywhere. +- Move protobuf adapter functions into `sequins-otlp`. +- Keep promoted-attribute routing in the codec crate behind explicit APIs. + +Priority: P1. + +### Attribute Encoding Errors Are Hidden + +CBOR encoding helpers and builder finalization paths can return empty bytes or +ignore errors. + +Why it matters: + +- Encoding corruption can be stored as apparently valid empty binary data. + +Direction: + +- Introduce `AttributeCodecError`. +- Return `Result` from encode helpers and array builders. +- Propagate errors to ingest callers instead of silently filling invalid values. + +Priority: P1. + +### WAL Exposes OTLP Internals Instead of an OTEL Ingest Contract + +`sequins-wal::WalPayload` stores OTLP protobuf export requests directly. + +Why it matters: + +- OTLP-native WAL alignment is intentional, but generated protobuf details leak + into code that should only need append/replay/watermark contracts. +- WAL evolution and recovery policy are harder to manage when callers depend on + the concrete request representation. + +Direction: + +- Preserve OTLP-native append/replay semantics. +- Add versioned OTEL ingest entries or a narrow payload wrapper so generated + protobuf details are hidden behind WAL APIs. +- Keep replay, migration, and recovery behavior explicit without making the WAL + a generic event log. + +Priority: P1. + +### WAL Recovery Silently Skips Errors + +Startup discovery scans segment contents and skips list/read errors. + +Why it matters: + +- Corruption, permissions, and transient object-store failures can look like an + empty or partial WAL. + +Direction: + +- Persist segment metadata or trailers. +- Distinguish not-found from read/corruption errors. +- Make recovery policy explicit in config. + +Priority: P1. + +### Batch Chain Exposes Unsafe Internals + +`BatchNode` is public and `head_arc()` exposes +`Arc>`. + +Why it matters: + +- Hot-tier must understand batch-chain internals to compact or flush. +- Unsafe implementation details become public API. + +Direction: + +- Expose a compactor or `spawn_compactor` API. +- Hide raw epoch pointers and nodes. +- Split or feature-gate DataFusion `TableProvider` and async compaction from + core chain storage if the crate is meant to be reusable. + +Priority: P1. + +### Hot-Tier Re-Exports Batch Chain as Compatibility Surface + +`sequins-hot-tier` exposes `sequins-batch-chain` through both root re-exports and +a `batch_chain` module. + +Why it matters: + +- Multiple public paths identify the same lower-level API. +- Callers can depend on internals through the hot-tier crate. + +Direction: + +- Deprecate compatibility paths. +- Make hot-tier expose signal-aware append/query APIs rather than batch-chain + internals. + +Priority: P1. + +### Hot-Tier Resource and Scope IDs Are Raw Hashes + +Resource and scope IDs are raw `u32` FNV hashes. + +Why it matters: + +- Identity derivation is a storage implementation detail. +- Collision risk and placeholder IDs leak into other crates. + +Direction: + +- Move identity derivation into typed domain/model code or a metadata index. +- Use typed newtypes and wider stable hashes. + +Priority: P1. + +### Cold-Tier Public Surface Is Too Wide + +`sequins-cold-tier` publicly exposes implementation modules and public fields on +`ColdTier`, including config, object store, and series index. + +Why it matters: + +- External callers can bypass invariants around path layout, index persistence, + and object-store behavior. +- Implementation modules become stable public API. + +Direction: + +- Keep `ColdTier`, config, query/write entrypoints, and selected rollup types + public. +- Make fields private with focused accessors or constructor injection for tests. +- Stop re-exporting index/layout crates wholesale. + +Priority: P1. + +### Cold-Tier Layout and Query Logic Are Duplicated + +Signal path mapping is repeated across write, compaction, helper, and partition +code. Query paths reconstruct schemas and duplicate scan/filter loops. + +Why it matters: + +- Storage path and schema changes require edits in multiple modules. +- Object-store list failures can become empty query results. + +Direction: + +- Centralize a `SignalLayout` table using the shared catalog. +- Reuse shared schemas from `sequins-arrow-schema`. +- Add a reusable Vortex scan helper. +- Return or trace storage errors intentionally. + +Priority: P1. + +### `sequins-storage` Is a Re-Export Umbrella and Local Lifecycle Owner + +`sequins-storage` re-exports tier crates and WAL, while `Storage` owns ingest +conversion, WAL, hot/cold tiers, live broadcast, retention, health config, and +background lifecycle. + +Why it matters: + +- Storage is both a facade and an engine. +- Callers can reach through it into every layer. +- Local lifecycle behavior is hard to change independently from ingest or + management. + +Direction: + +- Expose storage-level APIs only. +- Split concepts into storage engine, ingest pipeline, management store, and + local background supervisor. +- Move low-level access to direct crate dependencies for code that truly needs + them. + +Priority: P1. + +### Live Query Crate Has Shrunk Below a Clear Boundary + +`sequins-live-query` currently owns subscription accounting and heartbeat while +execution lives in storage/DataFusion backend. + +Why it matters: + +- The crate is too small to justify its dependency surface unless it becomes the + protocol owner for live query behavior. + +Direction: + +- Either fold subscription accounting into storage/runtime, or expand the crate + into a real live-query protocol/execution abstraction. +- Move heartbeat encoding next to Flight/query protocol if it remains + transport-specific. + +Priority: P1. + +## Boundary Decisions + +- Keep WAL separate and OTLP-native, while hiding generated protobuf details + behind append/replay contracts. +- Keep cold-tier, hot-tier, and batch-chain separate, but hide internals. +- Keep OTLP conversion separate from storage. +- Treat `sequins-storage` as orchestration, not a public umbrella for all tier + crates. +- Re-evaluate `sequins-live-query` after the query protocol boundary is cleaned. + +## Acceptance Checks + +- OTLP conversion can build without DataFusion. +- Attribute codec exposes narrow OTEL-oriented attribute APIs without forcing + broad protobuf plumbing on all callers. +- WAL tests cover not-found, corruption, and read failure recovery behavior. +- Hot-tier callers no longer need batch-chain internals to append signal batches. +- Cold-tier path/schema behavior is driven by one layout/catalog definition. diff --git a/docs/architecture/subsystems/query-view-and-runtime.md b/docs/architecture/subsystems/query-view-and-runtime.md new file mode 100644 index 00000000..04e8d52d --- /dev/null +++ b/docs/architecture/subsystems/query-view-and-runtime.md @@ -0,0 +1,299 @@ +# Query Execution, View, and Local Apps + +Crates/apps covered: `sequins-datafusion-backend`, `sequins-view`, +`sequins-client`, `sequins-server`, `sequins-cli`, `sequins-ffi`, `apps/linux`, +and `example`. + +## Intended Purpose + +This layer should separate: + +- Query execution over storage. +- Flight query stream wire protocol and client transport. +- View-model updates from query stream frames. +- Local embedded setup for app/FFI surfaces. +- CLI, FFI, and Linux UI adapters. + +Intended public contracts: + +- `sequins-datafusion-backend`: query execution over a narrow storage query + input. +- `sequins-flight`: Flight/Arrow retrieval framing for query results. +- `sequins-view`: transport-neutral view strategies and deltas, with Flight + decoding in an adapter. +- `sequins-client`: remote query and management clients, with text compilation + optional over time. +- `sequins-ffi`: stable C ABI; typed test/header stubs are not product API. + +## Current Weaknesses + +### DataFusion Execution Crosses Too Many Boundaries + +`sequins-datafusion-backend/src/execution.rs` handles plan decoding, snapshot +execution, live append/replace execution, WAL policy, filtering, expiry, and +Flight framing. + +Why it matters: + +- Different policies change for different reasons but share one large module. +- Live query behavior is hard to reason about independently from DataFusion plan + execution or wire framing. + +Direction: + +- Split into modules for plan decoding, snapshot execution, live append, live + replace, filtering, and framing. +- Keep `DataFusionBackend` as the facade that wires those pieces together. + +Priority: P1. + +### Backend Signal/Table Names Are Stringly and Leaky + +Execution maps strings back to signals, including fallback behavior that routes +unknown names to spans. Registration uses physical names such as +`profile_stacks`, while query/view code may use aliases such as `stacks`. + +Why it matters: + +- Unknown or renamed signals can subscribe to the wrong table. +- Compiler, backend, and view aliases drift independently. + +Direction: + +- Use the shared signal catalog for query aliases, physical table names, and + hot-tier signal mapping. +- Return structured errors for unknown names. + +Priority: P1. + +### Registration Mixes Catalog, Compatibility Policy, and Logging + +DataFusion registration embeds schema functions, storage paths, schema +compatibility fallback, and direct `eprintln!` output. + +Why it matters: + +- Table identity and operational fallback policy are coupled. +- Schema evolution behavior is hard to test or observe. + +Direction: + +- Move table catalog data to the shared catalog. +- Isolate cold schema compatibility into a helper that emits structured + `tracing` warnings. + +Priority: P2. + +### Arrow-to-Query Schema Conversion Loses Semantics + +Backend schema conversion marks every column as `Field` and maps unknown Arrow +types to string-like query schema types. + +Why it matters: + +- Clients cannot distinguish group keys, row IDs, aggregates, or unsupported + complex values reliably. + +Direction: + +- Return `Result` for unsupported types. +- Let compiler/plan metadata provide column roles instead of inferring all roles + from Arrow alone. + +Priority: P2. + +### View Strategies Are Coupled to Flight/Arrow Transport + +`sequins-view` strategy APIs accept `SeqlStream`, decode Flight metadata, and +read IPC batches directly. + +Why it matters: + +- View logic cannot be reused or tested independently from Flight. +- The crate inherits broad query/transport dependencies. + +Direction: + +- Introduce a transport-neutral `ViewInputFrame`. +- Keep pure view strategy state over typed batches/deltas. +- Put Flight decoding in an adapter module. + +Priority: P1. + +### Expiry Semantics Are Duplicated and Lossy + +Backend emits expiry metadata with one row ID, while table strategy hardcodes an +expired count of one. + +Why it matters: + +- Batch or range expiry can be represented incorrectly to frontends. + +Direction: + +- Define a shared expiry contract: row range, row count, or predicate. +- Make backend and view use the same metadata fields. + +Priority: P1. + +### Flamegraph View Hardcodes Query Shape and Drops Bad Rows + +Flamegraph strategy only recognizes `stacks` and `frames` aliases and silently +continues on missing/null/type-mismatched required columns. + +Why it matters: + +- Compiler alias changes or schema evolution can produce empty views without a + clear error. + +Direction: + +- Supply aliases from query metadata or strategy configuration. +- Add typed row extractors that emit warnings/errors for required-column + failures. + +Priority: P1. + +### Client Mixes Compilation and Flight Transport + +`RemoteClient` stores a DataFusion `SessionContext`, compiles SeQL, and owns +Flight `GetFlightInfo`/`DoGet` calls. + +Why it matters: + +- Thin remote clients inherit heavy compiler/DataFusion dependencies. +- Callers that already have plan bytes cannot depend only on transport. + +Direction: + +- Split plan transport from optional query compilation. +- Keep a convenience `RemoteQueryClient` over a lower-level `FlightPlanClient`. + +Priority: P1. + +### Server Lifecycle Is Shaped by Embedding Needs + +`OtlpServer` combines service construction, readiness signaling, gRPC handlers, +HTTP handlers, content negotiation, limits, and tests in one module. Lifecycle +APIs accept `std::sync::mpsc::Sender` readiness channels for embedders. + +Why it matters: + +- Protocol changes risk lifecycle behavior. +- FFI/Linux embedding concerns leak into the server crate. + +Direction: + +- Split OTLP server modules into lifecycle, gRPC, HTTP, and codec pieces. +- Expose lower-level build/bind APIs returning listeners/services. +- Let app/adapter setup own readiness signaling. + +Priority: P1. + +### Management Protocol Has No Client Counterpart + +Server exposes REST management routes, but FFI remote management reports +unsupported. + +Why it matters: + +- Remote and local data sources have different capabilities behind similar + shapes. + +Direction: + +- Add a management client to `sequins-client` or define a small management + protocol crate shared by server/client/FFI. + +Priority: P2. + +### CLI, FFI, and Linux Duplicate Local Embedded Setup + +CLI daemon setup, FFI `DataSourceImpl`, and Linux `LocalServer` each own storage, +backend, and server assembly. + +Why it matters: + +- Local embedded behavior has multiple assembly roots. +- Config, port, readiness, and local/remote behavior can drift. + +Direction: + +- Do not introduce a reusable production runtime crate as part of this cleanup. +- If duplication becomes a blocking issue, create a local-only embedded setup + helper below the FFI/Linux app boundary. +- Keep CLI, FFI, and Linux responsible for their adapter-specific config, + pointer/string/callback conversion, and UI integration. + +Priority: P1. + +### FFI Remote Mode Is Structurally Present but Unsupported + +FFI stores a remote client, but snapshot/live query and management return null or +unsupported for remote mode. + +Why it matters: + +- The API suggests remote support that is not functionally present. + +Direction: + +- Either implement remote dispatch through query and management clients, or + remove/feature-gate remote constructors until supported. + +Priority: P1. + +### Linux UI Owns Domain Analysis + +Linux components contain health scoring, trace grouping/tree building, Arrow IPC +decoding, and broad root app state. + +Why it matters: + +- UI components become domain model and local service adapters. +- The logic cannot be reused by FFI or other frontends. + +Direction: + +- Move health analysis, trace/log row projection, and typed stream adapters into + `sequins-view` or a new app-model crate. +- Split the root app into environment/profile management, OTLP controls, service + sidebar, and tab host components. + +Priority: P1/P2. + +### Example Duplicates Protocol Constants + +The example hardcodes endpoints, OTLP routes, and profile encoding behavior. + +Why it matters: + +- Examples become stale when protocol paths or ports change. + +Direction: + +- Read endpoint from environment once. +- Share protocol constants. +- Consider moving pprof-to-OTLP demo conversion into a helper if profiles remain + a supported demo path. + +Priority: P1. + +## Boundary Decisions + +- Backend should not join view or client; fix protocol coupling instead. +- Client transport should be usable without compiler dependencies. +- Server should expose services; apps/adapters should own embedding lifecycle. +- Do not add a production runtime crate in this cleanup. A future shared helper + may exist only for local embedded setup below app/FFI boundaries. +- UI components should render and adapt, not own domain analysis. + +## Acceptance Checks + +- Unknown live-query table names produce errors, not span fallback. +- View strategy tests can run over transport-neutral frames. +- Expiry metadata round-trips from backend to view with row count/range + preserved. +- Any shared CLI/FFI/Linux setup remains local-only and does not become a public + production runtime API. +- FFI remote mode is either implemented or not exposed as supported. diff --git a/docs/architecture/subsystems/seql.md b/docs/architecture/subsystems/seql.md new file mode 100644 index 00000000..dfefa522 --- /dev/null +++ b/docs/architecture/subsystems/seql.md @@ -0,0 +1,207 @@ +# SeQL Subsystem + +Crates covered: `seql-ast`, `seql-parser`, `seql-substrait`, and +`sequins-query`. + +## Intended Purpose + +The SeQL subsystem should have clear layers: + +- `seql-ast`: pure syntax and semantic query model. +- `seql-parser`: text-to-AST parsing only. +- `seql-substrait`: AST-to-Substrait/DataFusion planning. +- `sequins-query`: either a deliberate compatibility facade or removed in favor + of direct dependencies on the purpose crates. + +Intended public contracts: + +- Parser callers should use `seql-parser` for text parsing and parse errors. +- AST callers should use `seql-ast` for syntax and semantic query structures. +- Compiler callers should use `seql-substrait` for supported plan compilation + entrypoints. +- Retrieval/client callers should use `sequins-flight` or client/view crates + for Flight frames and result reduction, not language crates. + +## Current Weaknesses + +### Duplicated Signal Metadata + +Signal names, singular aliases, table names, time columns, join keys, and +correlation edges are duplicated across AST, parser, compiler, and backend code. + +Evidence: + +- `seql-ast/src/ast.rs` defines `Signal` and `Signal::join_key`. +- `seql-ast/src/correlation.rs` owns separate correlation rules. +- `seql-parser/src/stages.rs` has hardcoded plural/singular signal parsing and + error text. +- `seql-substrait/src/compiler.rs` has separate signal-to-name, signal-to-table, + join-key, and time-column mappings. + +Why it matters: + +- Adding a signal requires coordinated edits in multiple crates. +- Query names and physical table names can drift. +- Unsupported or unknown names can silently route to the wrong signal. + +Direction: + +- Move signal metadata into the shared catalog described in the roadmap. +- Parser, AST helpers, compiler, and backend should all delegate to that catalog. + +Priority: P1. + +### Parser Pulls Runtime Types for Clock Access + +`seql-parser` depends on `sequins-types` mostly to access `NowTime` / +`SystemNowTime` for relative time parsing. + +Why it matters: + +- A text parser inherits a broad domain/runtime dependency. +- `today` and `yesterday` parsing is nondeterministic unless callers can inject a + clock. + +Direction: + +- Add parser options with an explicit `now_ns` or `Timestamp`. +- Keep the default parser convenience API, but make the deterministic API the + lower-level primitive. +- Remove the `sequins-types` dependency from parser after migration. + +Priority: P1. + +### Parser Performs Product Policy Desugaring + +`parse_id_lookup` turns `signal(id)` into a query with a 24-hour window and +`Limit(1)`. + +Why it matters: + +- Syntax parsing owns product policy. +- The default time window is hidden from callers and hard to evolve. + +Direction: + +- Parse ID lookup as an explicit AST form or normalize it in a separate semantic + pass. +- Make the default window a named policy owned by query semantics, not the + grammar. + +Priority: P2. + +### `seql-ast` Owns Result/UI Schema Concepts + +`seql-ast/src/schema.rs` contains `ResponseShape`, `ColumnDef`, `DataType`, and +`infer_shape`. + +Why it matters: + +- A pure AST crate carries response and rendering hints. +- Query result metadata becomes mixed with syntax types. + +Direction: + +- Move response metadata into a query protocol or result metadata module. +- Keep `seql-ast` focused on query syntax and semantic query structure. + +Priority: P2. + +### `seql-substrait` Mixes Compiler and Client Reducer + +`seql-substrait` exports compiler APIs and a Flight reducer. Its dependency +surface includes DataFusion/Substrait, Flight, async, CBOR, base64, and row +materialization helpers. + +Why it matters: + +- Compiler consumers inherit client-side stream reduction and serialization + dependencies. +- Transport behavior is coupled to planning behavior. + +Direction: + +- Keep `seql-substrait` focused on AST-to-plan compilation. +- Move reducer and Arrow-to-JSON conversion to `sequins-flight`, + `sequins-view`, or a small response adapter crate. + +Priority: P1. + +### Compiler Public API Leaks DataFusion Internals + +`seql-substrait` publicly re-exports stage translators such as `apply_filter`, +`apply_project`, `ast_expr_to_df_expr`, and `schema_context`. + +Why it matters: + +- Internal planning steps become semver surface. +- Callers can depend on partial compiler internals that may need to change + together. + +Direction: + +- Publicly expose `compile`, `compile_ast`, and deliberately supported helper + APIs only. +- Move stage translators to `pub(crate)` or behind test/support features. + +Priority: P1. + +### AST Semantics Exceed Compiler Support + +Examples observed: + +- `UniqueStage.field` is ignored and whole-row distinct is applied. +- `Patterns` appears as a no-op in compiler stage handling. +- `Heatmap` and `Sample` are parseable but rejected later. +- Some aggregate modes are represented more richly in AST than in plan output. + +Why it matters: + +- Callers cannot know whether a parsed AST is executable. +- Unsupported semantics fail late or degrade silently. + +Direction: + +- Add a semantic validation/capability pass before planning. +- Return structured unsupported-stage errors before plan generation. + +Priority: P1. + +### `sequins-query` Is a Halfway Facade + +`sequins-query/src/lib.rs` re-exports `seql-*` crates, but the crate still +contains local parser, schema, AST, correlation, compiler, frame, and reducer +files. + +Why it matters: + +- Contributors can edit files that are no longer the active implementation. +- The crate depends on parser, DataFusion, Arrow, Flight, protobuf, async, and + metadata dependencies even when consumers only need one layer. + +Direction: + +- Choose one of two end states: + - keep `sequins-query` as a thin compatibility facade and delete stale local + implementations; or + - make it the real owner again and remove the split `seql-*` crates. +- Prefer the facade path because the split crates model clearer ownership. + +Priority: P1. + +## Boundary Decisions + +- Keep parser separate from AST. +- Keep compiler separate from execution backend. +- Split reducer/client frame handling out of compiler. +- Treat `sequins-query` as temporary compatibility unless a concrete product + reason requires a unified query crate. + +## Acceptance Checks + +- Adding a new signal requires editing the catalog and tests, not parser, + compiler, backend, server, and view by hand. +- `seql-parser` has a deterministic parse API that does not depend on + wall-clock access. +- Unsupported AST features fail in validation before Substrait generation. +- `sequins-query` has no stale duplicate implementation files. diff --git a/example/src/profiler.rs b/example/src/profiler.rs index 27794fcc..c2a2983f 100644 --- a/example/src/profiler.rs +++ b/example/src/profiler.rs @@ -209,13 +209,29 @@ fn convert_report_to_otlp(report: &pprof::Report) -> ExportProfilesServiceReques } } +/// OTLP/HTTP endpoint for profiles. Honors `OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT` +/// (a full URL), else derives the host from `OTEL_EXPORTER_OTLP_ENDPOINT` (swapping the +/// gRPC 4317 for the HTTP 4318 profiles path), else a local daemon. +fn profiles_endpoint() -> String { + if let Ok(url) = std::env::var("OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT") { + return url; + } + if let Ok(grpc) = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT") { + // e.g. http://192.168.65.74:4317 -> http://192.168.65.74:4318/v1development/profiles + if let Some(host) = grpc.rsplit_once(':').map(|(h, _)| h) { + return format!("{host}:4318/v1development/profiles"); + } + } + "http://localhost:4318/v1development/profiles".to_string() +} + async fn export_report(report: &pprof::Report) { let request = convert_report_to_otlp(report); let bytes = request.encode_to_vec(); let client = reqwest::Client::new(); match client - .post("http://localhost:4318/v1development/profiles") + .post(profiles_endpoint()) .header("Content-Type", "application/x-protobuf") .body(bytes) .send() diff --git a/example/src/telemetry.rs b/example/src/telemetry.rs index 61f3086a..0c9e26f3 100644 --- a/example/src/telemetry.rs +++ b/example/src/telemetry.rs @@ -4,10 +4,17 @@ use opentelemetry_sdk::{runtime, trace::TracerProvider, Resource}; use std::time::Duration; use tracing_subscriber::prelude::*; +/// OTLP/gRPC endpoint for traces, logs, and metrics. Honors the standard +/// `OTEL_EXPORTER_OTLP_ENDPOINT` env var, defaulting to a local daemon. +pub fn otlp_grpc_endpoint() -> String { + std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT") + .unwrap_or_else(|_| "http://localhost:4317".to_string()) +} + pub fn init_logs() -> opentelemetry_sdk::logs::LoggerProvider { let exporter = opentelemetry_otlp::new_exporter() .tonic() - .with_endpoint("http://localhost:4317"); + .with_endpoint(otlp_grpc_endpoint()); let logger_provider = opentelemetry_otlp::new_pipeline() .logging() @@ -37,7 +44,7 @@ pub fn init_logs() -> opentelemetry_sdk::logs::LoggerProvider { pub fn init_tracer() -> TracerProvider { let exporter = opentelemetry_otlp::new_exporter() .tonic() - .with_endpoint("http://localhost:4317"); + .with_endpoint(otlp_grpc_endpoint()); opentelemetry_otlp::new_pipeline() .tracing() @@ -52,7 +59,7 @@ pub fn init_tracer() -> TracerProvider { pub fn init_metrics() -> opentelemetry_sdk::metrics::SdkMeterProvider { let exporter = opentelemetry_otlp::new_exporter() .tonic() - .with_endpoint("http://localhost:4317"); + .with_endpoint(otlp_grpc_endpoint()); opentelemetry_otlp::new_pipeline() .metrics(runtime::Tokio) diff --git a/scripts/codex-assistant.sh b/scripts/codex-assistant.sh new file mode 100755 index 00000000..92214b66 --- /dev/null +++ b/scripts/codex-assistant.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# +# Launch OpenAI Codex CLI pointed at the Sequins assistant's **Responses API** +# endpoint (`/v1/responses`). +# +# Codex speaks the Responses API, so — unlike the Chat Completions path — it +# receives the assistant's server-executed tool activity as typed output items. +# This is the client to use to check the `/v1/responses` surface end-to-end. +# +# Usage: +# scripts/codex-assistant.sh "how many spans are there in the last hour?" +# scripts/codex-assistant.sh # opens the interactive TUI +# +# Environment overrides: +# RESPONSES_URL Base URL (default http://127.0.0.1:8082/v1; Codex POSTs /responses under it) +# MODEL_ID Model id to use (default: first advertised by /v1/models) +# ASSISTANT_BEARER Bearer token sent to the endpoint (default "local"). Keyless +# daemons ignore it; must match a --api-key if the daemon is keyed. +set -euo pipefail + +RESPONSES_URL="${RESPONSES_URL:-http://127.0.0.1:8082/v1}" +PROVIDER_ID="sequins" +ASSISTANT_BEARER="${ASSISTANT_BEARER:-local}" + +# --- 1. Codex installed? ------------------------------------------------------ +if ! command -v codex >/dev/null 2>&1; then + cat <<'EOF' >&2 +codex not found. Install it, then re-run: + npm i -g @openai/codex # or: brew install codex +Docs: https://developers.openai.com/codex/cli +EOF + exit 1 +fi + +# --- 2. Endpoint reachable? --------------------------------------------------- +echo "Checking assistant at ${RESPONSES_URL}/models ..." >&2 +if ! models_json="$(curl -fsS -H "Authorization: Bearer ${ASSISTANT_BEARER}" "${RESPONSES_URL}/models" 2>/dev/null)"; then + cat <&2 +Could not reach the assistant at ${RESPONSES_URL}. + +Start the Sequins Pro daemon (auto-enables the assistant when OPENAI_API_KEY is set): + + cd ../sequins-pro + export OPENAI_API_KEY=sk-... OPENAI_MODEL=gpt-4o-mini + cargo run -p sequins-pro-daemon --bin sequins-daemon -- start \\ + --config sequins-storage.yaml --assistant-addr 0.0.0.0:8082 +EOF + exit 1 +fi + +# --- 3. Resolve a model id ---------------------------------------------------- +if [[ -z "${MODEL_ID:-}" ]]; then + if command -v jq >/dev/null 2>&1; then + MODEL_ID="$(printf '%s' "$models_json" | jq -r '.data[0].id // empty')" + else + MODEL_ID="$(printf '%s' "$models_json" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)" + fi +fi +if [[ -z "${MODEL_ID:-}" ]]; then + echo "The assistant advertises no models (/v1/models is empty). Configure a server-side model" >&2 + echo "(e.g. set OPENAI_API_KEY on the daemon) so Codex has one to select." >&2 + exit 1 +fi +echo "Using model: ${MODEL_ID} via ${PROVIDER_ID} (wire_api=responses)" >&2 + +# --- 4. Isolated Codex config pointing at our Responses endpoint --------------- +# A private CODEX_HOME so we never touch the user's ~/.codex config. The key is +# read from an env var (Codex requires one for a custom provider); keyless daemons +# ignore it. +CODEX_HOME="$(mktemp -d)" +export CODEX_HOME +trap 'rm -rf "$CODEX_HOME"' EXIT +export SEQUINS_ASSISTANT_KEY="$ASSISTANT_BEARER" + +cat > "${CODEX_HOME}/config.toml" <&2 + +# With a prompt → non-interactive `codex exec`; without → interactive TUI. +if [[ "$#" -gt 0 ]]; then + exec codex exec --skip-git-repo-check -s read-only "$@" +else + exec codex --skip-git-repo-check -s read-only +fi diff --git a/scripts/opencode-assistant.sh b/scripts/opencode-assistant.sh new file mode 100755 index 00000000..a9a0516e --- /dev/null +++ b/scripts/opencode-assistant.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# +# Launch OpenCode pointed at the Sequins assistant as its model provider. +# +# The Sequins Pro daemon exposes an OpenAI-compatible endpoint (/v1) whose model +# is a tool-injecting agent over your telemetry. Connecting OpenCode to it means +# OpenCode's own tools AND the assistant's in-server data tools are both available +# to the model — the "proxy" mode. Ask it a question about your data and watch it +# call run_sql / column_profile / run_seql server-side. +# +# Usage: +# scripts/opencode-assistant.sh [extra opencode args...] +# +# Environment overrides: +# ASSISTANT_URL Base URL of the assistant (default http://127.0.0.1:8082/v1) +# MODEL_ID Model id to use (default: first advertised by /v1/models) +# ASSISTANT_BEARER Bearer token sent to the endpoint (default "local"). Keyless +# daemons ignore it; if the daemon was started with --api-key, +# this must match one of those keys. +set -euo pipefail + +ASSISTANT_URL="${ASSISTANT_URL:-http://127.0.0.1:8082/v1}" +PROVIDER_ID="sequins" +ASSISTANT_BEARER="${ASSISTANT_BEARER:-local}" + +# --- 1. OpenCode installed? --------------------------------------------------- +if ! command -v opencode >/dev/null 2>&1; then + cat <<'EOF' >&2 +opencode not found. Install it, then re-run this script: + curl -fsSL https://opencode.ai/install | bash # or: npm i -g opencode-ai +Docs: https://opencode.ai/docs/ +EOF + exit 1 +fi + +# --- 2. Endpoint reachable? --------------------------------------------------- +echo "Checking assistant at ${ASSISTANT_URL}/models ..." >&2 +if ! models_json="$(curl -fsS -H "Authorization: Bearer ${ASSISTANT_BEARER}" "${ASSISTANT_URL}/models" 2>/dev/null)"; then + cat <&2 +Could not reach the assistant at ${ASSISTANT_URL}. + +Start the Sequins Pro daemon with the assistant enabled (it auto-enables when +OPENAI_API_KEY is set — the daemon is meant to be the only process in its container): + + cd ../sequins-pro + export OPENAI_API_KEY=sk-... # your provider key (or a dummy for a local model) + # Optional: target a local OpenAI-compatible model instead of api.openai.com + # export OPENAI_BASE_URL=http://localhost:11434/v1 + # export OPENAI_MODEL=llama3.1 + cargo run -p sequins-pro-daemon --bin sequins-daemon -- start \\ + --config sequins-storage.yaml --assistant-addr 0.0.0.0:8082 +EOF + exit 1 +fi + +# --- 3. Resolve a model id ---------------------------------------------------- +# Prefer an explicit MODEL_ID; otherwise take the first model /v1/models advertises. +if [[ -z "${MODEL_ID:-}" ]]; then + if command -v jq >/dev/null 2>&1; then + MODEL_ID="$(printf '%s' "$models_json" | jq -r '.data[0].id // empty')" + else + # Minimal fallback parse of the first "id":"..." without jq. + MODEL_ID="$(printf '%s' "$models_json" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)" + fi +fi + +if [[ -z "${MODEL_ID:-}" ]]; then + cat <&2 +The assistant is running but advertises no models (/v1/models is empty), so OpenCode +has nothing to select. Configure a server-side model — the simplest way is to set +OPENAI_API_KEY (and optionally OPENAI_BASE_URL / OPENAI_MODEL) on the daemon and restart. +EOF + exit 1 +fi + +echo "Using model: ${PROVIDER_ID}/${MODEL_ID}" >&2 + +# --- 4. Generate an OpenCode config and launch -------------------------------- +# OpenCode reads opencode.json from the working directory; use a scratch dir so we +# don't touch your project. Pass through any extra args (e.g. a prompt, --model). +workdir="$(mktemp -d)" +trap 'rm -rf "$workdir"' EXIT +cat > "${workdir}/opencode.json" <&2 +cd "$workdir" +exec opencode "$@" From 12745326fd11fc3e2e81ac0b5ed8daa8ea1cf6be Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 21 Jul 2026 17:36:13 +0800 Subject: [PATCH 04/10] feat(assistant): data-exploration + dashboard-authoring tools, chart-role plumbing, SeQL null fix Assistant tool layer (crates/sequins-assistant): - Discovery tools: overview, list_attributes (promoted cols + _overflow_attrs map keys), attribute_values, list_metrics. - Dashboard authoring server tools over a new optional DashboardApi handle (builder, so downstream Tools::new stays valid): list/get/create/rename dashboards, add_chart, update_chart, arrange_dashboard (move/resize/reorder with weights + heights). Positional addressing. - Grounding teaches the explore -> build -> arrange workflow and non-null checks. - DRY/YAGNI cleanup: shared wire module, base_completion_request/message_for_role, PersistTurn build/finish; drop unused temperature/with_max_tool_turns/backend. - gpt-5.6: escalate reasoning_effort (none/drop) only when the provider demands it. SeQL (crates/seql-substrait): compile `field == null` / `!= null` as IS NULL / IS NOT NULL, so the common idiom no longer silently drops every row. FFI (crates/sequins-ffi): CSchemaFrame carries per-column semantic roles so renderers can tell dimensions from measures; conversation delete; wire the local dashboard store into the assistant tools. Metadata (crates/sequins-metadata): drop the never-released legacy free-grid dashboard migration; delete_conversation. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Sequins/Views/Visualization/VizData.swift | 63 -- crates/seql-substrait/src/compiler.rs | 15 + crates/sequins-assistant/src/config.rs | 4 - crates/sequins-assistant/src/lib.rs | 1 + crates/sequins-assistant/src/model.rs | 152 +++- crates/sequins-assistant/src/responses.rs | 188 ++-- crates/sequins-assistant/src/serve.rs | 96 +- crates/sequins-assistant/src/tools/ops.rs | 840 +++++++++++++++++- .../sequins-assistant/src/tools/registry.rs | 83 +- crates/sequins-assistant/src/wire.rs | 112 +++ crates/sequins-ffi/include/sequins.h | 16 + crates/sequins-ffi/src/assistant.rs | 6 +- crates/sequins-ffi/src/dashboard.rs | 53 +- crates/sequins-ffi/src/types/frames.rs | 37 + crates/sequins-metadata/src/lib.rs | 4 +- crates/sequins-metadata/src/store.rs | 63 +- crates/sequins-metadata/src/types.rs | 65 +- 17 files changed, 1396 insertions(+), 402 deletions(-) delete mode 100644 apps/macos/Sequins/Views/Visualization/VizData.swift create mode 100644 crates/sequins-assistant/src/wire.rs diff --git a/apps/macos/Sequins/Views/Visualization/VizData.swift b/apps/macos/Sequins/Views/Visualization/VizData.swift deleted file mode 100644 index 963cf8d4..00000000 --- a/apps/macos/Sequins/Views/Visualization/VizData.swift +++ /dev/null @@ -1,63 +0,0 @@ -import Foundation - -/// Small helpers for mapping loosely-typed SeQL/SQL result rows (`[[Any?]]`) into the -/// numeric/category values the shared visualization charts consume. -enum VizData { - /// Best-effort numeric coercion for a single cell. - static func numeric(_ value: Any?) -> Double? { - guard let value else { return nil } - switch value { - case let n as NSNumber: return n.doubleValue - case let d as Double: return d - case let i as Int: return Double(i) - case let u as UInt64: return Double(u) - case let i as Int64: return Double(i) - case let date as Date: return date.timeIntervalSince1970 - case let s as String: return Double(s) - default: return nil - } - } - - /// Display string for a single cell. - static func string(_ value: Any?) -> String { - guard let value else { return "" } - switch value { - case let s as String: return s - case let n as NSNumber: return n.stringValue - case let b as Bool: return b ? "true" : "false" - case let d as Date: return d.formatted(date: .abbreviated, time: .standard) - default: return String(describing: value) - } - } - - /// The indices/names of numeric "value" columns — every column after the first for - /// which at least one row holds a numeric value. - static func valueColumns(columns: [String], rows: [[Any?]]) -> [(index: Int, name: String)] { - guard columns.count > 1 else { return [] } - return (1.. Double? { - for cell in row { - if let v = numeric(cell) { return v } - } - return nil - } - - /// (category, value) pairs from the first (category) column and the first numeric - /// value column — used by bar and pie charts. - static func categoryValues(columns: [String], rows: [[Any?]]) -> [(category: String, value: Double)] { - guard !columns.isEmpty else { return [] } - let valueIdx = valueColumns(columns: columns, rows: rows).first?.index ?? (columns.count > 1 ? 1 : 0) - return rows.compactMap { row in - guard !row.isEmpty else { return nil } - let category = string(row.first ?? nil) - guard valueIdx < row.count, let value = numeric(row[valueIdx]) else { return nil } - return (category, value) - } - } -} diff --git a/crates/seql-substrait/src/compiler.rs b/crates/seql-substrait/src/compiler.rs index 9563e0df..4aa5cd77 100644 --- a/crates/seql-substrait/src/compiler.rs +++ b/crates/seql-substrait/src/compiler.rs @@ -1181,6 +1181,21 @@ fn predicate_to_expr( Ok(inner_expr.not()) } Predicate::Compare(cmp) => { + // `field == null` / `field != null` is a natural idiom, but SQL's + // three-valued logic makes `col = NULL` and `col <> NULL` evaluate to NULL + // for every row — silently dropping the entire result. Interpret an + // equality/inequality against a `null` literal as `IS NULL` / `IS NOT NULL` + // so the query does what's meant. + let null_on_right = matches!(cmp.right, AstExpr::Literal(Literal::Null)); + let null_on_left = matches!(cmp.left, AstExpr::Literal(Literal::Null)); + if (null_on_right || null_on_left) && matches!(cmp.op, CompareOp::Eq | CompareOp::Neq) { + let field_side = if null_on_right { &cmp.left } else { &cmp.right }; + let expr = ast_expr_to_df_expr(field_side, schema, signal, ctx)?; + return Ok(match cmp.op { + CompareOp::Eq => expr.is_null(), + _ => expr.is_not_null(), + }); + } let left = ast_expr_to_df_expr(&cmp.left, schema, signal, ctx)?; let right = ast_expr_to_df_expr(&cmp.right, schema, signal, ctx)?; Ok(match cmp.op { diff --git a/crates/sequins-assistant/src/config.rs b/crates/sequins-assistant/src/config.rs index 8fb47f58..8012b9d4 100644 --- a/crates/sequins-assistant/src/config.rs +++ b/crates/sequins-assistant/src/config.rs @@ -87,9 +87,6 @@ pub struct ModelConfig { /// Environment variable holding the API key (default `SEQUINS_ASSISTANT_API_KEY`). #[serde(default)] pub api_key_env: Option, - /// Optional sampling temperature (reserved for future per-model defaults). - #[serde(default)] - pub temperature: Option, } /// Errors building the model registry. @@ -232,7 +229,6 @@ mod tests { base_url: None, model: "gpt-4o".into(), api_key_env: Some("SEQUINS_ASSISTANT_KEY_DEFINITELY_UNSET".into()), - temperature: None, }], grounding: None, auto_from_env: false, diff --git a/crates/sequins-assistant/src/lib.rs b/crates/sequins-assistant/src/lib.rs index d1581d3c..41f75871 100644 --- a/crates/sequins-assistant/src/lib.rs +++ b/crates/sequins-assistant/src/lib.rs @@ -14,6 +14,7 @@ pub mod model; pub mod responses; pub mod serve; pub mod tools; +mod wire; pub use config::{ build_backing_model, build_registry, AssistantConfig, BackingModel, ModelConfig, ModelRegistry, diff --git a/crates/sequins-assistant/src/model.rs b/crates/sequins-assistant/src/model.rs index cc9e4aae..69cfa0f5 100644 --- a/crates/sequins-assistant/src/model.rs +++ b/crates/sequins-assistant/src/model.rs @@ -53,12 +53,6 @@ impl SequinsAssistantModel { self } - /// Override the in-process tool-call round cap. - pub fn with_max_tool_turns(mut self, turns: usize) -> Self { - self.max_tool_turns = turns.max(1); - self - } - /// Inject our grounding into the preamble and our tool defs into the request, /// without dropping anything the caller supplied. fn inject(&self, request: &mut CompletionRequest) { @@ -95,7 +89,7 @@ impl SequinsAssistantModel { self.inject(&mut request); for _ in 0..self.max_tool_turns { - let response = self.backing.completion(request.clone()).await?; + let response = self.complete(&mut request).await?; let mut our_calls: Vec = Vec::new(); let mut has_foreign = false; @@ -143,7 +137,8 @@ impl SequinsAssistantModel { .map(AssistantContent::ToolCall) .collect(); request.chat_history.push(Message::Assistant { - id: response_id(&response), + // Providers don't reliably supply an assistant message id here. + id: None, content: OneOrMany::many(assistant_content) .expect("our_calls is non-empty in this branch"), }); @@ -173,7 +168,7 @@ impl SequinsAssistantModel { // Exhausted the tool-turn budget: one final call with no tools, forcing text. request.tools.clear(); - let response = self.backing.completion(request).await?; + let response = self.complete(&mut request).await?; for content in response.choice.iter() { if let AssistantContent::Text(t) = content { if !t.text.is_empty() { @@ -184,6 +179,31 @@ impl SequinsAssistantModel { Ok(response) } + /// Run one backing completion, reconciling `reasoning_effort` with the model when the + /// provider rejects the request over it, then persisting the fix on `request` so later + /// tool turns keep it. + /// + /// `reasoning_effort` is model-specific and can't be sent unconditionally: newer + /// reasoning models (e.g. `gpt-5.6-*`) *require* `"none"` for function tools, some + /// models reject the value `"none"`, and non-reasoning models (e.g. `gpt-4o`) reject + /// the parameter entirely. So on a reasoning-effort error we escalate the adjustment — + /// try `"none"`, then drop the parameter — until it's accepted (at most twice). + async fn complete( + &self, + request: &mut CompletionRequest, + ) -> Result, CompletionError> { + let mut adjustments = 0; + loop { + match self.backing.completion(request.clone()).await { + Err(e) if mentions_reasoning_effort(&e) && adjustments < 2 => { + adjustments += 1; + adjust_reasoning_effort(request); + } + other => return other, + } + } + } + /// Run the agentic loop as a live [`AgentEvent`] stream — used by the Responses /// endpoint to surface server-side tool activity to the client as it happens. pub fn run_events( @@ -292,6 +312,65 @@ impl GetTokenUsage for MiddlewareStreamResponse { } } +/// Whether a completion error is the provider complaining about `reasoning_effort` (an +/// unsupported value, an unrecognized parameter, or the gpt-5.6-style "function tools … +/// set reasoning_effort to 'none'"). +fn mentions_reasoning_effort(error: &CompletionError) -> bool { + error + .to_string() + .to_lowercase() + .contains("reasoning_effort") +} + +/// The request's current `reasoning_effort` value, if any. +fn reasoning_effort_value(request: &CompletionRequest) -> Option { + request + .additional_params + .as_ref() + .and_then(|params| params.get("reasoning_effort")) + .and_then(|v| v.as_str()) + .map(str::to_string) +} + +/// Escalate the reasoning-effort adjustment one step toward acceptance: with no effort +/// (or a rejected non-`"none"` effort), try `"none"`; if even `"none"` was rejected, drop +/// the parameter so the model uses its default. +fn adjust_reasoning_effort(request: &mut CompletionRequest) { + match reasoning_effort_value(request).as_deref() { + Some("none") => remove_reasoning_effort(request), + _ => set_reasoning_effort_none(request), + } +} + +/// Set `reasoning_effort: "none"` in the request's flattened `additional_params`. +fn set_reasoning_effort_none(request: &mut CompletionRequest) { + let mut params = request + .additional_params + .take() + .unwrap_or_else(|| serde_json::json!({})); + if let Some(obj) = params.as_object_mut() { + obj.insert("reasoning_effort".to_string(), serde_json::json!("none")); + } else { + params = serde_json::json!({ "reasoning_effort": "none" }); + } + request.additional_params = Some(params); +} + +/// Remove `reasoning_effort` from `additional_params`, clearing the map entirely when it +/// becomes empty. +fn remove_reasoning_effort(request: &mut CompletionRequest) { + if let Some(obj) = request + .additional_params + .as_mut() + .and_then(|params| params.as_object_mut()) + { + obj.remove("reasoning_effort"); + if obj.is_empty() { + request.additional_params = None; + } + } +} + /// Return a copy of `response` with any of *our* tool calls removed from its choice, /// so a caller only ever sees text and its own tool calls. fn strip_our_tool_calls(response: CompletionResponse) -> CompletionResponse { @@ -313,11 +392,6 @@ fn strip_our_tool_calls(response: CompletionResponse) -> CompletionRespons } } -/// Best-effort assistant message id (providers don't always supply one). -fn response_id(_response: &CompletionResponse) -> Option { - None -} - /// The default SeQL system grounding. Includes a compact SeQL syntax cheatsheet with /// worked examples so a backing model unfamiliar with this DSL writes valid queries on /// the first try instead of looping on `validate_seql`. The daemon can override it with @@ -357,19 +431,43 @@ Every query begins with a signal and a mandatory time scope, then optional `|` s - Avg latency over time: `spans last 1h | group by { ts() bin 1m as bucket } { avg(duration_ns) as avg_ns }` - Error logs per minute: `logs last 1h | where severity_number >= 17 | group by { ts() bin 1m as bucket } { count() as errors }` -## Workflow - -Ground names with `list_tables` / `describe_schema` only if unsure. Write ONE SeQL query -using the rules above. If `validate_seql` fails, read `error.message`/`offset`, FIX the -query per the syntax above, and validate AT MOST once or twice more — do not loop. - -Client tools for showing results (call with the final SeQL `query`, a short `title`, and -an optional `chart_type` like `line`/`bar`/`stat`/`table`): -- `render_visualization` — show a chart INLINE in the chat. Use for a one-off answer. -- `add_to_dashboard` — SAVE a chart to a dashboard given a `dashboard` NAME (created if it - doesn't exist). Use when the user asks to add a chart to, or build/populate, a dashboard. - -The app re-runs the query to render it."# +## Exploring the data + +Prefer discovery tools over guessing — observability data is dominated by attributes: +- `overview` — row counts + time spans per table; skip empty tables. Call first when unsure. +- `list_attributes(table)` — the real attribute keys present (promoted + custom). Call this + before filtering on `attr.`; don't guess key names. +- `attribute_values(table, key)` — the actual values of a key (e.g. which `http.route`s exist). +- `list_metrics` — metric names/types/units; `describe_schema(table)` for columns. +- To keep rows where a field is present, write `where http_route != null` (it means IS NOT + NULL). Bare promoted attrs (e.g. `http_route`, `http_status_code`) are real columns. + +## Presenting results + +- `render_visualization(query, title, chart_type?)` — show a chart INLINE in the chat for a + one-off answer. `chart_type` is optional (`line`/`bar`/`stat`/`table`/`heatmap`/…); omit to + auto-select. The app re-runs the query to render it. + +## Dashboards + +Read before you edit, and address charts by position: +- `list_dashboards` / `get_dashboard(dashboard)` — see dashboards and each chart's `[row,col]` + position, title, weight, type, and query. Always `get_dashboard` before editing. +- `create_dashboard(title)` then `add_chart(dashboard, query, title, chart_type?, row?, + position?, weight?)` — build/populate. Omit `row` to add a new full-width row; give `row` + (and `position`/`weight`) to place charts side by side. +- `update_chart(dashboard, row, column, …)` — edit a chart's title/query/type. +- `arrange_dashboard(dashboard, rows:[{height?, panels:[{from_row, from_column, weight?}]}])` — + move/resize/reorder in one call. Charts are referenced by current position; set `weight` for + column-width ratios and `height` for rows. Charts you omit are removed. +- Deleting a dashboard or removing a chart requires the user's approval — propose it and let + them confirm; do not assume. + +## Query workflow + +Ground names with the discovery tools only if unsure. Write ONE SeQL query using the rules +above. If `validate_seql` fails, read `error.message`/`offset`, FIX the query, and validate AT +MOST once or twice more — do not loop."# .to_string() } diff --git a/crates/sequins-assistant/src/responses.rs b/crates/sequins-assistant/src/responses.rs index cd375246..1de7af24 100644 --- a/crates/sequins-assistant/src/responses.rs +++ b/crates/sequins-assistant/src/responses.rs @@ -14,10 +14,8 @@ use std::convert::Infallible; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; use axum::extract::State; -use axum::http::StatusCode; use axum::response::sse::{Event, Sse}; use axum::response::{IntoResponse, Response}; use axum::routing::post; @@ -35,6 +33,7 @@ use serde::Deserialize; use serde_json::json; use crate::model::{AgentEvent, SequinsAssistantModel}; +use crate::wire::{self, bad_request, model_not_found, new_id, parse_arguments, unix_secs}; /// Router state: the model registry plus the optional app-state store that /// persists conversations (when `store` is set on the request). @@ -70,7 +69,6 @@ where let response_id = new_id("resp"); let store = state.store.clone(); - let do_store = req.store.unwrap_or(true) && store.is_some(); // Resolve the conversation this turn belongs to (existing) — a new one is // created at persist time if none is referenced. @@ -89,13 +87,7 @@ where } let model_id = req.model.clone(); - let persist = do_store.then(|| PersistTurn { - store: store.clone().unwrap(), - conversation_id: conversation_id.clone(), - title: derive_title(&req), - input_items: input_conversation_items(&req), - response_id: response_id.clone(), - }); + let persist = PersistTurn::build(&store, &req, &conversation_id, &response_id); if req.stream { stream_response( @@ -109,10 +101,7 @@ where .into_response() } else { let events: Vec = model.run_events(completion_req).collect().await; - let conversation_id = match persist { - Some(p) => p.run(&events).await.or(conversation_id), - None => conversation_id, - }; + let conversation_id = PersistTurn::finish(persist, &events, conversation_id).await; Json(build_response_object( &model_id, &response_id, @@ -133,6 +122,40 @@ struct PersistTurn { } impl PersistTurn { + /// Build the persist descriptor for a turn, or `None` when persistence is off + /// (no store configured, or `store: false` on the request). + fn build( + store: &Option>, + req: &ResponsesRequest, + conversation_id: &Option, + response_id: &str, + ) -> Option { + let store = store.clone()?; + if !req.store.unwrap_or(true) { + return None; + } + Some(PersistTurn { + store, + conversation_id: conversation_id.clone(), + title: derive_title(req), + input_items: input_conversation_items(req), + response_id: response_id.to_string(), + }) + } + + /// Persist (if enabled) and resolve the continuation conversation id, falling back + /// to `fallback` when persistence is off or fails. + async fn finish( + persist: Option, + events: &[AgentEvent], + fallback: Option, + ) -> Option { + match persist { + Some(p) => p.run(events).await.or(fallback), + None => fallback, + } + } + /// Persist the turn; returns the (possibly newly created) conversation id. async fn run(self, events: &[AgentEvent]) -> Option { let output_items: Vec = events @@ -183,14 +206,10 @@ fn prepend_history(request: &mut CompletionRequest, conv: &sequins_metadata::Con if item.item_type != "message" { continue; } - let text = item.text.clone().unwrap_or_default(); - match item.role.as_str() { - "assistant" => prior.push(Message::assistant(text)), - "system" | "developer" => prior.push(Message::System { content: text }), - _ => prior.push(Message::User { - content: OneOrMany::one(UserContent::Text(Text::new(text))), - }), - } + prior.push(message_for_role( + &item.role, + item.text.clone().unwrap_or_default(), + )); } if prior.is_empty() { return; @@ -320,16 +339,7 @@ fn build_completion_request(req: &ResponsesRequest) -> Result { - let text = content.text(); - match role.as_str() { - "assistant" => history.push(Message::assistant(text)), - "system" | "developer" => { - history.push(Message::System { content: text }) - } - _ => history.push(Message::User { - content: OneOrMany::one(UserContent::Text(Text::new(text))), - }), - } + history.push(message_for_role(role, content.text())); } InputItem::FunctionCall { call_id, @@ -367,18 +377,28 @@ fn build_completion_request(req: &ResponsesRequest) -> Result Message { + match role { + "assistant" => Message::assistant(text), + "system" | "developer" => Message::System { content: text }, + _ => Message::User { + content: OneOrMany::one(UserContent::Text(Text::new(text))), + }, + } } /// Stream the agentic loop as Responses-API SSE events, surfacing every server tool @@ -434,10 +454,7 @@ where // Persist the completed turn; the (possibly new) conversation id goes on the // terminal event so the client can continue via `previous_response_id`. - let final_conversation = match persist { - Some(p) => p.run(&collected).await.or(conversation_id), - None => conversation_id, - }; + let final_conversation = PersistTurn::finish(persist, &collected, conversation_id).await; if let Some(msg) = failed { let resp = response_object(&model_id, &response_id, final_conversation.as_deref(), "failed", &output, Some(&msg)); @@ -553,10 +570,6 @@ fn sse(event: &str, data: serde_json::Value) -> Result { Ok(Event::default().event(event).data(data.to_string())) } -fn parse_arguments(arguments: &str) -> serde_json::Value { - serde_json::from_str(arguments).unwrap_or(serde_json::Value::Null) -} - // --------------------------------------------------------------------------- // Assistant façade — one AgentEvent-style stream for Local and Remote, used by // the FFI so Swift has a single interface regardless of backend. @@ -662,14 +675,7 @@ fn local_chat( prepend_history(&mut completion_req, &conv); } } - let do_store = req.store.unwrap_or(true) && store.is_some(); - let persist = do_store.then(|| PersistTurn { - store: store.clone().unwrap(), - conversation_id: conversation_id.clone(), - title: derive_title(&req), - input_items: input_conversation_items(&req), - response_id: response_id.clone(), - }); + let persist = PersistTurn::build(&store, &req, &conversation_id, &response_id); let events = model.run_events(completion_req); futures::pin_mut!(events); @@ -690,10 +696,7 @@ fn local_chat( } collected.push(event); } - let final_conversation = match persist { - Some(p) => p.run(&collected).await.or(conversation_id), - None => conversation_id, - }; + let final_conversation = PersistTurn::finish(persist, &collected, conversation_id).await; yield ChatEvent::Done { response_id, conversation_id: final_conversation }; } } @@ -833,6 +836,16 @@ struct ResponsesRequest { /// Explicit conversation id to append to. #[serde(default)] conversation: Option, + /// Reasoning controls (Responses API `reasoning: { effort }`). The effort is applied + /// as `reasoning_effort` on the backing Chat Completions request. + #[serde(default)] + reasoning: Option, +} + +#[derive(Debug, Deserialize)] +struct ReasoningConfig { + #[serde(default)] + effort: Option, } #[derive(Debug, Deserialize)] @@ -910,53 +923,14 @@ struct ResponsesTool { impl ResponsesTool { fn as_definition(&self) -> Option { let name = self.name.clone()?; - Some(ToolDefinition { + Some(wire::tool_definition( name, - description: self.description.clone().unwrap_or_default(), - parameters: self.parameters.clone().unwrap_or_else(|| json!({})), - }) + self.description.clone(), + self.parameters.clone(), + )) } } -// --------------------------------------------------------------------------- -// Errors + small helpers -// --------------------------------------------------------------------------- - -fn model_not_found(model: &str) -> (StatusCode, Json) { - ( - StatusCode::NOT_FOUND, - Json(json!({ "error": { - "message": format!("The model '{model}' does not exist or is not configured."), - "type": "invalid_request_error", - "code": "model_not_found", - }})), - ) -} - -fn bad_request(message: &str) -> (StatusCode, Json) { - ( - StatusCode::BAD_REQUEST, - Json(json!({ "error": { "message": message, "type": "invalid_request_error" } })), - ) -} - -fn unix_secs() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0) -} - -fn new_id(prefix: &str) -> String { - format!( - "{prefix}_{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - ) -} - #[cfg(test)] mod stream_relay_tests { use super::*; diff --git a/crates/sequins-assistant/src/serve.rs b/crates/sequins-assistant/src/serve.rs index 2de75651..8cab0cca 100644 --- a/crates/sequins-assistant/src/serve.rs +++ b/crates/sequins-assistant/src/serve.rs @@ -11,7 +11,6 @@ //! side of the remote wire — our own app and any OpenAI client hit the same route. use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; use axum::extract::State; use axum::http::StatusCode; @@ -29,6 +28,8 @@ use rig::OneOrMany; use serde::{Deserialize, Serialize}; use serde_json::json; +use crate::wire::{self, bad_request, model_not_found, unix_secs}; + /// Build the OpenAI-compatible router over a named registry of models. /// /// The registry order is preserved in `GET /v1/models`. An empty registry serves @@ -176,34 +177,24 @@ fn build_completion_request(req: &ChatRequest) -> Result = req .tools .iter() - .map(|t| ToolDefinition { - name: t.function.name.clone(), - description: t.function.description.clone().unwrap_or_default(), - parameters: t.function.parameters.clone().unwrap_or_else(|| json!({})), + .map(|t| { + wire::tool_definition( + t.function.name.clone(), + t.function.description.clone(), + t.function.parameters.clone(), + ) }) .collect(); let preamble = (!system_texts.is_empty()).then(|| system_texts.join("\n\n")); - Ok(CompletionRequest { - // No model override: `req.model` is our public registry id, not the backing - // provider's model name. The backing model supplies its own name (the - // middleware also clears this defensively). - model: None, - preamble, - chat_history, - documents: Vec::new(), - tools, - temperature: req.temperature, - // Drop the client's max_tokens: it sizes output for our *public* model id, - // but we route to a different backing model with its own limit. Forwarding - // an oversized value 400s ("max_tokens is too large for this model"); letting - // the backing model use its default is correct for a remapping proxy. - max_tokens: None, - tool_choice: None, - additional_params: None, - output_schema: None, - }) + // `base_completion_request` drops `max_tokens` (it sizes output for our *public* + // model id, but we route to a different backing model with its own limit — a + // forwarded oversized value 400s) and clears the model override. We forward only + // the client's temperature. + let mut request = wire::base_completion_request(preamble, chat_history, tools); + request.temperature = req.temperature; + Ok(request) } /// Split a completion response's choice into concatenated text and tool calls. @@ -387,7 +378,7 @@ struct ChatToolCallFunction { impl ChatToolCallFunction { fn parsed_arguments(&self) -> serde_json::Value { - serde_json::from_str(&self.arguments).unwrap_or(serde_json::Value::Null) + wire::parse_arguments(&self.arguments) } } @@ -406,29 +397,12 @@ struct ChatToolFunction { } // --------------------------------------------------------------------------- -// Errors (OpenAI-shaped) +// Errors + small helpers // --------------------------------------------------------------------------- -fn model_not_found(model: &str) -> (StatusCode, Json) { - error_body( - StatusCode::NOT_FOUND, - format!("The model '{model}' does not exist or is not configured."), - "invalid_request_error", - Some("model_not_found"), - ) -} - -fn bad_request(message: &str) -> (StatusCode, Json) { - error_body( - StatusCode::BAD_REQUEST, - message.to_string(), - "invalid_request_error", - None, - ) -} - +/// `502 api_error` for an upstream/backing-model failure. fn upstream_error(message: &str) -> (StatusCode, Json) { - error_body( + wire::error_body( StatusCode::BAD_GATEWAY, message.to_string(), "api_error", @@ -436,35 +410,7 @@ fn upstream_error(message: &str) -> (StatusCode, Json) { ) } -fn error_body( - status: StatusCode, - message: String, - kind: &str, - code: Option<&str>, -) -> (StatusCode, Json) { - ( - status, - Json(json!({ "error": { "message": message, "type": kind, "code": code } })), - ) -} - -// --------------------------------------------------------------------------- -// Small helpers -// --------------------------------------------------------------------------- - -fn unix_secs() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0) -} - +/// OpenAI chat-completion id (`chatcmpl-…`, hyphen-separated by convention). fn chat_id() -> String { - format!( - "chatcmpl-{}", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - ) + format!("chatcmpl-{}", wire::unix_nanos()) } diff --git a/crates/sequins-assistant/src/tools/ops.rs b/crates/sequins-assistant/src/tools/ops.rs index d7adcff2..b82250d7 100644 --- a/crates/sequins-assistant/src/tools/ops.rs +++ b/crates/sequins-assistant/src/tools/ops.rs @@ -18,14 +18,18 @@ use std::sync::Arc; +use arrow::array::Array; use arrow::record_batch::RecordBatch; use datafusion::execution::context::SQLOptions; use datafusion::prelude::SessionContext; use futures::StreamExt; use schemars::JsonSchema; -use sequins_arrow_schema::SignalType; +use sequins_arrow_schema::{PromotedAttribute, SignalType}; use sequins_datafusion_backend::{hot_signal_tables, hot_signal_type_for_table, DataFusionBackend}; use sequins_flight::{decode_metadata, ipc_to_batch, SeqlMetadata}; +use sequins_metadata::{ + Dashboard, DashboardApi, DashboardRow, RowPanel, SavedVisualization, DEFAULT_ROW_HEIGHT, +}; use sequins_traits::QueryApi; use serde::{Deserialize, Serialize}; @@ -50,6 +54,14 @@ pub enum OpError { DataFusion(#[from] datafusion::error::DataFusionError), #[error("arrow error: {0}")] Arrow(#[from] arrow::error::ArrowError), + #[error("dashboard editing is not available for this connection")] + DashboardsUnavailable, + #[error("no dashboard matching '{key}' — use list_dashboards to see ids/titles")] + UnknownDashboard { key: String }, + #[error("no chart at [row {row}, column {column}] — use get_dashboard to see indices")] + UnknownPanel { row: usize, column: usize }, + #[error("dashboard store error: {0}")] + Metadata(#[from] sequins_metadata::MetadataError), } // --------------------------------------------------------------------------- @@ -130,6 +142,150 @@ pub struct RunSeqlArgs { pub sample_rows: Option, } +/// Arguments for `overview` (none). +#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] +pub struct OverviewArgs {} + +/// Arguments for `list_metrics` (none). +#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ListMetricsArgs {} + +/// Which kind of attribute keys to enumerate. +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum AttributeKind { + /// Signal-level attributes (`attr.` — promoted columns + overflow map). + #[default] + Attr, + /// Resource attributes (from the `resources` table). + Resource, + /// Instrumentation-scope attributes (from the `scopes` table). + Scope, +} + +/// Arguments for `list_attributes`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ListAttributesArgs { + /// Signal table whose attributes to enumerate (e.g. `spans`, `logs`). Ignored for + /// `kind=resource`/`scope`, which read the `resources`/`scopes` tables. + pub table: String, + /// Which attribute namespace to list (default `attr`). + #[serde(default)] + pub kind: AttributeKind, + /// How many overflow/resource/scope keys to list (default 40, max 100). + #[serde(default)] + pub limit: Option, +} + +/// Arguments for `attribute_values`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct AttributeValuesArgs { + /// Signal table containing the attribute. + pub table: String, + /// Attribute key — an OTLP key like `http.route` or its promoted column name. + pub key: String, + /// How many most-frequent values to list (default 10, max 100). + #[serde(default)] + pub top_k: Option, +} + +/// Arguments for `list_dashboards` (none). +#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ListDashboardsArgs {} + +/// Arguments for `get_dashboard`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct GetDashboardArgs { + /// Dashboard id or (case-insensitive) title. + pub dashboard: String, +} + +/// Arguments for `create_dashboard`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct CreateDashboardArgs { + /// Title for the new dashboard. + pub title: String, +} + +/// Arguments for `rename_dashboard`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct RenameDashboardArgs { + /// Dashboard id or title to rename. + pub dashboard: String, + /// New title. + pub title: String, +} + +/// Arguments for `add_chart`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct AddChartArgs { + /// Target dashboard id or title (must already exist — use create_dashboard first). + pub dashboard: String, + /// SeQL query whose result the chart renders. + pub query: String, + /// Short chart title. + pub title: String, + /// Optional chart type (`line`/`bar`/`stat`/`table`/`heatmap`/…). Omit to auto-select. + #[serde(default)] + pub chart_type: Option, + /// Existing row index to add into; omit to append the chart as a new full-width row. + #[serde(default)] + pub row: Option, + /// Column position within `row` (default: end of the row). + #[serde(default)] + pub position: Option, + /// Relative width weight within the row (default 1.0). + #[serde(default)] + pub weight: Option, +} + +/// Arguments for `update_chart`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct UpdateChartArgs { + /// Dashboard id or title. + pub dashboard: String, + /// Row index of the chart (from get_dashboard). + pub row: usize, + /// Column index of the chart within the row. + pub column: usize, + #[serde(default)] + pub title: Option, + #[serde(default)] + pub query: Option, + #[serde(default)] + pub chart_type: Option, +} + +/// Arguments for `arrange_dashboard` — a declarative new layout referencing existing +/// charts by their current position, setting per-panel widths and per-row heights. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ArrangeDashboardArgs { + /// Dashboard id or title. + pub dashboard: String, + /// The desired rows, top to bottom. + pub rows: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ArrangeRow { + /// Row height in points (default 280). + #[serde(default)] + pub height: Option, + /// The charts in this row, left to right, referenced by current position. + pub panels: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ArrangePanel { + /// Current row index of the chart to place here. + pub from_row: usize, + /// Current column index of the chart to place here. + pub from_column: usize, + /// New relative width weight (default: keep the chart's current weight). + #[serde(default)] + pub weight: Option, +} + // --------------------------------------------------------------------------- // Tools — holds the backend; every op is a method returning rendered text. // --------------------------------------------------------------------------- @@ -138,17 +294,31 @@ pub struct RunSeqlArgs { #[derive(Clone)] pub struct Tools { backend: Arc, + /// Dashboard read/write, when the host wires it in (the FFI local assistant and the + /// Pro daemon both have a `DashboardApi`). Absent ⇒ dashboard tools report they're + /// unavailable rather than failing opaquely. + dashboards: Option>, } impl Tools { /// Build the tool layer over an existing backend. pub fn new(backend: Arc) -> Self { - Self { backend } + Self { + backend, + dashboards: None, + } + } + + /// Attach a dashboard store so the assistant can read and edit dashboards. + pub fn with_dashboards(mut self, dashboards: Arc) -> Self { + self.dashboards = Some(dashboards); + self } - /// The backend these tools operate over. - pub fn backend(&self) -> &Arc { - &self.backend + fn dashboard_api(&self) -> Result<&Arc, OpError> { + self.dashboards + .as_ref() + .ok_or(OpError::DashboardsUnavailable) } async fn ctx(&self) -> Result { @@ -382,6 +552,413 @@ impl Tools { Ok(out) } + /// A compact per-signal-table overview: row counts and (where a time column + /// exists) the time span, flagging empty tables so the model avoids them. + pub async fn overview(&self, _args: OverviewArgs) -> Result { + let ctx = self.ctx().await?; + let mut out = String::from("Signal data overview:\n"); + for (name, signal) in hot_signal_tables() { + let t = quote_ident(name); + let (n, span) = match signal.time_column() { + Some(tc) => { + let sql = format!( + "SELECT count(*) AS n, min(CAST({c} AS BIGINT)) AS lo, max(CAST({c} AS BIGINT)) AS hi FROM {t}", + c = quote_ident(tc), + ); + match self.query_readonly(&ctx, &sql, 1).await { + Ok(b) => { + let n = scalar_i64(&b, "n").unwrap_or(0); + let span = match (scalar_i64(&b, "lo"), scalar_i64(&b, "hi")) { + (Some(lo), Some(hi)) if hi >= lo => Some(format!( + ", spanning {}", + human_duration_ns((hi - lo) as u64) + )), + _ => None, + }; + (n, span) + } + Err(_) => (0, None), + } + } + None => { + let sql = format!("SELECT count(*) AS n FROM {t}"); + let n = self + .query_readonly(&ctx, &sql, 1) + .await + .ok() + .and_then(|b| scalar_i64(&b, "n")) + .unwrap_or(0); + (n, None) + } + }; + if n == 0 { + out.push_str(&format!("- {name}: empty\n")); + } else { + out.push_str(&format!("- {name}: {n} rows{}\n", span.unwrap_or_default())); + } + } + out.push_str("\nUse describe_schema/list_attributes/list_metrics to go deeper."); + Ok(out) + } + + /// List the available metrics with their type, unit, and series cardinality. + pub async fn list_metrics(&self, _args: ListMetricsArgs) -> Result { + let ctx = self.ctx().await?; + let sql = "SELECT m.name AS metric, m.metric_type AS type, m.unit AS unit, \ + count(DISTINCT d.series_id) AS series, count(d.series_id) AS datapoints \ + FROM metrics m LEFT JOIN datapoints d ON m.metric_id = d.metric_id \ + GROUP BY m.name, m.metric_type, m.unit ORDER BY m.name"; + let batches = self.query_readonly(&ctx, sql, MAX_ROWS).await?; + Ok(format!( + "Metrics (name, type, unit, series cardinality, datapoints):\n{}\n\ + Chart a metric by name via a `datapoints` SeQL query; use metric_labels for its label keys.", + render_batches(&batches)? + )) + } + + /// Enumerate the attribute keys present in a table: promoted (populated) columns + /// plus the most common overflow-map keys; or resource/scope attribute keys. + pub async fn list_attributes(&self, args: ListAttributesArgs) -> Result { + let ctx = self.ctx().await?; + let limit = args.limit.unwrap_or(40).clamp(1, MAX_ROWS); + match args.kind { + AttributeKind::Resource | AttributeKind::Scope => { + let (table, label) = match args.kind { + AttributeKind::Resource => ("resources", "resource"), + _ => ("scopes", "scope"), + }; + let keys = self.json_attribute_keys(&ctx, table, limit).await?; + if keys.is_empty() { + return Ok(format!( + "No {label} attributes found (table `{table}` empty)." + )); + } + Ok(format!( + "{label} attribute keys (from `{table}.attributes`):\n{}", + keys.iter() + .map(|k| format!("- {k}")) + .collect::>() + .join("\n") + )) + } + AttributeKind::Attr => { + validate_table(&args.table)?; + let cols = self.table_columns(&ctx, &args.table).await?; + let mut out = format!("Attributes on `{}`:\n", args.table); + + // Promoted attributes that actually have data (one scan, all counts). + let present: Vec<&PromotedAttribute> = sequins_arrow_schema::SEMCONV_ATTRIBUTES + .iter() + .filter(|a| cols.iter().any(|c| c == a.column_name)) + .collect(); + if !present.is_empty() { + let selects: Vec = present + .iter() + .map(|a| { + format!( + "count({}) AS {}", + quote_ident(a.column_name), + quote_ident(a.column_name) + ) + }) + .collect(); + let sql = format!( + "SELECT {} FROM {}", + selects.join(", "), + quote_ident(&args.table) + ); + out.push_str("promoted (typed columns, with non-null counts):\n"); + match self.query_readonly(&ctx, &sql, 1).await { + Ok(b) => { + let mut any = false; + for a in &present { + if let Some(n) = scalar_i64(&b, a.column_name) { + if n > 0 { + any = true; + out.push_str(&format!( + " - {} (col `{}`, {:?}): {n}\n", + a.key, a.column_name, a.value_type + )); + } + } + } + if !any { + out.push_str(" (none populated)\n"); + } + } + Err(e) => out.push_str(&format!(" (counts unavailable: {e})\n")), + } + } + + // Overflow (non-promoted) keys from the CBOR map column. + out.push_str("\ncustom (overflow) keys by frequency:\n"); + let overflow_sql = format!( + "SELECT k AS key, count(*) AS n FROM (SELECT unnest(map_keys(\"_overflow_attrs\")) AS k \ + FROM {t} WHERE \"_overflow_attrs\" IS NOT NULL) GROUP BY k ORDER BY n DESC LIMIT {limit}", + t = quote_ident(&args.table), + ); + match self.query_readonly(&ctx, &overflow_sql, limit).await { + Ok(b) if b.iter().any(|x| x.num_rows() > 0) => { + out.push_str(&render_batches(&b)?) + } + Ok(_) => out.push_str(" (none)\n"), + Err(_) => out.push_str(" (overflow-key enumeration unavailable)\n"), + } + out.push_str("\nRead a promoted key as a column; a custom key via attr. in SeQL. Use attribute_values to see values."); + Ok(out) + } + } + } + + /// The most frequent values for a given attribute key (promoted column or overflow). + pub async fn attribute_values(&self, args: AttributeValuesArgs) -> Result { + validate_table(&args.table)?; + let ctx = self.ctx().await?; + let top_k = args.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_ROWS); + let cols = self.table_columns(&ctx, &args.table).await?; + let t = quote_ident(&args.table); + + let v = match resolve_promoted_column(&cols, &args.key) { + Some(col) => quote_ident(&col), + None => format!( + "overflow_get_str(\"_overflow_attrs\", '{}')", + args.key.replace('\'', "''") + ), + }; + let sql = format!( + "SELECT {v} AS value, count(*) AS n FROM {t} WHERE {v} IS NOT NULL \ + GROUP BY {v} ORDER BY n DESC LIMIT {top_k}" + ); + let batches = self.query_readonly(&ctx, &sql, top_k).await?; + Ok(format!( + "Top {top_k} values of `{}`.`{}`:\n{}", + args.table, + args.key, + render_batches(&batches)? + )) + } + + /// The column names of a table. + async fn table_columns( + &self, + ctx: &SessionContext, + table: &str, + ) -> Result, OpError> { + let df = ctx.table(table).await?; + Ok(df + .schema() + .as_arrow() + .fields() + .iter() + .map(|f| f.name().to_string()) + .collect()) + } + + /// Distinct attribute keys parsed from a JSON `attributes` string column (resources/scopes). + async fn json_attribute_keys( + &self, + ctx: &SessionContext, + table: &str, + limit: usize, + ) -> Result, OpError> { + let sql = format!( + "SELECT DISTINCT attributes FROM {} WHERE attributes IS NOT NULL LIMIT 500", + quote_ident(table) + ); + let batches = self.query_readonly(ctx, &sql, 500).await?; + let mut keys = std::collections::BTreeSet::new(); + for batch in &batches { + if let Some(arr) = batch + .column(0) + .as_any() + .downcast_ref::() + { + for i in 0..arr.len() { + if arr.is_null(i) { + continue; + } + if let Ok(serde_json::Value::Object(map)) = + serde_json::from_str::(arr.value(i)) + { + for k in map.keys() { + keys.insert(k.clone()); + } + } + } + } + } + Ok(keys.into_iter().take(limit).collect()) + } + + // ---- Dashboard authoring ---------------------------------------------- + + /// Resolve a dashboard by id, then by case-insensitive title. + async fn resolve_dashboard(&self, key: &str) -> Result { + let api = self.dashboard_api()?; + if let Some(d) = api.get_dashboard(key).await? { + return Ok(d); + } + api.list_dashboards() + .await? + .into_iter() + .find(|d| d.title.eq_ignore_ascii_case(key)) + .ok_or_else(|| OpError::UnknownDashboard { + key: key.to_string(), + }) + } + + /// List saved dashboards with their ids, titles, and panel counts. + pub async fn list_dashboards(&self, _args: ListDashboardsArgs) -> Result { + let list = self.dashboard_api()?.list_dashboards().await?; + if list.is_empty() { + return Ok("No dashboards yet. Use create_dashboard to make one.".to_string()); + } + let mut out = String::from("Dashboards:\n"); + for d in &list { + out.push_str(&format!( + "- \"{}\" (id={}, {} rows, {} charts)\n", + d.title, + d.id, + d.rows.len(), + d.panel_count() + )); + } + Ok(out) + } + + /// Show a dashboard's full structure — rows, heights, and each chart's position, + /// title, weight, type, and query. Read this before editing to get chart indices. + pub async fn get_dashboard(&self, args: GetDashboardArgs) -> Result { + let d = self.resolve_dashboard(&args.dashboard).await?; + Ok(render_dashboard(&d)) + } + + /// Create a new empty dashboard. + pub async fn create_dashboard(&self, args: CreateDashboardArgs) -> Result { + let api = self.dashboard_api()?; + let d = api + .save_dashboard(Dashboard { + id: String::new(), + title: args.title, + created_at_ns: 0, + updated_at_ns: 0, + rows: Vec::new(), + }) + .await?; + Ok(format!("Created dashboard \"{}\" (id={}).", d.title, d.id)) + } + + /// Rename a dashboard. + pub async fn rename_dashboard(&self, args: RenameDashboardArgs) -> Result { + let api = self.dashboard_api()?; + let mut d = self.resolve_dashboard(&args.dashboard).await?; + d.title = args.title; + let d = api.save_dashboard(d).await?; + Ok(format!( + "Renamed dashboard to \"{}\" (id={}).", + d.title, d.id + )) + } + + /// Add a chart to a dashboard — either into an existing row (at a position/weight) or + /// as a new full-width row. + pub async fn add_chart(&self, args: AddChartArgs) -> Result { + let api = self.dashboard_api()?; + let mut d = self.resolve_dashboard(&args.dashboard).await?; + let title = args.title.clone(); + let panel = RowPanel { + visualization: SavedVisualization { + seql: args.query, + title: args.title, + shape: args.chart_type, + }, + weight: args.weight.unwrap_or(1.0), + }; + match args.row { + Some(r) if r < d.rows.len() => { + let row = &mut d.rows[r]; + let pos = args + .position + .unwrap_or(row.panels.len()) + .min(row.panels.len()); + row.panels.insert(pos, panel); + } + _ => d.rows.push(DashboardRow { + height: DEFAULT_ROW_HEIGHT, + panels: vec![panel], + }), + } + let d = api.save_dashboard(d).await?; + Ok(format!( + "Added chart \"{title}\".\n{}", + render_dashboard(&d) + )) + } + + /// Edit an existing chart's title, query, and/or type by position. + pub async fn update_chart(&self, args: UpdateChartArgs) -> Result { + let api = self.dashboard_api()?; + let mut d = self.resolve_dashboard(&args.dashboard).await?; + let panel = d + .rows + .get_mut(args.row) + .and_then(|row| row.panels.get_mut(args.column)) + .ok_or(OpError::UnknownPanel { + row: args.row, + column: args.column, + })?; + if let Some(t) = args.title { + panel.visualization.title = t; + } + if let Some(q) = args.query { + panel.visualization.seql = q; + } + if let Some(ct) = args.chart_type { + panel.visualization.shape = Some(ct); + } + let d = api.save_dashboard(d).await?; + Ok(format!( + "Updated chart [{},{}].\n{}", + args.row, + args.column, + render_dashboard(&d) + )) + } + + /// Rearrange a dashboard declaratively: place existing charts into new rows/columns + /// with new widths (weights) and row heights. Charts are referenced by their current + /// `(from_row, from_column)`; any chart not listed is dropped. + pub async fn arrange_dashboard(&self, args: ArrangeDashboardArgs) -> Result { + let api = self.dashboard_api()?; + let mut d = self.resolve_dashboard(&args.dashboard).await?; + let mut new_rows = Vec::with_capacity(args.rows.len()); + for spec in &args.rows { + let mut panels = Vec::with_capacity(spec.panels.len()); + for ps in &spec.panels { + let src = d + .rows + .get(ps.from_row) + .and_then(|row| row.panels.get(ps.from_column)) + .ok_or(OpError::UnknownPanel { + row: ps.from_row, + column: ps.from_column, + })?; + let mut panel = src.clone(); + if let Some(w) = ps.weight { + panel.weight = w; + } + panels.push(panel); + } + new_rows.push(DashboardRow { + height: spec.height.unwrap_or(DEFAULT_ROW_HEIGHT), + panels, + }); + } + d.rows = new_rows; + let d = api.save_dashboard(d).await?; + Ok(format!("Rearranged dashboard.\n{}", render_dashboard(&d))) + } + /// Run a read-only SQL statement and collect up to `limit` rows. async fn query_readonly( &self, @@ -440,6 +1017,95 @@ fn quote_ident(ident: &str) -> String { format!("\"{}\"", ident.replace('"', "\"\"")) } +/// Extract a single `Int64`/`UInt64` scalar (e.g. a `count(*)`/`CAST(.. AS BIGINT)`) +/// from the first row of `batches` by column name. +fn scalar_i64(batches: &[RecordBatch], col: &str) -> Option { + use arrow::array::{Int64Array, UInt64Array}; + let batch = batches.iter().find(|b| b.num_rows() > 0)?; + let idx = batch.schema().index_of(col).ok()?; + let arr = batch.column(idx); + if let Some(a) = arr.as_any().downcast_ref::() { + return (!a.is_null(0)).then(|| a.value(0)); + } + if let Some(a) = arr.as_any().downcast_ref::() { + return (!a.is_null(0)).then(|| a.value(0) as i64); + } + None +} + +/// Format a nanosecond duration compactly (e.g. `2h 15m`, `450ms`). +fn human_duration_ns(ns: u64) -> String { + let secs = ns / 1_000_000_000; + if secs == 0 { + return format!("{}ms", ns / 1_000_000); + } + let (d, h, m, s) = ( + secs / 86400, + (secs % 86400) / 3600, + (secs % 3600) / 60, + secs % 60, + ); + let mut parts = Vec::new(); + if d > 0 { + parts.push(format!("{d}d")); + } + if h > 0 { + parts.push(format!("{h}h")); + } + if m > 0 && d == 0 { + parts.push(format!("{m}m")); + } + if s > 0 && d == 0 && h == 0 { + parts.push(format!("{s}s")); + } + if parts.is_empty() { + parts.push(format!("{secs}s")); + } + parts.join(" ") +} + +/// Render a dashboard's structure for the model: rows with heights, and each chart's +/// `[row,col]` position, title, weight, type, and query — the addresses edit tools use. +fn render_dashboard(d: &Dashboard) -> String { + let mut out = format!( + "Dashboard \"{}\" (id={}, {} rows, {} charts):\n", + d.title, + d.id, + d.rows.len(), + d.panel_count() + ); + if d.rows.is_empty() { + out.push_str(" (empty — add_chart to populate)\n"); + } + for (r, row) in d.rows.iter().enumerate() { + out.push_str(&format!(" row {r} (height={}):\n", row.height)); + for (c, p) in row.panels.iter().enumerate() { + out.push_str(&format!( + " [{r},{c}] \"{}\" weight={} type={} :: {}\n", + p.visualization.title, + p.weight, + p.visualization.shape.as_deref().unwrap_or("auto"), + p.visualization.seql + )); + } + } + out +} + +/// Resolve an attribute key to a promoted column name present in `cols`, accepting the +/// OTLP dotted key, the underscore column name, or a raw existing column. +fn resolve_promoted_column(cols: &[String], key: &str) -> Option { + let underscore = key.replace('.', "_"); + for a in sequins_arrow_schema::SEMCONV_ATTRIBUTES { + if (a.key == key || a.column_name == key || a.column_name == underscore) + && cols.iter().any(|c| c == a.column_name) + { + return Some(a.column_name.to_string()); + } + } + cols.iter().find(|c| **c == underscore).cloned() +} + /// Render record batches as an LLM-legible ASCII table. fn render_batches(batches: &[RecordBatch]) -> Result { if batches.iter().all(|b| b.num_rows() == 0) { @@ -644,6 +1310,170 @@ mod tests { assert!(bad.contains("\"ok\":false")); } + #[tokio::test] + async fn overview_lists_tables_with_counts() { + let (tools, _t) = seeded_tools(5).await; + let out = tools.overview(OverviewArgs {}).await.unwrap(); + assert!(out.contains("spans"), "overview mentions spans: {out}"); + // Empty tables should be flagged so the model avoids them. + assert!(out.contains("empty"), "some tables are empty: {out}"); + } + + #[tokio::test] + async fn list_attributes_runs_on_spans() { + let (tools, _t) = seeded_tools(5).await; + let out = tools + .list_attributes(ListAttributesArgs { + table: "spans".into(), + kind: AttributeKind::Attr, + limit: None, + }) + .await + .unwrap(); + assert!(out.contains("Attributes on `spans`"), "{out}"); + } + + #[tokio::test] + async fn attribute_values_runs() { + let (tools, _t) = seeded_tools(5).await; + // `name` isn't an attribute, but the query path (promoted/overflow) must execute. + let out = tools + .attribute_values(AttributeValuesArgs { + table: "spans".into(), + key: "service.name".into(), + top_k: Some(5), + }) + .await + .unwrap(); + assert!(out.contains("values of"), "{out}"); + } + + #[tokio::test] + async fn seql_not_null_filter_keeps_rows() { + let (tools, _t) = seeded_tools(6).await; + // `name` is always populated, so `!= null` (meaning IS NOT NULL) must keep all 6 + // rows — not the SQL footgun `name <> NULL`, which drops every row. + let out = tools + .run_seql(RunSeqlArgs { + query: "spans last 1h | where name != null | group by {} { count() as n }".into(), + sample_rows: Some(1), + }) + .await + .unwrap(); + // The SQL footgun `name <> NULL` would drop every row → count 0. IS NOT NULL keeps + // them, so the count must be non-zero. + assert!( + !out.contains("| 0 "), + "!= null dropped all rows (should mean IS NOT NULL): {out}" + ); + } + + #[tokio::test] + async fn list_metrics_runs() { + let (storage, _t) = TestStorageBuilder::new().build().await; + storage + .ingest_metrics(make_test_otlp_metrics(1, 2, 4)) + .await + .unwrap(); + let tools = Tools::new(Arc::new(DataFusionBackend::new(Arc::new(storage)))); + let out = tools.list_metrics(ListMetricsArgs {}).await.unwrap(); + assert!(out.contains("Metrics"), "{out}"); + } + + #[tokio::test] + async fn dashboard_crud_via_tools() { + let (storage, _t) = TestStorageBuilder::new().build().await; + let storage = Arc::new(storage); + let backend = Arc::new(DataFusionBackend::new(storage.clone())); + let tools = Tools::new(backend).with_dashboards(storage.clone() as Arc); + + let out = tools + .create_dashboard(CreateDashboardArgs { + title: "Errors".into(), + }) + .await + .unwrap(); + assert!(out.contains("Created dashboard \"Errors\""), "{out}"); + + tools + .add_chart(AddChartArgs { + dashboard: "Errors".into(), + query: "spans last 1h | group by { ts() bin 1m as bucket } { count() as n }".into(), + title: "Spans/min".into(), + chart_type: Some("line".into()), + row: None, + position: None, + weight: None, + }) + .await + .unwrap(); + let after = tools + .add_chart(AddChartArgs { + dashboard: "Errors".into(), + query: "spans last 1h | group by {} { count() as total }".into(), + title: "Total".into(), + chart_type: Some("stat".into()), + row: Some(0), + position: None, + weight: Some(2.0), + }) + .await + .unwrap(); + // Second chart added into row 0 → two side-by-side panels. + assert!( + after.contains("[0,0]") && after.contains("[0,1]"), + "{after}" + ); + + let upd = tools + .update_chart(UpdateChartArgs { + dashboard: "Errors".into(), + row: 0, + column: 0, + title: Some("Spans per minute".into()), + query: None, + chart_type: None, + }) + .await + .unwrap(); + assert!(upd.contains("Spans per minute"), "{upd}"); + + // Rearrange into two rows, resizing one. + let arr = tools + .arrange_dashboard(ArrangeDashboardArgs { + dashboard: "Errors".into(), + rows: vec![ + ArrangeRow { + height: None, + panels: vec![ArrangePanel { + from_row: 0, + from_column: 1, + weight: None, + }], + }, + ArrangeRow { + height: Some(200.0), + panels: vec![ArrangePanel { + from_row: 0, + from_column: 0, + weight: None, + }], + }, + ], + }) + .await + .unwrap(); + assert!(arr.contains("row 0") && arr.contains("row 1"), "{arr}"); + + // Without a dashboard handle the tools report unavailability. + let no_dash = Tools::new(Arc::new(DataFusionBackend::new(storage.clone()))); + let err = no_dash + .list_dashboards(ListDashboardsArgs {}) + .await + .unwrap_err(); + assert!(matches!(err, OpError::DashboardsUnavailable)); + } + #[tokio::test] async fn run_seql_summarizes_result() { let (tools, _t) = seeded_tools(6).await; diff --git a/crates/sequins-assistant/src/tools/registry.rs b/crates/sequins-assistant/src/tools/registry.rs index 191cf02d..55205456 100644 --- a/crates/sequins-assistant/src/tools/registry.rs +++ b/crates/sequins-assistant/src/tools/registry.rs @@ -14,8 +14,10 @@ use schemars::{schema_for, JsonSchema}; use serde::de::DeserializeOwned; use super::ops::{ - ColumnProfileArgs, DescribeSchemaArgs, ExplainArgs, ListTablesArgs, RunSeqlArgs, RunSqlArgs, - SampleArgs, TimeRangeArgs, ValidateSeqlArgs, + AddChartArgs, ArrangeDashboardArgs, AttributeValuesArgs, ColumnProfileArgs, + CreateDashboardArgs, DescribeSchemaArgs, ExplainArgs, GetDashboardArgs, ListAttributesArgs, + ListDashboardsArgs, ListMetricsArgs, ListTablesArgs, OverviewArgs, RenameDashboardArgs, + RunSeqlArgs, RunSqlArgs, SampleArgs, TimeRangeArgs, UpdateChartArgs, ValidateSeqlArgs, }; use super::{OpError, Tools}; @@ -32,8 +34,12 @@ pub struct ToolSpec { /// The names of every tool this assistant executes in-process. Used by the /// middleware model to tell *our* tool calls from a caller's own tools. pub const TOOL_NAMES: &[&str] = &[ + "overview", "list_tables", "describe_schema", + "list_attributes", + "attribute_values", + "list_metrics", "column_profile", "time_range", "sample", @@ -41,6 +47,13 @@ pub const TOOL_NAMES: &[&str] = &[ "run_sql", "validate_seql", "run_seql", + "list_dashboards", + "get_dashboard", + "create_dashboard", + "rename_dashboard", + "add_chart", + "update_chart", + "arrange_dashboard", ]; /// Is `name` one of our in-process tools (vs. a caller-provided tool)? @@ -55,6 +68,11 @@ fn schema() -> serde_json::Value { /// Every tool's spec, in a stable order. pub fn specs() -> Vec { vec![ + ToolSpec { + name: "overview", + description: "Orient yourself: per-signal-table row counts and time spans, flagging empty tables. Call this first.", + parameters: schema::(), + }, ToolSpec { name: "list_tables", description: "List the queryable signal tables (spans, logs, datapoints, …) and their time columns.", @@ -65,6 +83,21 @@ pub fn specs() -> Vec { description: "Show a signal table's columns and Arrow types. Call before writing a query.", parameters: schema::(), }, + ToolSpec { + name: "list_attributes", + description: "Enumerate the attribute keys present on a table: promoted (populated) columns plus common overflow-map keys (or resource/scope keys). Observability data is dominated by attributes — use this to discover real keys before filtering on attr..", + parameters: schema::(), + }, + ToolSpec { + name: "attribute_values", + description: "The most-frequent values of a given attribute key (promoted column or overflow key) — e.g. which http.route or service values exist.", + parameters: schema::(), + }, + ToolSpec { + name: "list_metrics", + description: "List available metrics with their type, unit, and series cardinality. Use before charting a metric.", + parameters: schema::(), + }, ToolSpec { name: "column_profile", description: "Profile a column: total/non-null counts, approximate distinct cardinality, min/max, and the most frequent values.", @@ -100,6 +133,41 @@ pub fn specs() -> Vec { description: "Execute a SeQL query and summarize its result: shape, columns, row count, sample rows, and stats. The final answer must be a SeQL query.", parameters: schema::(), }, + ToolSpec { + name: "list_dashboards", + description: "List saved dashboards with ids, titles, and chart counts.", + parameters: schema::(), + }, + ToolSpec { + name: "get_dashboard", + description: "Show a dashboard's full layout — rows/heights and each chart's [row,col] position, title, weight, type, and query. Read this before editing to get chart indices.", + parameters: schema::(), + }, + ToolSpec { + name: "create_dashboard", + description: "Create a new empty dashboard with a title.", + parameters: schema::(), + }, + ToolSpec { + name: "rename_dashboard", + description: "Rename an existing dashboard.", + parameters: schema::(), + }, + ToolSpec { + name: "add_chart", + description: "Add a chart (a SeQL query + title + optional type) to a dashboard, either into an existing row at a position/weight or as a new full-width row.", + parameters: schema::(), + }, + ToolSpec { + name: "update_chart", + description: "Edit an existing chart's title, query, and/or type by its [row,col] position.", + parameters: schema::(), + }, + ToolSpec { + name: "arrange_dashboard", + description: "Rearrange a dashboard: place existing charts into new rows/columns with new widths (weights) and row heights. Charts are referenced by current position; unlisted charts are dropped. Use to move, resize, and reorder in one call.", + parameters: schema::(), + }, ] } @@ -130,8 +198,12 @@ pub async fn invoke(tools: &Tools, name: &str, args: serde_json::Value) -> Resul } let result: Result = match name { + "overview" => tools.overview(parse(args)?).await, "list_tables" => tools.list_tables(parse(args)?).await, "describe_schema" => tools.describe_schema(parse(args)?).await, + "list_attributes" => tools.list_attributes(parse(args)?).await, + "attribute_values" => tools.attribute_values(parse(args)?).await, + "list_metrics" => tools.list_metrics(parse(args)?).await, "column_profile" => tools.column_profile(parse(args)?).await, "time_range" => tools.time_range(parse(args)?).await, "sample" => tools.sample(parse(args)?).await, @@ -139,6 +211,13 @@ pub async fn invoke(tools: &Tools, name: &str, args: serde_json::Value) -> Resul "run_sql" => tools.run_sql(parse(args)?).await, "validate_seql" => tools.validate_seql(parse(args)?).await, "run_seql" => tools.run_seql(parse(args)?).await, + "list_dashboards" => tools.list_dashboards(parse(args)?).await, + "get_dashboard" => tools.get_dashboard(parse(args)?).await, + "create_dashboard" => tools.create_dashboard(parse(args)?).await, + "rename_dashboard" => tools.rename_dashboard(parse(args)?).await, + "add_chart" => tools.add_chart(parse(args)?).await, + "update_chart" => tools.update_chart(parse(args)?).await, + "arrange_dashboard" => tools.arrange_dashboard(parse(args)?).await, other => return Err(format!("unknown tool: {other}")), }; result.map_err(|e| e.to_string()) diff --git a/crates/sequins-assistant/src/wire.rs b/crates/sequins-assistant/src/wire.rs new file mode 100644 index 00000000..718b5bac --- /dev/null +++ b/crates/sequins-assistant/src/wire.rs @@ -0,0 +1,112 @@ +//! Small wire-format helpers shared by the OpenAI-compatible surfaces +//! ([`crate::serve`] chat-completions and [`crate::responses`]): unix timestamps and +//! id generation, tool-argument parsing, tool-definition construction, the +//! OpenAI-shaped error bodies, and the boilerplate for a Rig [`CompletionRequest`]. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use axum::http::StatusCode; +use axum::Json; +use rig::completion::{CompletionRequest, ToolDefinition}; +use rig::message::Message; +use rig::OneOrMany; +use serde_json::json; + +/// Seconds since the Unix epoch (0 if the clock is before the epoch). +pub(crate) fn unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Nanoseconds since the Unix epoch — the entropy behind generated ids. +pub(crate) fn unix_nanos() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) +} + +/// A unique-ish id of the form `{prefix}_{nanos}` (e.g. `resp_1234…`). +pub(crate) fn new_id(prefix: &str) -> String { + format!("{prefix}_{}", unix_nanos()) +} + +/// Parse OpenAI tool-call arguments (a JSON *string*) into a value, defaulting to +/// `null` on malformed input. +pub(crate) fn parse_arguments(arguments: &str) -> serde_json::Value { + serde_json::from_str(arguments).unwrap_or(serde_json::Value::Null) +} + +/// Build a Rig [`ToolDefinition`] from the optional description/parameters shared by +/// the chat and responses tool DTOs (empty description, `{}` schema when omitted). +pub(crate) fn tool_definition( + name: String, + description: Option, + parameters: Option, +) -> ToolDefinition { + ToolDefinition { + name, + description: description.unwrap_or_default(), + parameters: parameters.unwrap_or_else(|| json!({})), + } +} + +/// An OpenAI-shaped error body. +pub(crate) fn error_body( + status: StatusCode, + message: String, + kind: &str, + code: Option<&str>, +) -> (StatusCode, Json) { + ( + status, + Json(json!({ "error": { "message": message, "type": kind, "code": code } })), + ) +} + +/// `404 model_not_found` for an unknown/unconfigured model id. +pub(crate) fn model_not_found(model: &str) -> (StatusCode, Json) { + error_body( + StatusCode::NOT_FOUND, + format!("The model '{model}' does not exist or is not configured."), + "invalid_request_error", + Some("model_not_found"), + ) +} + +/// `400 invalid_request_error` for a malformed request. +pub(crate) fn bad_request(message: &str) -> (StatusCode, Json) { + error_body( + StatusCode::BAD_REQUEST, + message.to_string(), + "invalid_request_error", + None, + ) +} + +/// A [`CompletionRequest`] with the fields both surfaces always set the same way. +/// +/// `model` is `None` (the public registry id is not the backing provider's model +/// name; the middleware supplies its own) and `documents`/`max_tokens`/`tool_choice`/ +/// `additional_params`/`output_schema`/`temperature` are unset. Callers that need a +/// non-default (e.g. chat forwarding `temperature`) override the field afterward. +pub(crate) fn base_completion_request( + preamble: Option, + chat_history: OneOrMany, + tools: Vec, +) -> CompletionRequest { + CompletionRequest { + model: None, + preamble, + chat_history, + documents: Vec::new(), + tools, + temperature: None, + max_tokens: None, + tool_choice: None, + additional_params: None, + output_schema: None, + } +} diff --git a/crates/sequins-ffi/include/sequins.h b/crates/sequins-ffi/include/sequins.h index fe1cf82e..d5331040 100644 --- a/crates/sequins-ffi/include/sequins.h +++ b/crates/sequins-ffi/include/sequins.h @@ -440,6 +440,13 @@ typedef struct CSchemaFrame { * Column names (null-terminated strings) */ char **column_names; + /** + * Per-column semantic role codes (parallel to `column_names`), so renderers can + * tell dimensions (group keys/fields) from measures (aggregations/computed): + * 0=group_key, 1=aggregation, 2=field, 3=computed, 4=navigation, 5=trace_group, + * 6=row_id. + */ + uint32_t *column_roles; /** * Watermark at query start (nanoseconds since epoch) */ @@ -1592,6 +1599,15 @@ bool sequins_dashboard_save(struct CDataSource *data_source, */ bool sequins_dashboard_delete(struct CDataSource *data_source, const char *id, char **error_out); +/** + * Delete a persisted conversation by id (in-memory + durable). Local only; remote + * connections report an error until the daemon exposes conversation deletion. + * + * # Safety + * `data_source`/`id` must be valid; `error_out` is an out-param. + */ +bool sequins_conversation_delete(struct CDataSource *data_source, const char *id, char **error_out); + /** * Create a new local data source with embedded storage * diff --git a/crates/sequins-ffi/src/assistant.rs b/crates/sequins-ffi/src/assistant.rs index 1ee51aca..8c3c329b 100644 --- a/crates/sequins-ffi/src/assistant.rs +++ b/crates/sequins-ffi/src/assistant.rs @@ -153,7 +153,11 @@ pub unsafe extern "C" fn sequins_assistant_new( return std::ptr::null_mut(); } }; - let tools = sequins_assistant::Tools::new(Arc::clone(backend)); + // Give the tool layer the local dashboard store so the assistant can read and + // edit dashboards (`Storage` implements `DashboardApi`). + let dashboards: Arc = storage.clone(); + let tools = + sequins_assistant::Tools::new(Arc::clone(backend)).with_dashboards(dashboards); let model = sequins_assistant::SequinsAssistantModel::new(backing, tools); Assistant::local(model, Some(Arc::clone(storage.app_state()))) } diff --git a/crates/sequins-ffi/src/dashboard.rs b/crates/sequins-ffi/src/dashboard.rs index f2b1cba7..d67b6d81 100644 --- a/crates/sequins-ffi/src/dashboard.rs +++ b/crates/sequins-ffi/src/dashboard.rs @@ -1,5 +1,6 @@ -//! FFI: dashboard persistence (list/get/save/delete), normalized over Local -//! (in-process `Storage`) and Remote (`RemoteClient` REST). JSON in, JSON out. +//! FFI: app-state persistence — dashboards (list/get/save/delete) plus conversation +//! deletion — normalized over Local (in-process `Storage`) and Remote (`RemoteClient` +//! REST). JSON in, JSON out. //! //! Management-style ABI: each fn returns `bool` (success), writes JSON to an //! out-param (caller frees with `sequins_string_free`), and on failure writes an @@ -164,6 +165,49 @@ pub unsafe extern "C" fn sequins_dashboard_delete( } } +/// Delete a persisted conversation by id (in-memory + durable). Local only; remote +/// connections report an error until the daemon exposes conversation deletion. +/// +/// # Safety +/// `data_source`/`id` must be valid; `error_out` is an out-param. +#[no_mangle] +pub unsafe extern "C" fn sequins_conversation_delete( + data_source: *mut CDataSource, + id: *const c_char, + error_out: *mut *mut c_char, +) -> bool { + if data_source.is_null() || id.is_null() { + set_error(error_out, "data source or id is null"); + return false; + } + let id = match CStr::from_ptr(id).to_str() { + Ok(s) => s, + Err(_) => { + set_error(error_out, "id is not valid UTF-8"); + return false; + } + }; + match &*(data_source as *const DataSourceImpl) { + #[cfg(feature = "local")] + DataSourceImpl::Local { storage, .. } => { + match RUNTIME.block_on(storage.app_state().delete_conversation(id)) { + Ok(()) => true, + Err(e) => { + set_error(error_out, &e.to_string()); + false + } + } + } + DataSourceImpl::Remote { .. } => { + set_error( + error_out, + "deleting conversations is not supported on remote connections yet", + ); + false + } + } +} + #[cfg(all(test, feature = "local"))] mod tests { use super::*; @@ -197,8 +241,9 @@ mod tests { // Save. let dashboard = serde_json::json!({ "id": "", "title": "Errors", "created_at_ns": 0, "updated_at_ns": 0, - "panels": [{ "visualization": { "seql": "logs last 1h", "title": "logs", "shape": "table" }, - "layout": { "x": 0, "y": 0, "w": 6, "h": 4 } }] + "rows": [{ "height": 280.0, "panels": [ + { "visualization": { "seql": "logs last 1h", "title": "logs", "shape": "table" }, + "weight": 6.0 } ] }] }); let dashboard_c = CString::new(dashboard.to_string()).unwrap(); let mut out: *mut c_char = std::ptr::null_mut(); diff --git a/crates/sequins-ffi/src/types/frames.rs b/crates/sequins-ffi/src/types/frames.rs index 6ec20420..0c00ab00 100644 --- a/crates/sequins-ffi/src/types/frames.rs +++ b/crates/sequins-ffi/src/types/frames.rs @@ -76,6 +76,11 @@ pub struct CSchemaFrame { pub column_count: c_uint, /// Column names (null-terminated strings) pub column_names: *mut *mut c_char, + /// Per-column semantic role codes (parallel to `column_names`), so renderers can + /// tell dimensions (group keys/fields) from measures (aggregations/computed): + /// 0=group_key, 1=aggregation, 2=field, 3=computed, 4=navigation, 5=trace_group, + /// 6=row_id. + pub column_roles: *mut u32, /// Watermark at query start (nanoseconds since epoch) pub initial_watermark_ns: u64, /// Table name for multi-table responses (null = primary table, non-null = auxiliary table alias) @@ -95,6 +100,15 @@ impl CSchemaFrame { let names_ptr = boxed_names.as_mut_ptr(); std::mem::forget(boxed_names); + let roles: Vec = schema + .columns + .iter() + .map(|c| column_role_code(c.role)) + .collect(); + let mut boxed_roles = roles.into_boxed_slice(); + let roles_ptr = boxed_roles.as_mut_ptr(); + std::mem::forget(boxed_roles); + let table_ptr = table .and_then(|t| CString::new(t).ok()) .map(|s| s.into_raw()) @@ -104,12 +118,28 @@ impl CSchemaFrame { shape: CResponseShape::from(&schema.shape), column_count: count as c_uint, column_names: names_ptr, + column_roles: roles_ptr, initial_watermark_ns: schema.initial_watermark_ns, table: table_ptr, }) } } +/// Stable numeric code for a column's semantic role (kept in sync with the Swift +/// `SeQLColumnRole` enum and the `column_roles` doc on [`CSchemaFrame`]). +fn column_role_code(role: seql_ast::schema::ColumnRole) -> u32 { + use seql_ast::schema::ColumnRole::*; + match role { + GroupKey => 0, + Aggregation => 1, + Field => 2, + Computed => 3, + Navigation => 4, + TraceGroup => 5, + RowId => 6, + } +} + // ── FFI normalization ────────────────────────────────────────────────────────── // ── CDataFrame ──────────────────────────────────────────────────────────────── @@ -392,6 +422,13 @@ pub unsafe extern "C" fn c_schema_frame_free(frame: *mut CSchemaFrame) { frame.column_count as usize, frame.column_count as usize, )); + if !frame.column_roles.is_null() { + drop(Vec::from_raw_parts( + frame.column_roles, + frame.column_count as usize, + frame.column_count as usize, + )); + } if !frame.table.is_null() { drop(CString::from_raw(frame.table)); } diff --git a/crates/sequins-metadata/src/lib.rs b/crates/sequins-metadata/src/lib.rs index b279eaa7..dea089d9 100644 --- a/crates/sequins-metadata/src/lib.rs +++ b/crates/sequins-metadata/src/lib.rs @@ -13,6 +13,6 @@ pub mod types; pub use error::{MetadataError, Result}; pub use store::{AppStateStore, DashboardApi}; pub use types::{ - Conversation, ConversationItem, Dashboard, DashboardRow, Layout, Panel, RowPanel, - SavedVisualization, DEFAULT_ROW_HEIGHT, + Conversation, ConversationItem, Dashboard, DashboardRow, RowPanel, SavedVisualization, + DEFAULT_ROW_HEIGHT, }; diff --git a/crates/sequins-metadata/src/store.rs b/crates/sequins-metadata/src/store.rs index a8d8fe5f..3c53032c 100644 --- a/crates/sequins-metadata/src/store.rs +++ b/crates/sequins-metadata/src/store.rs @@ -91,8 +91,7 @@ impl AppStateStore { let dash_prefix = ObjPath::from(format!("{}/dashboards", self.prefix)); for location in self.list_locations(&dash_prefix).await? { match self.get_json::(&location).await { - Ok(mut dash) => { - dash.migrate_legacy(); + Ok(dash) => { self.dashboards.write().await.insert(dash.id.clone(), dash); } Err(e) => tracing::warn!(%location, error = %e, "skipping unreadable dashboard"), @@ -183,6 +182,17 @@ impl AppStateStore { self.conversations.read().await.values().cloned().collect() } + /// Delete a conversation (in-memory + durable) and drop any response-index entries + /// pointing at it. No-op if absent. + pub async fn delete_conversation(&self, id: &str) -> Result<()> { + self.conversations.write().await.remove(id); + self.response_index.write().await.retain(|_, cid| cid != id); + match self.store.delete(&self.conversation_path(id)).await { + Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), + Err(e) => Err(e.into()), + } + } + // ---- Dashboards -------------------------------------------------------- /// Snapshot all dashboards (for the DataFusion table provider). @@ -193,7 +203,6 @@ impl AppStateStore { /// Create or update a dashboard, stamping `id`/timestamps as needed. Returns /// the stored dashboard (with its id). pub async fn upsert_dashboard(&self, mut dashboard: Dashboard) -> Result { - dashboard.migrate_legacy(); let now = now_ns(); if dashboard.id.is_empty() { dashboard.id = self.next_id("dash"); @@ -232,8 +241,9 @@ impl AppStateStore { } } -/// Read/write dashboards. Implemented by [`AppStateStore`] (local) and, elsewhere, -/// by the remote client so the app has one interface across Local and Remote. +/// Read/write dashboards. Implemented for `Storage` (local, delegating to +/// [`AppStateStore`]'s inherent methods) and for the remote client over HTTP, so the +/// app has one interface across Local and Remote. #[async_trait] pub trait DashboardApi: Send + Sync { async fn list_dashboards(&self) -> Result>; @@ -242,22 +252,6 @@ pub trait DashboardApi: Send + Sync { async fn delete_dashboard(&self, id: &str) -> Result<()>; } -#[async_trait] -impl DashboardApi for AppStateStore { - async fn list_dashboards(&self) -> Result> { - Ok(self.dashboards_snapshot().await) - } - async fn get_dashboard(&self, id: &str) -> Result> { - Ok(AppStateStore::get_dashboard(self, id).await) - } - async fn save_dashboard(&self, dashboard: Dashboard) -> Result { - self.upsert_dashboard(dashboard).await - } - async fn delete_dashboard(&self, id: &str) -> Result<()> { - AppStateStore::delete_dashboard(self, id).await - } -} - #[cfg(test)] mod tests { use super::*; @@ -348,7 +342,6 @@ mod tests { weight: 1.0, }], }], - panels: Vec::new(), }) .await .unwrap(); @@ -364,30 +357,4 @@ mod tests { s3.load().await.unwrap(); assert!(s3.dashboards_snapshot().await.is_empty()); } - - #[test] - fn legacy_panels_migrate_into_rows_grouped_by_y() { - // Old free-grid JSON: two panels on row y=0 (side by side) + one on y=4. - let json = serde_json::json!({ - "id": "d1", "title": "Old", "created_at_ns": 0, "updated_at_ns": 0, - "panels": [ - { "visualization": { "seql": "a", "title": "A" }, "layout": { "x": 0, "y": 0, "w": 6, "h": 4 } }, - { "visualization": { "seql": "b", "title": "B" }, "layout": { "x": 6, "y": 0, "w": 6, "h": 4 } }, - { "visualization": { "seql": "c", "title": "C" }, "layout": { "x": 0, "y": 4, "w": 12, "h": 4 } } - ] - }); - let mut dash: Dashboard = serde_json::from_value(json).unwrap(); - dash.migrate_legacy(); - - assert!(dash.panels.is_empty(), "legacy panels consumed"); - assert_eq!(dash.rows.len(), 2, "two y-groups → two rows"); - assert_eq!(dash.rows[0].panels.len(), 2, "row 0 has both y=0 panels"); - assert_eq!(dash.rows[0].panels[0].weight, 6.0, "weight from old width"); - assert_eq!(dash.rows[1].panels.len(), 1); - assert_eq!(dash.panel_count(), 3); - - // Idempotent. - dash.migrate_legacy(); - assert_eq!(dash.rows.len(), 2); - } } diff --git a/crates/sequins-metadata/src/types.rs b/crates/sequins-metadata/src/types.rs index 2687b378..071cc882 100644 --- a/crates/sequins-metadata/src/types.rs +++ b/crates/sequins-metadata/src/types.rs @@ -61,8 +61,7 @@ fn default_weight() -> f64 { /// A saved dashboard — a titled, ordered stack of full-width [`DashboardRow`]s. /// /// The layout is a flexbox of rows: each row has a height and fills the full width, -/// splitting it among its panels by relative weight. Legacy free-grid dashboards -/// (`panels` with `x/y/w/h`) are migrated into rows by [`Dashboard::migrate_legacy`]. +/// splitting it among its panels by relative weight. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Dashboard { pub id: String, @@ -71,10 +70,6 @@ pub struct Dashboard { pub updated_at_ns: u64, #[serde(default)] pub rows: Vec, - /// Legacy free-grid panels — read from old stored dashboards, migrated into - /// `rows`, and never re-serialized once migrated. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub panels: Vec, } impl Dashboard { @@ -82,42 +77,6 @@ impl Dashboard { pub fn panel_count(&self) -> usize { self.rows.iter().map(|r| r.panels.len()).sum() } - - /// Convert any legacy `panels` (free x/y/w/h grid) into `rows`: panels are grouped - /// into rows by their `y`, ordered left-to-right by `x`, with each panel's width - /// `w` becoming its row weight. Idempotent; a no-op once migrated. - pub fn migrate_legacy(&mut self) { - if self.panels.is_empty() { - return; - } - let mut legacy = std::mem::take(&mut self.panels); - legacy.sort_by_key(|p| (p.layout.y, p.layout.x)); - let mut rows: Vec = Vec::new(); - let mut current_y: Option = None; - for p in legacy { - let weight = if p.layout.w == 0 { - 1.0 - } else { - p.layout.w as f64 - }; - let row_panel = RowPanel { - visualization: p.visualization, - weight, - }; - if current_y == Some(p.layout.y) { - rows.last_mut().unwrap().panels.push(row_panel); - } else { - current_y = Some(p.layout.y); - rows.push(DashboardRow { - height: DEFAULT_ROW_HEIGHT, - panels: vec![row_panel], - }); - } - } - // Prepend migrated rows before any rows that already exist (there shouldn't be). - rows.append(&mut self.rows); - self.rows = rows; - } } /// A full-width dashboard row: a fixed height and an ordered set of panels that split @@ -149,15 +108,6 @@ pub struct RowPanel { pub weight: f64, } -/// A legacy free-grid panel: a saved visualization plus its old `x/y/w/h` layout. -/// Retained only to deserialize and migrate older dashboards. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Panel { - pub visualization: SavedVisualization, - #[serde(default)] - pub layout: Layout, -} - /// A visualization the app can re-render: a SeQL query, a title, and an optional /// requested `ResponseShape` (as its `as_str()` form, e.g. `"timeseries"`). #[derive(Debug, Clone, Serialize, Deserialize)] @@ -167,16 +117,3 @@ pub struct SavedVisualization { #[serde(default)] pub shape: Option, } - -/// Legacy grid placement of a panel within a dashboard (pre-rows layout). -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct Layout { - #[serde(default)] - pub x: u32, - #[serde(default)] - pub y: u32, - #[serde(default)] - pub w: u32, - #[serde(default)] - pub h: u32, -} From f027f1aea5958d950fb2e725098ec62f4d4d594c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 21 Jul 2026 17:36:26 +0800 Subject: [PATCH 05/10] =?UTF-8?q?feat(macos):=20assistant=20tools=20UX=20?= =?UTF-8?q?=E2=80=94=20selectors,=20dashboard=20approval,=20role-aware=20c?= =?UTF-8?q?harts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assistant tab: - Model + reasoning pickers below the composer as faded pills that light up on hover; send button right-aligned in the controls row. Model list pulled from the provider's /v1/models, filtered to text/chat models; reasoning effort selectable per turn. - Dashboard authoring is server-side; the app reloads dashboards after each turn. - Destructive ops (delete_dashboard/remove_chart) surface an in-chat approval card; the composer stays live so a new instruction redirects instead of a bare decline. Conversation delete with confirmation. - "Open Settings" and the settings assistant section actually work; the environment pane exposes provider base URL + API key. Visualization reliability: - Decode per-column SeQL roles; value detection plots only measures (a numeric dimension like http_status_code is never charted as a series); role-aware auto-selection; never render an empty chart — fall back to a table. Also: dashboard separators only surface while dragging; DRY cleanup (shared FFI-error/frame decoders, VizFormat helpers, delete unused VizData). Co-Authored-By: Claude Opus 4.8 (1M context) --- apps/macos/.gitignore | 2 + .../ViewModels/AppStateViewModel.swift | 11 +- .../ViewModels/AssistantViewModel.swift | 263 ++++++++++++++---- .../Assistant/AssistantContentView.swift | 56 +++- .../Views/Assistant/ChatInputBar.swift | 137 ++++++++- .../Views/Assistant/ChatListPanel.swift | 62 ++++- .../Views/Assistant/ChatTranscriptView.swift | 50 +++- .../Views/Dashboards/DashboardGridView.swift | 38 ++- .../Views/Explore/ExploreScalarView.swift | 2 +- .../macos/Sequins/Views/Main/MainWindow.swift | 12 +- .../Views/Settings/EditEnvironmentView.swift | 12 +- .../Sequins/Views/Settings/SettingsView.swift | 55 ++++ .../Views/Visualization/TimeSeriesChart.swift | 15 +- .../Visualization/VisualizationRunner.swift | 19 +- .../Visualization/VisualizationView.swift | 33 ++- .../Views/Visualization/VizCharts.swift | 22 +- .../Sources/SequinsData/AssistantAPI.swift | 68 +++++ .../Sources/SequinsData/DashboardStore.swift | 7 +- .../Sources/SequinsData/DataSource.swift | 63 ++--- .../Sources/SequinsData/ManagementAPI.swift | 35 +-- .../Sources/SequinsData/SQLQueryAPI.swift | 62 ++--- .../Sources/SequinsData/SeQLAPI.swift | 257 +++++++---------- .../Sources/SequinsData/VizFormat.swift | 41 +++ .../Sources/SequinsData/VizType.swift | 45 +-- 24 files changed, 925 insertions(+), 442 deletions(-) create mode 100644 apps/macos/.gitignore diff --git a/apps/macos/.gitignore b/apps/macos/.gitignore new file mode 100644 index 00000000..62fe11b1 --- /dev/null +++ b/apps/macos/.gitignore @@ -0,0 +1,2 @@ +# Local xcodebuild output (derivedDataPath used by the build scripts) +build/ diff --git a/apps/macos/Sequins/ViewModels/AppStateViewModel.swift b/apps/macos/Sequins/ViewModels/AppStateViewModel.swift index cb5a48e0..7f612f8b 100644 --- a/apps/macos/Sequins/ViewModels/AppStateViewModel.swift +++ b/apps/macos/Sequins/ViewModels/AppStateViewModel.swift @@ -20,7 +20,6 @@ final class AppStateViewModel { // UI State var selectedService: Service? var selectedView: NavigationItem = .traces - var showSettings = false var showServerInfo = false var isServiceAttributesExpanded = false @@ -67,17 +66,19 @@ final class AppStateViewModel { /// Keychain-stored secret. Returns `nil` when the assistant is not configured for /// the current environment (so the UI can prompt the user to set it up). /// - /// - Local: needs a model + API key (base URL optional → api.openai.com). - /// - Remote: needs the daemon `/v1` base URL + a bearer token. + /// The model is chosen at runtime in the Assistant tab (from the provider's model + /// list), so it isn't required here — only enough to reach the provider/daemon: + /// - Local: an API key (base URL optional → api.openai.com). + /// - Remote: the daemon `/v1` base URL + a bearer token. func assistantConfig() -> AssistantConfig? { if let env = environmentManager.selectedEnvironment { let secret = KeychainStore.shared.assistantSecret(environmentId: env.id) let base = env.assistantBaseURL?.isEmpty == false ? env.assistantBaseURL : nil let model = env.assistantModel?.isEmpty == false ? env.assistantModel : nil if let secret, !secret.isEmpty { - if env.isLocal, let model { + if env.isLocal { return AssistantConfig(baseURL: base, model: model, apiKey: secret) - } else if !env.isLocal, let base { + } else if let base { return AssistantConfig(baseURL: base, model: model, apiKey: secret) } } diff --git a/apps/macos/Sequins/ViewModels/AssistantViewModel.swift b/apps/macos/Sequins/ViewModels/AssistantViewModel.swift index 7529588e..99a3f9d2 100644 --- a/apps/macos/Sequins/ViewModels/AssistantViewModel.swift +++ b/apps/macos/Sequins/ViewModels/AssistantViewModel.swift @@ -40,6 +40,27 @@ struct ChatItem: Identifiable { } } +/// Reasoning effort for the assistant's next turn. `auto` sends nothing — the model's +/// default — while the middleware reconciles models that require a specific value. +enum ReasoningEffort: String, CaseIterable, Identifiable { + case auto, none, low, medium, high + + var id: String { rawValue } + + var label: String { + switch self { + case .auto: return "Auto" + case .none: return "None" + case .low: return "Low" + case .medium: return "Medium" + case .high: return "High" + } + } + + /// Value sent as `reasoning.effort`, or `nil` for `auto` (omit it entirely). + var wireValue: String? { self == .auto ? nil : rawValue } +} + /// Drives the Assistant chat tab: the conversation list, the active transcript, and a /// streaming turn. Conversation history is read from the `messages`/`conversations` /// tables via SQL; turns are sent through the normalized assistant FFI. @@ -53,11 +74,39 @@ final class AssistantViewModel { var inputText: String = "" var errorMessage: String? + /// Models advertised by the provider/daemon's `/v1/models`, for the input-bar picker. + private(set) var availableModels: [String] = [] + /// The model used for the next turn — chosen in the input bar, seeded from the + /// environment's saved model, defaulting to the first advertised model. + var selectedModel: String? + /// Reasoning effort for the next turn (chosen in the input bar). + var selectedReasoning: ReasoningEffort = .auto + /// Populated when the model list couldn't be fetched (bad key, offline, no `/models`). + private(set) var modelsError: String? + private var activeStream: AssistantChatStream? private var assistant: Assistant? private var assistantConfigKey: String? private var lastResponseId: String? + /// Called when a turn completes, so the host can reload dashboards the assistant may + /// have created/edited server-side (set by `MainWindow`). + var onDashboardsChanged: (() -> Void)? + + /// A destructive action the assistant proposed (delete a dashboard / remove a chart) + /// that awaits the user's approval. Rendered as a card in the transcript; the input + /// stays live so the user can instead type revised instructions. + private(set) var pendingApproval: PendingApproval? + + struct PendingApproval: Identifiable { + let id = UUID() + let toolName: String + let arguments: String + let title: String + let detail: String + let confirmLabel: String + } + // MARK: - Conversation list func refreshConversations(dataSource: DataSource) { @@ -109,11 +158,134 @@ final class AssistantViewModel { errorMessage = nil } + /// Delete a persisted conversation, removing it from the list and clearing the + /// transcript if it was the open chat. + func deleteConversation(_ id: String, dataSource: DataSource) { + do { + try dataSource.deleteConversation(id: id) + conversations.removeAll { $0.id == id } + if selectedConversationId == id { newChat() } + } catch { + errorMessage = error.localizedDescription + } + } + + // MARK: - Destructive-action approval + + /// Turn a destructive tool call into a pending approval card rather than executing it. + private func proposeDestructive(name: String, arguments: String) { + let obj = (arguments.data(using: .utf8) + .flatMap { try? JSONSerialization.jsonObject(with: $0) }) as? [String: Any] ?? [:] + let dashboard = (obj["dashboard"] as? String) ?? "this dashboard" + let pending: PendingApproval + switch name { + case "delete_dashboard": + pending = PendingApproval( + toolName: name, arguments: arguments, + title: "Delete dashboard “\(dashboard)”?", + detail: "This permanently removes the dashboard and all of its charts.", + confirmLabel: "Delete") + default: // remove_chart + let row = (obj["row"] as? Int).map(String.init) ?? "?" + let col = (obj["column"] as? Int).map(String.init) ?? "?" + pending = PendingApproval( + toolName: name, arguments: arguments, + title: "Remove chart [\(row),\(col)] from “\(dashboard)”?", + detail: "This removes the chart from the dashboard.", + confirmLabel: "Remove") + } + pendingApproval = pending + } + + /// User approved the pending destructive action — execute it via the data source. + func approvePending(dataSource: DataSource) { + guard let p = pendingApproval else { return } + pendingApproval = nil + let obj = (p.arguments.data(using: .utf8) + .flatMap { try? JSONSerialization.jsonObject(with: $0) }) as? [String: Any] ?? [:] + let key = (obj["dashboard"] as? String) ?? "" + do { + let output: String + switch p.toolName { + case "delete_dashboard": + guard let d = try resolveDashboard(key, dataSource: dataSource) else { + throw SequinsError.ffiError("no dashboard matching “\(key)”") + } + try dataSource.deleteDashboard(id: d.id) + output = "Deleted dashboard “\(d.title)”." + default: // remove_chart + guard var d = try resolveDashboard(key, dataSource: dataSource) else { + throw SequinsError.ffiError("no dashboard matching “\(key)”") + } + let row = obj["row"] as? Int ?? -1 + let col = obj["column"] as? Int ?? -1 + guard d.rows.indices.contains(row), d.rows[row].panels.indices.contains(col) else { + throw SequinsError.ffiError("no chart at [\(row),\(col)]") + } + d.rows[row].panels.remove(at: col) + d.rows.removeAll { $0.panels.isEmpty } + _ = try dataSource.saveDashboard(d) + output = "Removed chart [\(row),\(col)] from “\(d.title)”." + } + transcript.append(ChatItem(kind: .toolActivity(AssistantToolActivity( + name: p.toolName, arguments: p.arguments, output: output)))) + onDashboardsChanged?() + } catch { + errorMessage = error.localizedDescription + } + } + + /// User declined the pending destructive action. + func rejectPending() { + guard let p = pendingApproval else { return } + pendingApproval = nil + transcript.append(ChatItem(kind: .toolActivity(AssistantToolActivity( + name: p.toolName, arguments: p.arguments, output: "Declined.")))) + } + + /// Resolve a dashboard by id, then case-insensitive title. + private func resolveDashboard(_ key: String, dataSource: DataSource) throws -> Dashboard? { + if let byId = try dataSource.getDashboard(id: key) { return byId } + return try dataSource.listDashboards() + .first { $0.title.caseInsensitiveCompare(key) == .orderedSame } + } + + // MARK: - Model list + + /// Fetch the provider/daemon's model list for the input-bar picker and settle on a + /// selection: keep the current one, else the environment's saved model, else the + /// first advertised model. + func loadModels(config: AssistantConfig) async { + if selectedModel == nil { selectedModel = config.model } + do { + let models = try await fetchAssistantModels(config) + availableModels = models + modelsError = nil + if selectedModel == nil || selectedModel?.isEmpty == true { + selectedModel = models.first + } + } catch { + availableModels = [] + modelsError = error.localizedDescription + } + } + // MARK: - Sending - func send(dataSource: DataSource, config: AssistantConfig) { + func send(dataSource: DataSource, config baseConfig: AssistantConfig) { let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty, !isStreaming else { return } + // A new instruction supersedes any pending destructive proposal — treat it as a + // decline and let the model act on the revised guidance. + if let pending = pendingApproval { + pendingApproval = nil + transcript.append(ChatItem(kind: .toolActivity(AssistantToolActivity( + name: pending.toolName, arguments: pending.arguments, + output: "Skipped — see new instructions below.")))) + } + // The input-bar picker's model wins over the environment default. + var config = baseConfig + if let selectedModel, !selectedModel.isEmpty { config.model = selectedModel } inputText = "" errorMessage = nil transcript.append(ChatItem(kind: .userText(text))) @@ -134,8 +306,8 @@ final class AssistantViewModel { if let viz = self.parseVisualization(from: call.arguments) { self.transcript.append(ChatItem(kind: .visualization(viz))) } - case "add_to_dashboard": - self.handleAddToDashboard(arguments: call.arguments, dataSource: dataSource) + case "delete_dashboard", "remove_chart": + self.proposeDestructive(name: call.name, arguments: call.arguments) default: break } @@ -175,6 +347,8 @@ final class AssistantViewModel { isStreaming = false activeStream = nil refreshConversations(dataSource: dataSource) + // The turn may have created/edited dashboards via server-side tools; reload them. + onDashboardsChanged?() } private func appendTextDelta(_ delta: String) { @@ -209,36 +383,6 @@ final class AssistantViewModel { } } - /// Handle an `add_to_dashboard` tool call: find the named dashboard (or create it) - /// and append the visualization as a new full-width row, then persist. - private func handleAddToDashboard(arguments: String, dataSource: DataSource) { - guard let viz = parseVisualization(from: arguments), - let obj = jsonObject(arguments) else { return } - let dashboardName = (obj["dashboard"] as? String) - ?? (obj["dashboard_name"] as? String) - ?? "Assistant" - do { - let existing = try dataSource.listDashboards() - var dashboard = existing.first { $0.title.caseInsensitiveCompare(dashboardName) == .orderedSame } - ?? Dashboard(title: dashboardName) - dashboard.rows.append(DashboardRow(panels: [RowPanel(visualization: viz)])) - _ = try dataSource.saveDashboard(dashboard) - // Show the chart inline plus a confirmation of where it went. - transcript.append(ChatItem(kind: .visualization(viz))) - transcript.append(ChatItem(kind: .toolActivity(AssistantToolActivity( - name: "add_to_dashboard", - arguments: arguments, - output: "Added “\(viz.title)” to dashboard “\(dashboardName)”.")))) - } catch { - errorMessage = error.localizedDescription - } - } - - private func jsonObject(_ json: String) -> [String: Any]? { - guard let data = json.data(using: .utf8) else { return nil } - return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] - } - /// Parse `render_visualization` arguments (`{ query|seql, title, chart_type? }`) /// into a `SavedVisualization`. func parseVisualization(from argsJSON: String) -> SavedVisualization? { @@ -258,8 +402,11 @@ final class AssistantViewModel { "input": [["type": "message", "role": "user", "content": userText]], "stream": true, "store": true, - "tools": [renderVisualizationTool, addToDashboardTool], + "tools": [renderVisualizationTool, deleteDashboardTool, removeChartTool], ] + if let effort = selectedReasoning.wireValue { + req["reasoning"] = ["effort": effort] + } if let lastResponseId { req["previous_response_id"] = lastResponseId } @@ -294,36 +441,34 @@ final class AssistantViewModel { ] } - private var addToDashboardTool: [String: Any] { + private var deleteDashboardTool: [String: Any] { [ - "name": "add_to_dashboard", - "description": "Save a visualization to a dashboard (by name). If a dashboard with " - + "that name exists the chart is appended as a new row; otherwise a new dashboard " - + "with that name is created. Use this when the user asks to add a chart to, or " - + "build, a dashboard — as opposed to render_visualization which only shows a chart " - + "inline in the chat.", + "name": "delete_dashboard", + "description": "Delete a dashboard (by id or title). DESTRUCTIVE — the user must " + + "approve; propose it and let them confirm.", "parameters": [ "type": "object", "properties": [ - "query": [ - "type": "string", - "description": "The SeQL query whose results the chart shows.", - ], - "title": [ - "type": "string", - "description": "A short, descriptive title for the chart.", - ], - "dashboard": [ - "type": "string", - "description": "Name of the dashboard to add the chart to (created if missing).", - ], - "chart_type": [ - "type": "string", - "enum": VizType.allCases.map { $0.rawValue }, - "description": "Optional chart type. Omit to let the client choose.", - ], + "dashboard": ["type": "string", "description": "Dashboard id or title to delete."], + ], + "required": ["dashboard"], + ], + ] + } + + private var removeChartTool: [String: Any] { + [ + "name": "remove_chart", + "description": "Remove a chart from a dashboard by its [row,column] position (from " + + "get_dashboard). DESTRUCTIVE — the user must approve.", + "parameters": [ + "type": "object", + "properties": [ + "dashboard": ["type": "string", "description": "Dashboard id or title."], + "row": ["type": "integer", "description": "Row index of the chart."], + "column": ["type": "integer", "description": "Column index within the row."], ], - "required": ["query", "title", "dashboard"], + "required": ["dashboard", "row", "column"], ], ] } diff --git a/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift b/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift index 95bb4b0c..b662ddc5 100644 --- a/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift +++ b/apps/macos/Sequins/Views/Assistant/AssistantContentView.swift @@ -45,10 +45,64 @@ struct AssistantContentView: View { } else { VStack(spacing: 0) { ChatTranscriptView(viewModel: viewModel) + if let modelsError = viewModel.modelsError { + modelsErrorBanner(modelsError) + } Divider() ChatInputBar(viewModel: viewModel, onSend: sendMessage) } + // Load the provider's model list whenever the provider (base URL / key) + // changes; the picker in the input bar selects among them. + .task(id: assistantProviderKey) { + if let config = appState.assistantConfig() { + await viewModel.loadModels(config: config) + } + } + // Remember the chosen model on the environment so it persists across launches + // and feeds `assistantConfig()`. + .onChange(of: viewModel.selectedModel) { _, newValue in + persistSelectedModel(newValue) + } + } + } + + /// Identity of the current assistant provider — changes when the base URL or the + /// presence of an API key changes, so the model list reloads. + private var assistantProviderKey: String { + let config = appState.assistantConfig() + return "\(config?.resolvedBaseURL ?? "")|\(config?.apiKey?.isEmpty == false)" + } + + /// A visible banner explaining why the model list is empty (e.g. an invalid API key + /// or an unreachable provider), with a shortcut to fix it in Settings. + private func modelsErrorBanner(_ message: String) -> some View { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + VStack(alignment: .leading, spacing: 1) { + Text("Couldn't load models") + .font(.caption.weight(.semibold)) + Text(message) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(2) + } + Spacer() + SettingsLink { Text("Settings") } + .font(.caption) } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color.orange.opacity(0.12)) + } + + /// Persist the selected model to the current environment (when there is one). + private func persistSelectedModel(_ model: String?) { + guard let env = appState.environmentManager.selectedEnvironment, + env.assistantModel != model else { return } + env.assistantModel = model + appState.environmentManager.updateEnvironment(env) } private var configPrompt: some View { @@ -63,7 +117,7 @@ struct AssistantContentView: View { .foregroundStyle(.secondary) .multilineTextAlignment(.center) .frame(maxWidth: 320) - Button("Open Settings") { appState.showSettings = true } + SettingsLink { Text("Open Settings") } .buttonStyle(.borderedProminent) } .frame(maxWidth: .infinity, maxHeight: .infinity) diff --git a/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift b/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift index 0758495b..c69a611a 100644 --- a/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift +++ b/apps/macos/Sequins/Views/Assistant/ChatInputBar.swift @@ -5,12 +5,15 @@ struct ChatInputBar: View { @Bindable var viewModel: AssistantViewModel let onSend: () -> Void + @State private var modelHover = false + @State private var reasoningHover = false + private var canSend: Bool { !viewModel.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } var body: some View { - HStack(alignment: .bottom, spacing: 8) { + VStack(alignment: .leading, spacing: 8) { TextField("Ask about your telemetry…", text: $viewModel.inputText, axis: .vertical) .textFieldStyle(.plain) .lineLimit(1...6) @@ -21,25 +24,129 @@ struct ChatInputBar: View { if canSend { onSend() } } - if viewModel.isStreaming { + // Per-turn controls under the composer; send/stop is right-aligned. + HStack(spacing: 14) { + modelPicker + reasoningPicker + Spacer() + sendButton + } + .padding(.horizontal, 6) + .padding(.bottom, 2) + } + .padding(8) + } + + @ViewBuilder + private var sendButton: some View { + if viewModel.isStreaming { + Button { + viewModel.cancelStreaming() + } label: { + Image(systemName: "stop.circle.fill") + .font(.title2) + } + .buttonStyle(.borderless) + .help("Stop") + } else { + Button(action: onSend) { + Image(systemName: "arrow.up.circle.fill") + .font(.title2) + } + .buttonStyle(.borderless) + .disabled(!canSend) + .help("Send") + } + } + + /// Model selector — lists the provider/daemon's advertised models and changes the + /// model used for the next turn on the fly. + private var modelPicker: some View { + Menu { + if viewModel.availableModels.isEmpty { + Text(viewModel.modelsError == nil ? "Loading models…" : "No models available") + } + ForEach(viewModel.availableModels, id: \.self) { model in Button { - viewModel.cancelStreaming() + viewModel.selectedModel = model } label: { - Image(systemName: "stop.circle.fill") - .font(.title2) + if viewModel.selectedModel == model { + Label(model, systemImage: "checkmark") + } else { + Text(model) + } } - .buttonStyle(.borderless) - .help("Stop") - } else { - Button(action: onSend) { - Image(systemName: "arrow.up.circle.fill") - .font(.title2) + } + } label: { + pill(hovered: modelHover) { + Image(systemName: "cpu") + Text(viewModel.selectedModel ?? "Model") + .lineLimit(1) + .truncationMode(.middle) + .frame(maxWidth: 200) + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .semibold)) + } + } + .menuStyle(.button) + .buttonStyle(.plain) + .menuIndicator(.hidden) + .fixedSize() + .onHover { modelHover = $0 } + .help(viewModel.modelsError ?? "Model for the next message") + } + + /// Reasoning-effort selector — controls how hard the model thinks before answering. + /// Unsupported choices are reconciled by the assistant middleware. + private var reasoningPicker: some View { + Menu { + ForEach(ReasoningEffort.allCases) { effort in + Button { + viewModel.selectedReasoning = effort + } label: { + if viewModel.selectedReasoning == effort { + Label(effort.label, systemImage: "checkmark") + } else { + Text(effort.label) + } } - .buttonStyle(.borderless) - .disabled(!canSend) - .help("Send") + } + } label: { + pill(hovered: reasoningHover) { + Image(systemName: "brain") + Text(viewModel.selectedReasoning.label) + Image(systemName: "chevron.down") + .font(.system(size: 8, weight: .semibold)) } } - .padding(8) + .menuStyle(.button) + .buttonStyle(.plain) + .menuIndicator(.hidden) + .fixedSize() + .onHover { reasoningHover = $0 } + .help("Reasoning effort for the next message") + } + + /// A compact pill label for the per-turn control menus: subtle/faded by default, and + /// lit up (brighter fill + border, full opacity) while hovered. + @ViewBuilder + private func pill( + hovered: Bool, @ViewBuilder content: () -> Content + ) -> some View { + HStack(spacing: 4) { + content() + } + .font(.caption) + .foregroundStyle(.secondary) + .padding(.horizontal, 10) + .padding(.vertical, 4) + .background( + Capsule().fill(Color.secondary.opacity(hovered ? 0.16 : 0.07)) + ) + .overlay( + Capsule().strokeBorder(Color.secondary.opacity(hovered ? 0.3 : 0.12), lineWidth: 0.5) + ) + .opacity(hovered ? 1.0 : 0.6) + .animation(.easeOut(duration: 0.15), value: hovered) } } diff --git a/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift b/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift index 59762d28..516925f7 100644 --- a/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift +++ b/apps/macos/Sequins/Views/Assistant/ChatListPanel.swift @@ -6,6 +6,9 @@ struct ChatListPanel: View { @Environment(AppStateViewModel.self) private var appState @Bindable var viewModel: AssistantViewModel + /// The conversation pending deletion (drives the confirmation dialog). + @State private var conversationToDelete: ConversationSummary? + var body: some View { VStack(spacing: 0) { HStack { @@ -38,12 +41,8 @@ struct ChatListPanel: View { } else { List(selection: selectionBinding) { ForEach(viewModel.conversations) { convo in - VStack(alignment: .leading, spacing: 2) { - Text(convo.displayTitle) - .lineLimit(1) - Text("\(convo.itemCount) message\(convo.itemCount == 1 ? "" : "s")") - .font(.caption) - .foregroundStyle(.secondary) + ConversationRow(convo: convo) { + conversationToDelete = convo } .tag(convo.id) } @@ -52,6 +51,24 @@ struct ChatListPanel: View { } } .background(Color(nsColor: .controlBackgroundColor).opacity(0.5)) + .confirmationDialog( + "Delete this chat?", + isPresented: Binding( + get: { conversationToDelete != nil }, + set: { if !$0 { conversationToDelete = nil } } + ), + presenting: conversationToDelete + ) { convo in + Button("Delete", role: .destructive) { + if let ds = appState.dataSource { + viewModel.deleteConversation(convo.id, dataSource: ds) + } + conversationToDelete = nil + } + Button("Cancel", role: .cancel) { conversationToDelete = nil } + } message: { convo in + Text("“\(convo.displayTitle)” will be permanently deleted.") + } } private var selectionBinding: Binding { @@ -65,3 +82,36 @@ struct ChatListPanel: View { ) } } + +/// One conversation row: title + message count, with a delete (✕) button revealed on +/// hover. +private struct ConversationRow: View { + let convo: ConversationSummary + let onDelete: () -> Void + + @State private var hovering = false + + var body: some View { + HStack(spacing: 6) { + VStack(alignment: .leading, spacing: 2) { + Text(convo.displayTitle) + .lineLimit(1) + Text("\(convo.itemCount) message\(convo.itemCount == 1 ? "" : "s")") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 0) + if hovering { + Button(action: onDelete) { + Image(systemName: "xmark") + .font(.caption2) + .foregroundStyle(.secondary) + } + .buttonStyle(.borderless) + .help("Delete chat") + } + } + .contentShape(Rectangle()) + .onHover { hovering = $0 } + } +} diff --git a/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift b/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift index f9e382e4..24442542 100644 --- a/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift +++ b/apps/macos/Sequins/Views/Assistant/ChatTranscriptView.swift @@ -16,7 +16,7 @@ struct ChatTranscriptView: View { if let last = viewModel.transcript.last, case .assistantText(let t) = last.kind { lastLen = t.count } - return "\(count)-\(lastLen)-\(viewModel.isStreaming)" + return "\(count)-\(lastLen)-\(viewModel.isStreaming)-\(viewModel.pendingApproval?.id.uuidString ?? "")" } /// A transcript run: either a standalone message, or a group of consecutive tool @@ -71,6 +71,19 @@ struct ChatTranscriptView: View { } } + if let pending = viewModel.pendingApproval { + ApprovalCard( + pending: pending, + onApprove: { + if let ds = appState.dataSource { + viewModel.approvePending(dataSource: ds) + } + }, + onReject: { viewModel.rejectPending() } + ) + .id("approval-\(pending.id)") + } + if viewModel.isStreaming { HStack(spacing: 6) { ProgressView().scaleEffect(0.6) @@ -100,3 +113,38 @@ struct ChatTranscriptView: View { } } } + +/// An in-chat approval prompt for a destructive assistant action. The composer stays +/// live below, so the user can approve, cancel, or type revised instructions instead. +private struct ApprovalCard: View { + let pending: AssistantViewModel.PendingApproval + let onApprove: () -> Void + let onReject: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + Text(pending.title) + .font(.callout.weight(.semibold)) + } + Text(pending.detail) + .font(.caption) + .foregroundStyle(.secondary) + HStack { + Spacer() + Button("Cancel", role: .cancel, action: onReject) + Button(pending.confirmLabel, role: .destructive, action: onApprove) + .keyboardShortcut(.defaultAction) + } + } + .padding(12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: 10).fill(Color.orange.opacity(0.10))) + .overlay( + RoundedRectangle(cornerRadius: 10) + .strokeBorder(Color.orange.opacity(0.35), lineWidth: 1) + ) + } +} diff --git a/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift b/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift index a9b6c18d..84a7da15 100644 --- a/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift +++ b/apps/macos/Sequins/Views/Dashboards/DashboardGridView.swift @@ -74,6 +74,7 @@ struct DashboardGridView: View { RowResizeHandle( thickness: handleThickness, + revealed: dragActive, onChanged: { dy in if let ds = dataSource { viewModel.setRowHeight(rowIndex, height: row.height + dy, persist: false, dataSource: ds) @@ -206,6 +207,7 @@ private struct DashboardRowView: View { if panelIndex < row.panels.count - 1 { PanelRatioHandle( width: panelHandleWidth, + revealed: dragActive, onChanged: { dx in ratioDrag(after: panelIndex, dx: dx, panelsWidth: panelsWidth, commit: false) }, onEnded: { dx in ratioDrag(after: panelIndex, dx: dx, panelsWidth: panelsWidth, commit: true) } ) @@ -390,11 +392,22 @@ private struct DashboardPanelView: View { // MARK: - Handles /// A vertical bar dragged left/right to re-proportion two adjacent panels. +/// +/// Its grip is normally invisible so the gap reads as plain margin between charts; it +/// surfaces only when a chart is being dragged (`revealed` — every boundary lights up as +/// a drop/resize area) or while this handle itself is hovered or dragged to resize. private struct PanelRatioHandle: View { let width: CGFloat + /// A chart drag is in progress — reveal all separators as drop/resize areas. + let revealed: Bool let onChanged: (CGFloat) -> Void let onEnded: (CGFloat) -> Void + @State private var isHovering = false + @State private var isDragging = false + + private var showGrip: Bool { revealed || isHovering || isDragging } + var body: some View { Rectangle() .fill(Color.secondary.opacity(0.001)) @@ -402,26 +415,38 @@ private struct PanelRatioHandle: View { RoundedRectangle(cornerRadius: 1.5) .fill(Color.secondary.opacity(0.35)) .frame(width: 3) + .opacity(showGrip ? 1 : 0) ) .frame(width: width) .contentShape(Rectangle()) .onHover { inside in + isHovering = inside if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } } .gesture( DragGesture() - .onChanged { onChanged($0.translation.width) } - .onEnded { onEnded($0.translation.width) } + .onChanged { isDragging = true; onChanged($0.translation.width) } + .onEnded { isDragging = false; onEnded($0.translation.width) } ) + .animation(.easeOut(duration: 0.12), value: showGrip) } } -/// A horizontal bar dragged up/down to resize the row above it. +/// A horizontal bar dragged up/down to resize the row above it. Like ``PanelRatioHandle`` +/// its grip is blank margin until a chart is dragged (`revealed`) or the handle is +/// hovered/dragged to resize. private struct RowResizeHandle: View { let thickness: CGFloat + /// A chart drag is in progress — reveal all separators as drop/resize areas. + let revealed: Bool let onChanged: (CGFloat) -> Void let onEnded: (CGFloat) -> Void + @State private var isHovering = false + @State private var isDragging = false + + private var showGrip: Bool { revealed || isHovering || isDragging } + var body: some View { Rectangle() .fill(Color.secondary.opacity(0.001)) @@ -430,17 +455,20 @@ private struct RowResizeHandle: View { .fill(Color.secondary.opacity(0.35)) .frame(height: 3) .padding(.horizontal, 40) + .opacity(showGrip ? 1 : 0) ) .frame(height: thickness) .contentShape(Rectangle()) .onHover { inside in + isHovering = inside if inside { NSCursor.resizeUpDown.push() } else { NSCursor.pop() } } .gesture( DragGesture() - .onChanged { onChanged($0.translation.height) } - .onEnded { onEnded($0.translation.height) } + .onChanged { isDragging = true; onChanged($0.translation.height) } + .onEnded { isDragging = false; onEnded($0.translation.height) } ) + .animation(.easeOut(duration: 0.12), value: showGrip) } } diff --git a/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift b/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift index ca36b3e6..9f39c5ea 100644 --- a/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift +++ b/apps/macos/Sequins/Views/Explore/ExploreScalarView.swift @@ -12,7 +12,7 @@ struct ExploreScalarView: View { var previousValue: Double? private var currentValue: Double? { - rows.first?.compactMap { VizFormat.numeric($0) }.first + VizFormat.firstNumeric(inFirstRowOf: rows) } private var display: String { diff --git a/apps/macos/Sequins/Views/Main/MainWindow.swift b/apps/macos/Sequins/Views/Main/MainWindow.swift index 36619a8e..85952b8c 100644 --- a/apps/macos/Sequins/Views/Main/MainWindow.swift +++ b/apps/macos/Sequins/Views/Main/MainWindow.swift @@ -3,6 +3,7 @@ import SwiftUI /// Main application window containing the navigation split view and tab content struct MainWindow: View { @Environment(AppStateViewModel.self) private var appState + @Environment(\.openSettings) private var openSettings @State private var selectedTab: NavigationItem @State private var columnVisibility: NavigationSplitViewVisibility = .all @@ -142,9 +143,18 @@ struct MainWindow: View { appState.connectToDataSource() } } + .onAppear { + // Reload dashboards after an assistant turn that edited them server-side, so a + // dashboard the user is viewing updates live. + assistantViewModel.onDashboardsChanged = { + if let ds = appState.dataSource { + dashboardsViewModel.refresh(dataSource: ds) + } + } + } .alert("Connection Error", isPresented: .constant(appState.dataSourceError != nil)) { Button("Retry") { appState.reconnect() } - Button("Settings") { appState.showSettings = true } + Button("Settings") { openSettings() } Button("OK") { appState.dataSourceError = nil } } message: { if let error = appState.dataSourceError { diff --git a/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift b/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift index 79c94909..1113eca0 100644 --- a/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift +++ b/apps/macos/Sequins/Views/Settings/EditEnvironmentView.swift @@ -213,22 +213,14 @@ struct EditEnvironmentView: View { .textFieldStyle(.roundedBorder) } - LabeledContent("Model") { - TextField( - environment.isLocal ? "gpt-5.5" : "(optional)", - text: optionalBinding(\.assistantModel) - ) - .textFieldStyle(.roundedBorder) - } - LabeledContent(environment.isLocal ? "API Key" : "Bearer Token") { SecureField("", text: $assistantSecret) .textFieldStyle(.roundedBorder) } Text(environment.isLocal - ? "Stored securely in your Keychain. Required to chat with the assistant." - : "Bearer token for the daemon's assistant endpoint. Stored in your Keychain.") + ? "Stored securely in your Keychain. Pick a model from the list in the Assistant tab." + : "Bearer token for the daemon's assistant endpoint. Stored in your Keychain. Pick a model in the Assistant tab.") .font(.caption) .foregroundStyle(.secondary) } diff --git a/apps/macos/Sequins/Views/Settings/SettingsView.swift b/apps/macos/Sequins/Views/Settings/SettingsView.swift index f5b77f26..3c113871 100644 --- a/apps/macos/Sequins/Views/Settings/SettingsView.swift +++ b/apps/macos/Sequins/Views/Settings/SettingsView.swift @@ -49,6 +49,9 @@ struct SelectedEnvironmentView: View { @Environment(AppStateViewModel.self) private var appState @Bindable var environment: ConnectionEnvironment @State private var needsReconnect = false + /// Assistant API key / bearer token — loaded from and saved to the Keychain (never + /// stored in the SwiftData model). + @State private var assistantSecret = "" var body: some View { Form { @@ -95,6 +98,9 @@ struct SelectedEnvironmentView: View { remoteEnvironmentSettings } + // Assistant (AI) configuration + assistantSettings + // About section Section("About") { LabeledContent("Version", value: "1.0.0") @@ -102,6 +108,55 @@ struct SelectedEnvironmentView: View { } } .formStyle(.grouped) + .task(id: environment.id) { + assistantSecret = KeychainStore.shared.assistantSecret(environmentId: environment.id) ?? "" + } + } + + /// Assistant (AI) configuration. Base URL + model persist on the environment; the + /// API key / bearer token is stored in the Keychain. Changes apply on the next chat + /// turn (the assistant reads its config fresh each time), so no reconnect is needed. + @ViewBuilder + private var assistantSettings: some View { + Section("Assistant (AI)") { + LabeledContent(environment.isLocal ? "Provider Base URL" : "Daemon /v1 URL") { + TextField( + environment.isLocal ? "https://api.openai.com/v1" : "http://host:8082/v1", + text: assistantBinding(\.assistantBaseURL) + ) + .textFieldStyle(.roundedBorder) + .frame(maxWidth: 350) + } + + LabeledContent(environment.isLocal ? "API Key" : "Bearer Token") { + SecureField("", text: $assistantSecret) + .textFieldStyle(.roundedBorder) + .frame(maxWidth: 350) + .onChange(of: assistantSecret) { _, newValue in + KeychainStore.shared.setAssistantSecret(newValue, environmentId: environment.id) + } + } + + Text(environment.isLocal + ? "OpenAI-compatible provider. Leave the base URL blank for api.openai.com. The API key is stored securely in your Keychain. Pick a model from the list in the Assistant tab." + : "The daemon's assistant /v1 endpoint and bearer token. Stored in your Keychain. Pick a model in the Assistant tab.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + + /// A `String` binding over an optional environment field that persists on edit and + /// maps empty strings to `nil`. + private func assistantBinding( + _ keyPath: ReferenceWritableKeyPath + ) -> Binding { + Binding( + get: { environment[keyPath: keyPath] ?? "" }, + set: { + environment[keyPath: keyPath] = $0.isEmpty ? nil : $0 + appState.environmentManager.updateEnvironment(environment) + } + ) } @ViewBuilder diff --git a/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift b/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift index e44a31d5..1069fc27 100644 --- a/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift +++ b/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift @@ -11,6 +11,7 @@ struct TimeSeriesChart: View { let columns: [String] let rows: [[Any?]] let columnTypes: [NodeTypeLabel] + var columnRoles: [SeQLColumnRole] = [] /// Fill under the line (area) vs. a plain line. var filled: Bool = false /// Stack the areas/series (area only). @@ -28,19 +29,13 @@ struct TimeSeriesChart: View { @State private var plotFrame: CGRect = .zero private var isTemporal: Bool { - if columnTypes.first == .timestamp { return true } - // Fall back to the data: the backend now emits time buckets as Arrow timestamps, - // which arrive as `Date`. - return rows.first?.first is Date + VizFormat.isTemporalFirstColumn(columnTypes: columnTypes, rows: rows) } - /// Numeric "value" columns (every column after the first that carries numbers). + /// Numeric "value" columns (measures when roles are known, else every column after + /// the first that carries numbers). private var seriesColumns: [(index: Int, name: String)] { - guard columns.count > 1 else { return [] } - return (1.. idx && VizFormat.numeric($0[idx]) != nil } - return numeric ? (idx, columns[idx]) : nil - } + VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles) } private var data: [Datum] { diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift b/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift index 784d2367..dd4d5917 100644 --- a/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift +++ b/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift @@ -1,20 +1,16 @@ import Foundation import SequinsData -/// Runs the query behind a ``VisualizationView`` and exposes its schema, rows, per-column -/// semantic types, and the raw batches reactively. Supports a one-shot snapshot -/// (`executeSeQL`) and a continuously updating live stream (`executeLiveSeQL`). +/// Runs the query behind a ``VisualizationView`` and exposes its schema, rows, and +/// per-column semantic types reactively. Supports a one-shot snapshot (`executeSeQL`) +/// and a continuously updating live stream (`executeLiveSeQL`). @MainActor @Observable final class VisualizationRunner: SeQLSink { private(set) var schema: SeQLSchema? private(set) var rows: [[Any?]] = [] - private(set) var recordTrees: [RecordNode] = [] /// Semantic type per column (temporal/duration/number/id/…), from the Arrow schema. private(set) var columnTypes: [NodeTypeLabel] = [] - /// The raw primary-table batches (kept for renderers that need typed decode, e.g. the - /// trace waterfall). - private(set) var primaryBatches: [RecordBatch] = [] private(set) var errorMessage: String? private(set) var isLoading = false @@ -22,6 +18,8 @@ final class VisualizationRunner: SeQLSink { private var liveStream: LiveSeQLStream? var columns: [String] { schema?.columnNames ?? [] } + /// Per-column semantic roles (dimensions vs measures), when the schema supplies them. + var columnRoles: [SeQLColumnRole] { schema?.columnRoles ?? [] } var shape: ResponseShape { schema?.shape ?? .table } /// (Re)start the query. Cancels any prior stream first. @@ -29,9 +27,7 @@ final class VisualizationRunner: SeQLSink { stop() errorMessage = nil rows = [] - recordTrees = [] columnTypes = [] - primaryBatches = [] isLoading = true guard !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { @@ -75,9 +71,7 @@ final class VisualizationRunner: SeQLSink { guard let stream = liveStream else { return } if let s = stream.schema { schema = s } let batches = stream.batches - primaryBatches = batches rows = batches.flatMap { $0.toRows() } - recordTrees = batches.flatMap { $0.toRecordTrees() } if let first = batches.first { columnTypes = first.columnTypeLabels() } } @@ -90,12 +84,9 @@ final class VisualizationRunner: SeQLSink { nonisolated func onBatch(_ batch: RecordBatch, table: String?) { guard table == nil else { return } let newRows = batch.toRows() - let newTrees = batch.toRecordTrees() let types = batch.columnTypeLabels() Task { @MainActor in self.rows.append(contentsOf: newRows) - self.recordTrees.append(contentsOf: newTrees) - self.primaryBatches.append(batch) if self.columnTypes.isEmpty { self.columnTypes = types } } } diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift index 121f483c..31fdff85 100644 --- a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift +++ b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift @@ -24,12 +24,17 @@ struct VisualizationView: View { var effectiveVizType: VizType { vizTypeOverride ?? visualization.vizType - ?? VizType.autoSelect(shape: runner.shape, columns: runner.columns, rows: runner.rows) + ?? VizType.autoSelect( + shape: runner.shape, + columns: runner.columns, + rows: runner.rows, + roles: runner.columnRoles + ) } /// The prior-period scalar value (for a stat's delta), when loaded. private var previousStatValue: Double? { - prevRunner.rows.first?.compactMap { VizFormat.numeric($0) }.first + VizFormat.firstNumeric(inFirstRowOf: prevRunner.rows) } /// The query to execute — time-scope rewritten when `applyTimeRange` is set. @@ -68,7 +73,7 @@ struct VisualizationView: View { columns: runner.columns, rows: runner.rows, columnTypes: runner.columnTypes, - recordTrees: runner.recordTrees, + columnRoles: runner.columnRoles, previousValue: previousStatValue ) } @@ -104,21 +109,31 @@ struct VizRenderer: View { let columns: [String] let rows: [[Any?]] var columnTypes: [NodeTypeLabel] = [] - let recordTrees: [RecordNode] + var columnRoles: [SeQLColumnRole] = [] var previousValue: Double? + /// A chart type that plots measures but has none to plot degrades to a table, so a + /// result with rows always shows something rather than an empty chart. + private var effectiveType: VizType { + if vizType.plotsMeasures, !rows.isEmpty, + VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles).isEmpty { + return .table + } + return vizType + } + var body: some View { - switch vizType { + switch effectiveType { case .line: ExploreTimeSeriesView(columns: columns, rows: rows, columnTypes: columnTypes) case .area: - AreaChartView(columns: columns, rows: rows, columnTypes: columnTypes) + AreaChartView(columns: columns, rows: rows, columnTypes: columnTypes, columnRoles: columnRoles) case .bar: - BarChartView(columns: columns, rows: rows, stacked: false, columnTypes: columnTypes) + BarChartView(columns: columns, rows: rows, stacked: false, columnTypes: columnTypes, columnRoles: columnRoles) case .stackedBar: - BarChartView(columns: columns, rows: rows, stacked: true, columnTypes: columnTypes) + BarChartView(columns: columns, rows: rows, stacked: true, columnTypes: columnTypes, columnRoles: columnRoles) case .pie: - PieChartView(columns: columns, rows: rows, columnTypes: columnTypes) + PieChartView(columns: columns, rows: rows, columnTypes: columnTypes, columnRoles: columnRoles) case .gauge: GaugeChartView(columns: columns, rows: rows, columnTypes: columnTypes) case .stat: diff --git a/apps/macos/Sequins/Views/Visualization/VizCharts.swift b/apps/macos/Sequins/Views/Visualization/VizCharts.swift index ceb47328..37f8ea26 100644 --- a/apps/macos/Sequins/Views/Visualization/VizCharts.swift +++ b/apps/macos/Sequins/Views/Visualization/VizCharts.swift @@ -15,10 +15,11 @@ struct AreaChartView: View { let columns: [String] let rows: [[Any?]] var columnTypes: [NodeTypeLabel] = [] + var columnRoles: [SeQLColumnRole] = [] var body: some View { TimeSeriesChart(columns: columns, rows: rows, columnTypes: columnTypes, - filled: true, stacked: true) + columnRoles: columnRoles, filled: true, stacked: true) } } @@ -29,17 +30,15 @@ struct BarChartView: View { let rows: [[Any?]] var stacked: Bool = false var columnTypes: [NodeTypeLabel] = [] + var columnRoles: [SeQLColumnRole] = [] private struct Bar: Identifiable { let id = UUID(); let category: String; let value: Double; let series: String } - /// Numeric value columns. + /// Numeric value columns (measures when roles are known). private var valueCols: [(index: Int, name: String)] { - guard columns.count > 1 else { return [] } - return (1.. idx && VizFormat.numeric($0[idx]) != nil } ? (idx, columns[idx]) : nil - } + VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles) } private var singleSeries: Bool { valueCols.count == 1 } @@ -115,6 +114,7 @@ struct PieChartView: View { let columns: [String] let rows: [[Any?]] var columnTypes: [NodeTypeLabel] = [] + var columnRoles: [SeQLColumnRole] = [] private struct Slice: Identifiable { let id = UUID(); let category: String; let value: Double @@ -122,14 +122,12 @@ struct PieChartView: View { /// True when the data looks like a time series (pie is the wrong chart for it). private var looksTemporal: Bool { - columnTypes.first == .timestamp || rows.first?.first is Date + VizFormat.isTemporalFirstColumn(columnTypes: columnTypes, rows: rows) } private var slices: [Slice] { guard columns.count >= 2 else { return [] } - let valueIdx = (1.. idx && VizFormat.numeric($0[idx]) != nil } - } ?? 1 + let valueIdx = VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles).first?.index ?? 1 var out: [Slice] = rows.compactMap { row in guard !row.isEmpty, valueIdx < row.count, let v = VizFormat.numeric(row[valueIdx]) else { return nil } return Slice(category: VizFormat.string(row.first ?? nil), value: v) @@ -188,7 +186,7 @@ struct GaugeChartView: View { var columnTypes: [NodeTypeLabel] = [] private var value: Double? { - rows.first?.compactMap { VizFormat.numeric($0) }.first + VizFormat.firstNumeric(inFirstRowOf: rows) } /// A "max" from a second numeric column named max/limit/total, else a nice upper bound. @@ -254,7 +252,7 @@ struct HeatmapChartView: View { } private var isTemporalX: Bool { - columnTypes.first == .timestamp || rows.first?.first is Date + VizFormat.isTemporalFirstColumn(columnTypes: columnTypes, rows: rows) } private var cells: [Cell] { diff --git a/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift index f5ba2ff8..5d0c8cb8 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/AssistantAPI.swift @@ -33,6 +33,64 @@ public struct AssistantConfig: Sendable { apiKey: key ) } + + /// The provider/daemon base URL, defaulting to api.openai.com for a local assistant + /// with no explicit base. Trailing slash stripped. + public var resolvedBaseURL: String { + let base = (baseURL?.isEmpty == false ? baseURL! : "https://api.openai.com/v1") + return base.hasSuffix("/") ? String(base.dropLast()) : base + } +} + +/// Fetch the available model ids from the assistant provider/daemon's OpenAI-compatible +/// `GET /v1/models` endpoint (bearer-authenticated with `apiKey`). Returns the ids +/// sorted and de-duplicated. Works for both a local provider and a remote daemon, since +/// both speak the OpenAI models API. +public func fetchAssistantModels(_ config: AssistantConfig) async throws -> [String] { + guard let url = URL(string: config.resolvedBaseURL + "/models") else { + throw SequinsError.ffiError("invalid assistant base URL") + } + var request = URLRequest(url: url) + request.timeoutInterval = 15 + if let key = config.apiKey, !key.isEmpty { + request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") + } + let (data, response) = try await URLSession.shared.data(for: request) + if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { + let body = String(data: data, encoding: .utf8) ?? "" + throw SequinsError.ffiError("models request failed (HTTP \(http.statusCode)): \(body.prefix(200))") + } + struct ModelList: Decodable { + let data: [Model] + struct Model: Decodable { let id: String } + } + let decoded = try JSONDecoder().decode(ModelList.self, from: data) + let ids = decoded.data.map { $0.id } + // Keep chat/text models; drop embedding/audio/image/moderation/base-completion + // families. If filtering would drop everything (an unusual provider), fall back to + // the full list rather than showing nothing. + let chat = ids.filter(isChatCompletionModel) + return Set(chat.isEmpty ? ids : chat).sorted() +} + +/// Heuristic for whether a model id is a text/chat-completion model. The OpenAI +/// `/v1/models` list carries no capability field, so we filter by well-known id markers: +/// embeddings, audio (whisper/tts/realtime/transcribe), image (dall-e/gpt-image), +/// moderation, instruct/base-completion families. +private func isChatCompletionModel(_ id: String) -> Bool { + let lower = id.lowercased() + let excludedSubstrings = [ + "embedding", + "whisper", "tts", "audio", "transcribe", "realtime", + "dall-e", "dalle", "image", + "moderation", + "instruct", + "text-search", "code-search", "text-similarity", + ] + if excludedSubstrings.contains(where: lower.contains) { return false } + let excludedPrefixes = ["babbage", "davinci"] + if excludedPrefixes.contains(where: lower.hasPrefix) { return false } + return true } /// A server-executed tool call and its rendered result (assistant "activity"). @@ -153,6 +211,16 @@ public final class Assistant { } extension DataSource { + /// Delete a persisted conversation by id. Local data sources only; remote + /// connections throw until the daemon exposes conversation deletion. + public func deleteConversation(id: String) throws { + var errorPtr: UnsafeMutablePointer? + let ok = id.withCString { sequins_conversation_delete(rawPointer, $0, &errorPtr) } + if !ok { + throw consumeFFIError(errorPtr, fallback: .ffiError("failed to delete conversation")) + } + } + /// Construct an ``Assistant`` over this data source and provider/daemon config. public func makeAssistant(_ config: AssistantConfig) throws -> Assistant { // strdup the config strings; `sequins_assistant_new` copies them synchronously, diff --git a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift index d8d9fb99..52ad8dd5 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift @@ -216,11 +216,6 @@ extension DataSource { fileprivate func ffiError( _ errorPtr: UnsafeMutablePointer?, fallback: String ) -> SequinsError { - if let errorPtr { - let msg = String(cString: errorPtr) - sequins_string_free(errorPtr) - return SequinsError.ffiError(msg) - } - return SequinsError.ffiError(fallback) + consumeFFIError(errorPtr, fallback: .ffiError(fallback)) } } diff --git a/apps/macos/SequinsData/Sources/SequinsData/DataSource.swift b/apps/macos/SequinsData/Sources/SequinsData/DataSource.swift index 13bb5453..d133831b 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/DataSource.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/DataSource.swift @@ -1,6 +1,20 @@ import Foundation import SequinsFFI +/// Consume an FFI `char **error_out`: if it holds a message, copy it, free the C string, +/// and wrap it in a `SequinsError.ffiError`; otherwise return `fallback`. One home for the +/// `String(cString:)` + `sequins_string_free` + wrap dance every fallible FFI call repeats. +func consumeFFIError( + _ errorPtr: UnsafeMutablePointer?, fallback: SequinsError +) -> SequinsError { + if let errorPtr { + let message = String(cString: errorPtr) + sequins_string_free(errorPtr) + return SequinsError.ffiError(message) + } + return fallback +} + /// Configuration for the embedded OTLP server public struct OTLPServerConfig { /// gRPC port. Use 0 to request an OS-assigned ephemeral port. @@ -45,12 +59,7 @@ public final class DataSource { let cConfig = config.toCStruct() guard let pointer = sequins_data_source_new_local(dbPath, cConfig, &errorPtr) else { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } // Start the OTLP server @@ -81,12 +90,7 @@ public final class DataSource { var errorPtr: UnsafeMutablePointer? = nil guard let pointer = sequins_data_source_new_remote(queryURL, managementURL, &errorPtr) else { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } return DataSource(pointer: pointer) @@ -109,12 +113,7 @@ public final class DataSource { let success = sequins_management_get_health_threshold_config(pointer, &cConfig, &errorPtr) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.ffiError("Failed to get health threshold config") + throw consumeFFIError(errorPtr, fallback: .ffiError("Failed to get health threshold config")) } defer { sequins_health_threshold_config_free(cConfig) } @@ -180,12 +179,7 @@ public final class DataSource { } if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.ffiError("Failed to set health threshold config") + throw consumeFFIError(errorPtr, fallback: .ffiError("Failed to set health threshold config")) } } @@ -218,12 +212,7 @@ public final class DataSource { free(cRule.display_name) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.ffiError("Failed to add health rule") + throw consumeFFIError(errorPtr, fallback: .ffiError("Failed to add health rule")) } } @@ -244,12 +233,7 @@ public final class DataSource { ) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.ffiError("Failed to remove health rule") + throw consumeFFIError(errorPtr, fallback: .ffiError("Failed to remove health rule")) } } @@ -268,12 +252,7 @@ public final class DataSource { let count = sequins_data_source_generate_test_data(pointer, &errorPtr) if count == 0 { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.ffiError("Failed to generate test data") + throw consumeFFIError(errorPtr, fallback: .ffiError("Failed to generate test data")) } return Int(count) diff --git a/apps/macos/SequinsData/Sources/SequinsData/ManagementAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/ManagementAPI.swift index ab5621b3..7ec808e0 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/ManagementAPI.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/ManagementAPI.swift @@ -122,12 +122,7 @@ extension DataSource { ) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } } @@ -151,12 +146,7 @@ extension DataSource { ) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } return RetentionPolicy(cPolicy: cPolicy) @@ -182,12 +172,7 @@ extension DataSource { ) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } return StorageStats(cStats: cStats) @@ -208,12 +193,7 @@ extension DataSource { ) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } return deletedCount @@ -237,12 +217,7 @@ extension DataSource { ) if !success { - if let errorPtr = errorPtr { - let errorMessage = String(cString: errorPtr) - sequins_string_free(errorPtr) - throw SequinsError.ffiError(errorMessage) - } - throw SequinsError.nullPointer + throw consumeFFIError(errorPtr, fallback: .nullPointer) } return MaintenanceStats(cStats: cStats) diff --git a/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift index b1791480..99263bfe 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/SQLQueryAPI.swift @@ -33,41 +33,29 @@ extension DataSource { try executeFramedSQL(sql, sink: sink, invoke: sequins_app_state_query) } - /// Shared framed-SQL driver: builds the callback vtable and starts the stream via - /// `invoke` (either `sequins_sql_query` or `sequins_app_state_query`). - private func executeFramedSQL( + /// Shared framed driver for the snapshot (schema → data → complete) callback vtable, + /// starting the stream via `invoke`. Used by the plain-SQL path (`sequins_sql_query` / + /// `sequins_app_state_query`) and by ``executeSeQL(_:sink:)`` (`sequins_seql_query`), + /// which all share this exact vtable. `label` names the stream in the start error. + func executeFramedSQL( _ sql: String, sink: any SeQLSink, - invoke: @escaping (OpaquePointer?, UnsafePointer?, CFrameSinkVTable, UnsafeMutableRawPointer?) -> OpaquePointer? + invoke: @escaping (OpaquePointer?, UnsafePointer?, CFrameSinkVTable, UnsafeMutableRawPointer?) -> OpaquePointer?, + label: String = "SQL" ) throws -> SeQLStream { let context = SeQLContext(sink: sink) let ctxRaw = Unmanaged.passUnretained(context).toOpaque() var vtable = CFrameSinkVTable() - vtable.on_schema = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + vtable.on_schema = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - var names: [String] = [] - for i in 0...fromOpaque(ctxPtr).takeUnretainedValue() ctx.sink?.onSchema(schema) } - vtable.on_data = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + vtable.on_data = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } let frame = framePtr.pointee let table: String? = frame.table.map { String(cString: $0) } @@ -79,39 +67,23 @@ extension DataSource { } } - vtable.on_complete = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + vtable.on_complete = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - let stats = SeQLStats( - executionTimeUs: frame.execution_time_us, - rowsScanned: frame.rows_scanned, - bytesRead: frame.bytes_read, - rowsReturned: frame.rows_returned, - warningCount: frame.warning_count - ) + let stats = decodeStatsFrame(framePtr) let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() ctx.sink?.onComplete(stats) } - vtable.on_warning = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + vtable.on_warning = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - let code = UInt32(frame.code) - let message = frame.message.map { String(cString: $0) } ?? "warning" - c_warning_frame_free(UnsafeMutablePointer(mutating: framePtr)) + let (code, message) = decodeWarningFrame(framePtr) let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() ctx.sink?.onWarning(code: code, message: message) } - vtable.on_error = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in + vtable.on_error = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - let code = UInt32(frame.code) - let message = frame.message.map { String(cString: $0) } ?? "query error" - c_query_error_free(UnsafeMutablePointer(mutating: framePtr)) + let (code, message) = decodeErrorFrame(framePtr) let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() ctx.sink?.onError(code: code, message: message) } @@ -120,7 +92,7 @@ extension DataSource { invoke(rawPointer, sqlPtr, vtable, ctxRaw) } guard let streamHandle else { - throw SequinsError.ffiError("failed to start SQL query stream") + throw SequinsError.ffiError("failed to start \(label) query stream") } return SeQLStream(streamHandle, context: context) } diff --git a/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift index df5ef49c..8cf7c10c 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift @@ -19,11 +19,43 @@ public enum ResponseShape: Int { case scalar = 6 } +/// Semantic role of a result column, so renderers can tell dimensions (group +/// keys/fields) from measures (aggregations/computed). Raw values match the FFI +/// `CSchemaFrame.column_roles` codes. +public enum SeQLColumnRole: UInt32, Sendable { + case groupKey = 0 + case aggregation = 1 + case field = 2 + case computed = 3 + case navigation = 4 + case traceGroup = 5 + case rowId = 6 + + /// A numeric value to plot (an aggregate/derived quantity), not a category. + public var isMeasure: Bool { self == .aggregation || self == .computed } + /// A category/key to group or split by (group keys and projected fields). + public var isDimension: Bool { self == .groupKey || self == .field } +} + /// Schema received before data rows public struct SeQLSchema { public let shape: ResponseShape public let columnNames: [String] + /// Per-column semantic role (parallel to `columnNames`), empty if unavailable. + public let columnRoles: [SeQLColumnRole] public let initialWatermarkNs: UInt64 + + public init( + shape: ResponseShape, + columnNames: [String], + columnRoles: [SeQLColumnRole] = [], + initialWatermarkNs: UInt64 + ) { + self.shape = shape + self.columnNames = columnNames + self.columnRoles = columnRoles + self.initialWatermarkNs = initialWatermarkNs + } } /// Query execution statistics @@ -339,6 +371,68 @@ func decodeIPC(data dataPtr: UnsafeMutablePointer?, length: Int) -> [Reco } } +// MARK: - Frame Decode Helpers +// +// Each takes a borrowed C frame pointer, builds the Swift value, and frees the frame +// where the C side heap-allocated it (schema/warning/error frames; the complete frame is +// stack-allocated and needs no free). Shared by the snapshot (`executeFramedSQL`) and +// live (`executeLiveSeQL`) callback vtables so the decode + ownership rules live in one +// place. + +/// Decode and free a schema frame into a `SeQLSchema`. +func decodeSchemaFrame(_ framePtr: UnsafePointer) -> SeQLSchema { + let frame = framePtr.pointee + var names: [String] = [] + var roles: [SeQLColumnRole] = [] + for i in 0..) -> SeQLStats { + let frame = framePtr.pointee + return SeQLStats( + executionTimeUs: frame.execution_time_us, + rowsScanned: frame.rows_scanned, + bytesRead: frame.bytes_read, + rowsReturned: frame.rows_returned, + warningCount: frame.warning_count + ) +} + +/// Decode and free a warning frame into its `(code, message)`. +func decodeWarningFrame(_ framePtr: UnsafePointer) -> (code: UInt32, message: String) { + let frame = framePtr.pointee + let code = UInt32(frame.code) + let message = frame.message.map { String(cString: $0) } ?? "warning" + c_warning_frame_free(UnsafeMutablePointer(mutating: framePtr)) + return (code, message) +} + +/// Decode and free a query-error frame into its `(code, message)`. +func decodeErrorFrame(_ framePtr: UnsafePointer) -> (code: UInt32, message: String) { + let frame = framePtr.pointee + let code = UInt32(frame.code) + let message = frame.message.map { String(cString: $0) } ?? "query error" + c_query_error_free(UnsafeMutablePointer(mutating: framePtr)) + return (code, message) +} + // MARK: - DataSource Extension extension DataSource { @@ -379,119 +473,12 @@ extension DataSource { /// - Throws: `SequinsError` on failures (parse errors are reported via sink.onError) @discardableResult public func executeSeQL(_ query: String, sink: any SeQLSink) throws -> SeQLStream { - return try withSpan("DataSource.executeSeQL") { _ in - let context = SeQLContext(sink: sink) - let ctxRaw = Unmanaged.passUnretained(context).toOpaque() - - var vtable = CFrameSinkVTable() - - // Schema callback — decode synchronously, free C memory, then call sink - vtable.on_schema = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in - guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - - var names: [String] = [] - for i in 0...fromOpaque(ctxPtr).takeUnretainedValue() - ctx.sink?.onSchema(schema) - } - - // Data callback — decode Arrow IPC bytes, deliver as RecordBatch to sink - vtable.on_data = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in - guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - let table: String? = frame.table.map { String(cString: $0) } - let batches = decodeIPC(data: frame.ipc_data, length: Int(frame.ipc_len)) - c_data_frame_free(UnsafeMutablePointer(mutating: framePtr)) - - let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() - for batch in batches { - ctx.sink?.onBatch(batch, table: table) - } - } - - // Complete callback — stack-allocated frame, no free needed - vtable.on_complete = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in - guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - - let stats = SeQLStats( - executionTimeUs: frame.execution_time_us, - rowsScanned: frame.rows_scanned, - bytesRead: frame.bytes_read, - rowsReturned: frame.rows_returned, - warningCount: frame.warning_count - ) - - let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() - ctx.sink?.onComplete(stats) - } - - // Warning callback — heap-allocated, must free - vtable.on_warning = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in - guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - - let code = UInt32(frame.code) - let message: String - if let cStr = frame.message { - message = String(cString: cStr) - } else { - message = "warning" - } - c_warning_frame_free(UnsafeMutablePointer(mutating: framePtr)) - - let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() - ctx.sink?.onWarning(code: code, message: message) + // The SeQL snapshot path shares the exact schema→data→complete callback vtable + // with the plain-SQL path, so it reuses the shared framed driver — the only + // difference is the FFI entry point (`sequins_seql_query`). + try withSpan("DataSource.executeSeQL") { _ in + try executeFramedSQL(query, sink: sink, invoke: sequins_seql_query, label: "SeQL") } - - // Error callback — heap-allocated, must free - vtable.on_error = { - (framePtr: UnsafePointer?, ctxPtr: UnsafeMutableRawPointer?) -> Void in - guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - - let code = UInt32(frame.code) - let message: String - if let cStr = frame.message { - message = String(cString: cStr) - } else { - message = "query error" - } - c_query_error_free(UnsafeMutablePointer(mutating: framePtr)) - - let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() - ctx.sink?.onError(code: code, message: message) - } - - // Convert Swift String to C string explicitly - let streamHandle = query.withCString { queryPtr in - sequins_seql_query(rawPointer, queryPtr, vtable, ctxRaw) - } - - guard let streamHandle else { - throw SequinsError.ffiError("failed to start SeQL query stream") - } - - return SeQLStream(streamHandle, context: context) - } // end withSpan("DataSource.executeSeQL") } /// Execute a SeQL query in live streaming mode, returning an observable stream. @@ -514,23 +501,7 @@ extension DataSource { // Schema callback vtable.on_schema = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - - var names: [String] = [] - for i in 0...fromOpaque(ctxPtr).takeUnretainedValue() DispatchQueue.main.async { ctx.stream?.applySchema(schema) } } @@ -594,14 +565,7 @@ extension DataSource { // Complete callback vtable.on_complete = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - let stats = SeQLStats( - executionTimeUs: frame.execution_time_us, - rowsScanned: frame.rows_scanned, - bytesRead: frame.bytes_read, - rowsReturned: frame.rows_returned, - warningCount: frame.warning_count - ) + let stats = decodeStatsFrame(framePtr) let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() DispatchQueue.main.async { ctx.stream?.applyComplete(stats) } } @@ -609,29 +573,14 @@ extension DataSource { // Warning callback vtable.on_warning = { (framePtr, _) in guard let framePtr else { return } - let frame = framePtr.pointee - let message: String - if let cStr = frame.message { - message = String(cString: cStr) - } else { - message = "warning" - } - c_warning_frame_free(UnsafeMutablePointer(mutating: framePtr)) + let (_, message) = decodeWarningFrame(framePtr) logger.warning("LiveSeQL warning", metadata: ["message": "\(message)"]) } // Error callback vtable.on_error = { (framePtr, ctxPtr) in guard let framePtr, let ctxPtr else { return } - let frame = framePtr.pointee - let code = UInt32(frame.code) - let message: String - if let cStr = frame.message { - message = String(cString: cStr) - } else { - message = "query error" - } - c_query_error_free(UnsafeMutablePointer(mutating: framePtr)) + let (code, message) = decodeErrorFrame(framePtr) let ctx = Unmanaged.fromOpaque(ctxPtr).takeUnretainedValue() DispatchQueue.main.async { ctx.stream?.applyError(code: code, message: message) } } diff --git a/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift b/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift index 94e0ead8..9b50d47a 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/VizFormat.swift @@ -181,4 +181,45 @@ public enum VizFormat { } return words.joined(separator: " ") } + + // MARK: - Data-shape helpers (shared across chart renderers) + + /// The numeric "value" columns of a result — the series to plot. + /// + /// When column `roles` are known, only **measures** (aggregations/computed) count as + /// values, so a numeric *dimension* (e.g. `http_status_code`) is never mistaken for a + /// data series. Without roles it falls back to "every column after the first that + /// carries numbers." A column is only included if it actually contains numeric data. + public static func valueColumns( + columns: [String], rows: [[Any?]], roles: [SeQLColumnRole] = [] + ) -> [(index: Int, name: String)] { + func carriesNumbers(_ idx: Int) -> Bool { + rows.contains { $0.count > idx && numeric($0[idx]) != nil } + } + if !roles.isEmpty { + let measures: [(index: Int, name: String)] = (0.. 1 else { return [] } + return (1.. Bool { + columnTypes.first == .timestamp || rows.first?.first is Date + } + + /// The first numeric value in the first row (the scalar behind stats/gauges). + public static func firstNumeric(inFirstRowOf rows: [[Any?]]) -> Double? { + rows.first?.compactMap { numeric($0) }.first + } } diff --git a/apps/macos/SequinsData/Sources/SequinsData/VizType.swift b/apps/macos/SequinsData/Sources/SequinsData/VizType.swift index 00deb3bb..793782b5 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/VizType.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/VizType.swift @@ -52,18 +52,6 @@ public enum VizType: String, CaseIterable, Codable, Sendable { } } - /// Whether this type is a good fit for the given result (used to gray out - /// obviously-wrong choices in the picker). Permissive by default. - public func isSuitable(columnCount: Int, rowCount: Int) -> Bool { - switch self { - case .stat, .gauge: return columnCount >= 1 - case .pie: return columnCount >= 2 - case .line, .area, .bar, .stackedBar: return columnCount >= 2 - case .heatmap: return columnCount >= 3 - case .table, .trace: return true - } - } - /// Parse a stored `shape` string into a `VizType`, accepting both `VizType` raw /// values and legacy `ResponseShape` strings (e.g. "timeseries", "trace_tree"). public static func from(shapeString: String?) -> VizType? { @@ -85,9 +73,26 @@ public enum VizType: String, CaseIterable, Codable, Sendable { } } - /// Choose a default `VizType` from the Rust-inferred shape and the result columns. + /// Whether this type plots numeric measures (so an absence of any measure/numeric + /// column means it can't render and should fall back to a table). + public var plotsMeasures: Bool { + switch self { + case .line, .area, .bar, .stackedBar, .pie, .gauge, .heatmap: return true + case .stat, .table, .trace: return false + } + } + + /// Choose a default `VizType` from the Rust-inferred shape, the result columns, and + /// (when available) their semantic roles. + /// + /// Roles make table-shaped results reliable: a grouped aggregation like + /// `group by { http_route, http_status_code } { count() }` has two *dimensions* and + /// one *measure* — that's a heatmap (dim × dim → value), not a broken line/bar that + /// mistakes `http_status_code` for a data series. When roles are absent we fall back + /// to a conservative column-count heuristic; either way an unplottable result becomes + /// a table rather than an empty chart. public static func autoSelect( - shape: ResponseShape, columns: [String], rows: [[Any?]] + shape: ResponseShape, columns: [String], rows: [[Any?]], roles: [SeQLColumnRole] = [] ) -> VizType { switch shape { case .timeSeries: return .line @@ -96,8 +101,16 @@ public enum VizType: String, CaseIterable, Codable, Sendable { case .heatmap: return .heatmap case .patternGroups: return .table case .table: - // A compact two-column (category + one value) result reads well as a bar - // chart; anything wider or larger stays a table. + if !roles.isEmpty { + let dimensions = roles.filter { $0.isDimension }.count + let measures = roles.filter { $0.isMeasure }.count + if measures == 0 { return .table } + if dimensions >= 2 && measures == 1 { return .heatmap } + if dimensions == 1 && rows.count > 1 && rows.count <= 24 { return .bar } + return .table + } + // No roles: a compact two-column (category + one value) result reads well as + // a bar chart; anything wider or larger stays a table. if columns.count == 2, rows.count <= 24, rows.count > 1 { return .bar } From 1c85a0a0a49de73982068b96888a9411d204cd6e Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 21 Jul 2026 18:19:56 +0800 Subject: [PATCH 06/10] feat(assistant): metric labels + deeper column/sample profiling - metric_labels / metric_label_values: enumerate the per-series label dimensions a metric is broken down by, from the series index (metric attributes aren't in the SQL tables). New SeriesIndex::{metric_names,label_keys,label_values}; Tools gains an optional series-index handle (with_series_index), wired from the local cold tier. - column_profile: numeric quantiles (mean/stddev/p50/p90/p95/p99) + optional `filter` scope. - sample: optional `columns` projection, `filter`, and `order_by`. - describe_schema: point _overflow_attrs at list_attributes/attribute_values. - Grounding notes the metric-label tools. Co-Authored-By: Claude Opus 4.8 (1M context) --- crates/sequins-assistant/Cargo.toml | 1 + crates/sequins-assistant/src/model.rs | 4 +- crates/sequins-assistant/src/tools/ops.rs | 193 +++++++++++++++++- .../sequins-assistant/src/tools/registry.rs | 19 +- crates/sequins-ffi/src/assistant.rs | 12 +- crates/sequins-series-index/src/lib.rs | 64 +++++- 6 files changed, 278 insertions(+), 15 deletions(-) diff --git a/crates/sequins-assistant/Cargo.toml b/crates/sequins-assistant/Cargo.toml index 656c6229..74edfd3c 100644 --- a/crates/sequins-assistant/Cargo.toml +++ b/crates/sequins-assistant/Cargo.toml @@ -14,6 +14,7 @@ sequins-flight = { workspace = true } sequins-traits = { workspace = true } sequins-arrow-schema = { workspace = true } sequins-metadata = { workspace = true } +sequins-series-index = { workspace = true } seql-parser = { workspace = true } seql-ast = { workspace = true } diff --git a/crates/sequins-assistant/src/model.rs b/crates/sequins-assistant/src/model.rs index 69cfa0f5..63500a77 100644 --- a/crates/sequins-assistant/src/model.rs +++ b/crates/sequins-assistant/src/model.rs @@ -438,7 +438,9 @@ Prefer discovery tools over guessing — observability data is dominated by attr - `list_attributes(table)` — the real attribute keys present (promoted + custom). Call this before filtering on `attr.`; don't guess key names. - `attribute_values(table, key)` — the actual values of a key (e.g. which `http.route`s exist). -- `list_metrics` — metric names/types/units; `describe_schema(table)` for columns. +- `list_metrics` — metric names/types/units; `metric_labels(metric?)` / + `metric_label_values(key, metric?)` — the label dimensions a metric is split by + (not in the SQL tables). `describe_schema(table)` for columns. - To keep rows where a field is present, write `where http_route != null` (it means IS NOT NULL). Bare promoted attrs (e.g. `http_route`, `http_status_code`) are real columns. diff --git a/crates/sequins-assistant/src/tools/ops.rs b/crates/sequins-assistant/src/tools/ops.rs index b82250d7..4b0beff7 100644 --- a/crates/sequins-assistant/src/tools/ops.rs +++ b/crates/sequins-assistant/src/tools/ops.rs @@ -30,8 +30,10 @@ use sequins_flight::{decode_metadata, ipc_to_batch, SeqlMetadata}; use sequins_metadata::{ Dashboard, DashboardApi, DashboardRow, RowPanel, SavedVisualization, DEFAULT_ROW_HEIGHT, }; +use sequins_series_index::SeriesIndex; use sequins_traits::QueryApi; use serde::{Deserialize, Serialize}; +use tokio::sync::RwLock; /// Default number of rows returned by `sample` and rendered by `run_sql`/`run_seql`. const DEFAULT_ROWS: usize = 10; @@ -56,6 +58,8 @@ pub enum OpError { Arrow(#[from] arrow::error::ArrowError), #[error("dashboard editing is not available for this connection")] DashboardsUnavailable, + #[error("metric label enumeration is not available for this connection")] + MetricLabelsUnavailable, #[error("no dashboard matching '{key}' — use list_dashboards to see ids/titles")] UnknownDashboard { key: String }, #[error("no chart at [row {row}, column {column}] — use get_dashboard to see indices")] @@ -89,6 +93,9 @@ pub struct ColumnProfileArgs { /// How many most-frequent values to list (default 10). #[serde(default)] pub top_k: Option, + /// Optional SQL predicate to scope the profile (e.g. `http_status_code >= 500`). + #[serde(default)] + pub filter: Option, } /// Arguments for `time_range`. @@ -106,6 +113,15 @@ pub struct SampleArgs { /// Number of rows to return (default 10, max 100). #[serde(default)] pub limit: Option, + /// Optional columns to project (default: all). Narrow wide tables to what matters. + #[serde(default)] + pub columns: Option>, + /// Optional SQL predicate to filter rows (e.g. `status == 2`). + #[serde(default)] + pub filter: Option, + /// Optional `ORDER BY` clause (e.g. `start_time_unix_nano DESC` for the latest rows). + #[serde(default)] + pub order_by: Option, } /// Arguments for `explain`. @@ -142,6 +158,24 @@ pub struct RunSeqlArgs { pub sample_rows: Option, } +/// Arguments for `metric_labels`. +#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] +pub struct MetricLabelsArgs { + /// Restrict to one metric name (default: all metrics). + #[serde(default)] + pub metric: Option, +} + +/// Arguments for `metric_label_values`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct MetricLabelValuesArgs { + /// The label key whose values to list (e.g. `http.route`). + pub key: String, + /// Restrict to one metric name (default: all metrics). + #[serde(default)] + pub metric: Option, +} + /// Arguments for `overview` (none). #[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] pub struct OverviewArgs {} @@ -298,6 +332,9 @@ pub struct Tools { /// Pro daemon both have a `DashboardApi`). Absent ⇒ dashboard tools report they're /// unavailable rather than failing opaquely. dashboards: Option>, + /// The metric series index, for enumerating per-series labels (metric attributes + /// aren't in the SQL tables). Absent ⇒ metric-label tools report unavailable. + series_index: Option>>, } impl Tools { @@ -306,6 +343,7 @@ impl Tools { Self { backend, dashboards: None, + series_index: None, } } @@ -315,12 +353,24 @@ impl Tools { self } + /// Attach the metric series index so the assistant can enumerate metric labels. + pub fn with_series_index(mut self, series_index: Arc>) -> Self { + self.series_index = Some(series_index); + self + } + fn dashboard_api(&self) -> Result<&Arc, OpError> { self.dashboards .as_ref() .ok_or(OpError::DashboardsUnavailable) } + fn series_index(&self) -> Result<&Arc>, OpError> { + self.series_index + .as_ref() + .ok_or(OpError::MetricLabelsUnavailable) + } + async fn ctx(&self) -> Result { Ok(self.backend.session().await?) } @@ -350,7 +400,11 @@ impl Tools { args.table, schema.fields().len() ); + let mut has_overflow = false; for f in schema.fields() { + if f.name() == "_overflow_attrs" { + has_overflow = true; + } out.push_str(&format!( "- {}: {}{}\n", f.name(), @@ -358,10 +412,18 @@ impl Tools { if f.is_nullable() { " (nullable)" } else { "" } )); } + if has_overflow { + out.push_str( + "\nPromoted attributes (e.g. http_route, http_status_code) are typed columns; \ + custom attributes live in `_overflow_attrs` — use list_attributes / \ + attribute_values to discover keys and values.\n", + ); + } Ok(out) } - /// Profile a column: total/non-null/approx-distinct, min/max, and top-k values. + /// Profile a column: total/non-null/approx-distinct, min/max, numeric quantiles, and + /// top-k values — optionally scoped by a `filter` predicate. pub async fn column_profile(&self, args: ColumnProfileArgs) -> Result { validate_table(&args.table)?; let ctx = self.ctx().await?; @@ -371,20 +433,33 @@ impl Tools { let t = quote_ident(&args.table); let c = quote_ident(&args.column); let top_k = args.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_ROWS); + let where_clause = args + .filter + .as_ref() + .map(|f| format!(" WHERE {f}")) + .unwrap_or_default(); + let is_numeric = self + .column_is_numeric(&ctx, &args.table, &args.column) + .await; let mut out = format!("Profile of `{}`.`{}`:\n", args.table, args.column); + if !where_clause.is_empty() { + out.push_str(&format!("(scope:{where_clause})\n")); + } // Row counts always work for any column type — kept separate from // approx_distinct so an unsupported type (e.g. Float64, which DataFusion's // HyperLogLog can't hash) doesn't hide the counts too. - let counts_sql = format!("SELECT count(*) AS total_rows, count({c}) AS non_null FROM {t}"); + let counts_sql = + format!("SELECT count(*) AS total_rows, count({c}) AS non_null FROM {t}{where_clause}"); match self.query_readonly(&ctx, &counts_sql, MAX_ROWS).await { Ok(batches) => out.push_str(&render_batches(&batches)?), Err(e) => out.push_str(&format!("(counts unavailable: {e})\n")), } // Approximate distinct cardinality — best effort; unsupported for some types. - let distinct_sql = format!("SELECT approx_distinct({c}) AS approx_distinct FROM {t}"); + let distinct_sql = + format!("SELECT approx_distinct({c}) AS approx_distinct FROM {t}{where_clause}"); match self.query_readonly(&ctx, &distinct_sql, MAX_ROWS).await { Ok(batches) => { out.push_str("\nApprox distinct:\n"); @@ -393,14 +468,29 @@ impl Tools { Err(_) => out.push_str("\nApprox distinct: unavailable for this column type.\n"), } - let minmax_sql = format!("SELECT min({c}) AS min, max({c}) AS max FROM {t}"); + let minmax_sql = format!("SELECT min({c}) AS min, max({c}) AS max FROM {t}{where_clause}"); if let Ok(batches) = self.query_readonly(&ctx, &minmax_sql, MAX_ROWS).await { out.push_str("\nRange:\n"); out.push_str(&render_batches(&batches)?); } + // Numeric distribution — quantiles + mean/stddev — for number-typed columns. + if is_numeric { + let quant_sql = format!( + "SELECT avg({c}) AS mean, stddev({c}) AS stddev, \ + approx_percentile_cont({c}, 0.5) AS p50, approx_percentile_cont({c}, 0.9) AS p90, \ + approx_percentile_cont({c}, 0.95) AS p95, approx_percentile_cont({c}, 0.99) AS p99 \ + FROM {t}{where_clause}" + ); + if let Ok(batches) = self.query_readonly(&ctx, &quant_sql, MAX_ROWS).await { + out.push_str("\nDistribution:\n"); + out.push_str(&render_batches(&batches)?); + } + } + let topk_sql = format!( - "SELECT {c} AS value, count(*) AS n FROM {t} GROUP BY {c} ORDER BY n DESC LIMIT {top_k}" + "SELECT {c} AS value, count(*) AS n FROM {t}{where_clause} \ + GROUP BY {c} ORDER BY n DESC LIMIT {top_k}" ); match self.query_readonly(&ctx, &topk_sql, top_k).await { Ok(batches) => { @@ -412,6 +502,18 @@ impl Tools { Ok(out) } + /// Whether a column's Arrow type is numeric (so quantiles/mean apply). + async fn column_is_numeric(&self, ctx: &SessionContext, table: &str, column: &str) -> bool { + let Ok(df) = ctx.table(table).await else { + return false; + }; + df.schema() + .as_arrow() + .field_with_name(column) + .map(|f| f.data_type().is_numeric()) + .unwrap_or(false) + } + /// Report the min/max of a table's time column (nanoseconds since epoch). pub async fn time_range(&self, args: TimeRangeArgs) -> Result { let signal = validate_table(&args.table)?; @@ -432,12 +534,39 @@ impl Tools { )) } - /// Return up to `limit` sample rows from a table. + /// Return up to `limit` sample rows from a table, optionally projected to specific + /// `columns`, filtered by a predicate, and ordered. pub async fn sample(&self, args: SampleArgs) -> Result { validate_table(&args.table)?; let limit = args.limit.unwrap_or(DEFAULT_ROWS).clamp(1, MAX_ROWS); let ctx = self.ctx().await?; - let sql = format!("SELECT * FROM {} LIMIT {limit}", quote_ident(&args.table)); + + let projection = match &args.columns { + Some(cols) if !cols.is_empty() => { + for col in cols { + self.validate_column(&ctx, &args.table, col).await?; + } + cols.iter() + .map(|c| quote_ident(c)) + .collect::>() + .join(", ") + } + _ => "*".to_string(), + }; + let where_clause = args + .filter + .as_ref() + .map(|f| format!(" WHERE {f}")) + .unwrap_or_default(); + let order_clause = args + .order_by + .as_ref() + .map(|o| format!(" ORDER BY {o}")) + .unwrap_or_default(); + let sql = format!( + "SELECT {projection} FROM {}{where_clause}{order_clause} LIMIT {limit}", + quote_ident(&args.table) + ); let batches = self.query_readonly(&ctx, &sql, limit).await?; Ok(format!( "Up to {limit} rows from `{}`:\n{}", @@ -616,6 +745,50 @@ impl Tools { )) } + /// The label (per-series attribute) keys carried by metrics — e.g. which dimensions a + /// request-count metric is broken down by. From the series index, optionally per metric. + pub async fn metric_labels(&self, args: MetricLabelsArgs) -> Result { + let index = self.series_index()?.read().await; + let keys = index.label_keys(args.metric.as_deref()); + let scope = args + .metric + .as_deref() + .map(|m| format!(" for metric `{m}`")) + .unwrap_or_default(); + if keys.is_empty() { + return Ok(format!("No metric labels found{scope}.")); + } + Ok(format!( + "Metric label keys{scope}:\n{}\nUse metric_label_values(key) for their values.", + keys.iter() + .map(|k| format!("- {k}")) + .collect::>() + .join("\n") + )) + } + + /// The distinct values a metric label key takes (optionally within one metric). + pub async fn metric_label_values( + &self, + args: MetricLabelValuesArgs, + ) -> Result { + let index = self.series_index()?.read().await; + let values = index.label_values(&args.key, args.metric.as_deref()); + if values.is_empty() { + return Ok(format!("No values found for metric label `{}`.", args.key)); + } + Ok(format!( + "Values of metric label `{}`:\n{}", + args.key, + values + .iter() + .take(MAX_ROWS) + .map(|v| format!("- {v}")) + .collect::>() + .join("\n") + )) + } + /// Enumerate the attribute keys present in a table: promoted (populated) columns /// plus the most common overflow-map keys; or resource/scope attribute keys. pub async fn list_attributes(&self, args: ListAttributesArgs) -> Result { @@ -1152,6 +1325,7 @@ mod tests { table: "datapoints".into(), column: "value".into(), top_k: Some(3), + filter: None, }) .await .unwrap(); @@ -1203,6 +1377,9 @@ mod tests { .sample(SampleArgs { table: "spans".into(), limit: Some(3), + columns: None, + filter: None, + order_by: None, }) .await .unwrap(); @@ -1231,6 +1408,7 @@ mod tests { table: "spans".into(), column: "name".into(), top_k: Some(3), + filter: None, }) .await .unwrap(); @@ -1246,6 +1424,7 @@ mod tests { table: "spans".into(), column: "not_a_col".into(), top_k: None, + filter: None, }) .await .unwrap_err(); diff --git a/crates/sequins-assistant/src/tools/registry.rs b/crates/sequins-assistant/src/tools/registry.rs index 55205456..16ca74c5 100644 --- a/crates/sequins-assistant/src/tools/registry.rs +++ b/crates/sequins-assistant/src/tools/registry.rs @@ -16,8 +16,9 @@ use serde::de::DeserializeOwned; use super::ops::{ AddChartArgs, ArrangeDashboardArgs, AttributeValuesArgs, ColumnProfileArgs, CreateDashboardArgs, DescribeSchemaArgs, ExplainArgs, GetDashboardArgs, ListAttributesArgs, - ListDashboardsArgs, ListMetricsArgs, ListTablesArgs, OverviewArgs, RenameDashboardArgs, - RunSeqlArgs, RunSqlArgs, SampleArgs, TimeRangeArgs, UpdateChartArgs, ValidateSeqlArgs, + ListDashboardsArgs, ListMetricsArgs, ListTablesArgs, MetricLabelValuesArgs, MetricLabelsArgs, + OverviewArgs, RenameDashboardArgs, RunSeqlArgs, RunSqlArgs, SampleArgs, TimeRangeArgs, + UpdateChartArgs, ValidateSeqlArgs, }; use super::{OpError, Tools}; @@ -40,6 +41,8 @@ pub const TOOL_NAMES: &[&str] = &[ "list_attributes", "attribute_values", "list_metrics", + "metric_labels", + "metric_label_values", "column_profile", "time_range", "sample", @@ -98,6 +101,16 @@ pub fn specs() -> Vec { description: "List available metrics with their type, unit, and series cardinality. Use before charting a metric.", parameters: schema::(), }, + ToolSpec { + name: "metric_labels", + description: "The per-series label keys a metric is broken down by (metric attributes aren't in the SQL tables). Optionally scope to one metric.", + parameters: schema::(), + }, + ToolSpec { + name: "metric_label_values", + description: "The distinct values a metric label key takes (optionally within one metric).", + parameters: schema::(), + }, ToolSpec { name: "column_profile", description: "Profile a column: total/non-null counts, approximate distinct cardinality, min/max, and the most frequent values.", @@ -204,6 +217,8 @@ pub async fn invoke(tools: &Tools, name: &str, args: serde_json::Value) -> Resul "list_attributes" => tools.list_attributes(parse(args)?).await, "attribute_values" => tools.attribute_values(parse(args)?).await, "list_metrics" => tools.list_metrics(parse(args)?).await, + "metric_labels" => tools.metric_labels(parse(args)?).await, + "metric_label_values" => tools.metric_label_values(parse(args)?).await, "column_profile" => tools.column_profile(parse(args)?).await, "time_range" => tools.time_range(parse(args)?).await, "sample" => tools.sample(parse(args)?).await, diff --git a/crates/sequins-ffi/src/assistant.rs b/crates/sequins-ffi/src/assistant.rs index 8c3c329b..64de139c 100644 --- a/crates/sequins-ffi/src/assistant.rs +++ b/crates/sequins-ffi/src/assistant.rs @@ -153,11 +153,15 @@ pub unsafe extern "C" fn sequins_assistant_new( return std::ptr::null_mut(); } }; - // Give the tool layer the local dashboard store so the assistant can read and - // edit dashboards (`Storage` implements `DashboardApi`). + // Give the tool layer the local dashboard store (Storage implements + // DashboardApi) and the metric series index, so the assistant can edit + // dashboards and enumerate metric labels. let dashboards: Arc = storage.clone(); - let tools = - sequins_assistant::Tools::new(Arc::clone(backend)).with_dashboards(dashboards); + let series_index = RUNTIME + .block_on(async { storage.cold_tier_arc().read().await.series_index.clone() }); + let tools = sequins_assistant::Tools::new(Arc::clone(backend)) + .with_dashboards(dashboards) + .with_series_index(series_index); let model = sequins_assistant::SequinsAssistantModel::new(backing, tools); Assistant::local(model, Some(Arc::clone(storage.app_state()))) } diff --git a/crates/sequins-series-index/src/lib.rs b/crates/sequins-series-index/src/lib.rs index 4a415825..eb75a081 100644 --- a/crates/sequins-series-index/src/lib.rs +++ b/crates/sequins-series-index/src/lib.rs @@ -10,7 +10,7 @@ pub mod error; use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use crate::error::{Error, Result}; @@ -152,6 +152,32 @@ impl SeriesIndex { self.reverse_map.get(&id) } + /// Distinct metric names present in the index. + pub fn metric_names(&self) -> BTreeSet { + self.reverse_map + .values() + .map(|m| m.metric_name.clone()) + .collect() + } + + /// Distinct label keys across series, optionally scoped to one metric. + pub fn label_keys(&self, metric: Option<&str>) -> BTreeSet { + self.reverse_map + .values() + .filter(|m| metric.map_or(true, |name| m.metric_name == name)) + .flat_map(|m| m.attributes.keys().cloned()) + .collect() + } + + /// Distinct values for a label key, optionally scoped to one metric. + pub fn label_values(&self, key: &str, metric: Option<&str>) -> BTreeSet { + self.reverse_map + .values() + .filter(|m| metric.map_or(true, |name| m.metric_name == name)) + .filter_map(|m| m.attributes.get(key).cloned()) + .collect() + } + /// Find all series matching a metric name and label filters /// /// Returns the intersection of series matching all filters. @@ -357,6 +383,42 @@ mod tests { .collect() } + #[test] + fn test_label_enumeration() { + let mut index = SeriesIndex::new(); + index.register( + "http_requests", + create_attrs(&[("method", "GET"), ("route", "/a")]), + ); + index.register( + "http_requests", + create_attrs(&[("method", "POST"), ("route", "/b")]), + ); + index.register("cpu_seconds", create_attrs(&[("core", "0")])); + + assert_eq!( + index.metric_names(), + ["cpu_seconds".to_string(), "http_requests".to_string()] + .into_iter() + .collect() + ); + // All label keys, and scoped to one metric. + assert!(index.label_keys(None).contains("route")); + assert!(index.label_keys(None).contains("core")); + assert_eq!( + index.label_keys(Some("http_requests")), + ["method".to_string(), "route".to_string()] + .into_iter() + .collect() + ); + // Values for a key, scoped to a metric. + assert_eq!( + index.label_values("route", Some("http_requests")), + ["/a".to_string(), "/b".to_string()].into_iter().collect() + ); + assert!(index.label_values("core", Some("http_requests")).is_empty()); + } + #[test] fn test_series_registration() { let mut index = SeriesIndex::new(); From d0f8af07df387a0cece790a8ac8894ee2e54250d Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 21 Jul 2026 18:57:41 +0800 Subject: [PATCH 07/10] feat(assistant): recommend_chart tool + chart presentation options Add a `recommend_chart(query)` server tool that runs a SeQL query and suggests the best chart type from its result shape/roles, plus a `VisualizationOptions` presentation blob (unit, y_scale/log, y_min/max, stacked, legend, series_limit, thresholds) threaded end-to-end: - metadata: `VisualizationOptions`/`Threshold` on `SavedVisualization` (additive, omitted-when-empty serde). - assistant: `add_chart`/`update_chart` accept `options`; `render_dashboard` surfaces them; grounding teaches recommend_chart + options. - ffi/swift: mirror the options model in `DashboardStore`, parse them in the inline `render_visualization` client tool, and honor them in the renderers (log/explicit y-scale, unit labels, legend, series cap, threshold rules, bar stacking) via a propagating `chartYPresentation` modifier. Tests: assistant recommend_chart + options round-trip; metadata + SequinsData options coding. All green; macOS app builds. Co-Authored-By: Claude Opus 4.8 (1M context) --- Cargo.lock | 1 + .../ViewModels/AssistantViewModel.swift | 55 +++- .../Views/Explore/ExploreTimeSeriesView.swift | 3 +- .../Views/Visualization/TimeSeriesChart.swift | 106 +++++++- .../Visualization/VisualizationView.swift | 34 ++- .../Views/Visualization/VizCharts.swift | 69 +++-- .../Sources/SequinsData/DashboardStore.swift | 133 ++++++++- .../SequinsDataTests/DashboardVizTests.swift | 41 +++ crates/sequins-assistant/src/model.rs | 29 +- crates/sequins-assistant/src/tools/ops.rs | 254 +++++++++++++++++- .../sequins-assistant/src/tools/registry.rs | 11 +- crates/sequins-metadata/src/lib.rs | 2 +- crates/sequins-metadata/src/store.rs | 1 + crates/sequins-metadata/src/types.rs | 55 ++++ 14 files changed, 749 insertions(+), 45 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 936b770d..77228bd8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6023,6 +6023,7 @@ dependencies = [ "sequins-datafusion-backend", "sequins-flight", "sequins-metadata", + "sequins-series-index", "sequins-storage", "sequins-traits", "serde", diff --git a/apps/macos/Sequins/ViewModels/AssistantViewModel.swift b/apps/macos/Sequins/ViewModels/AssistantViewModel.swift index 99a3f9d2..602abc4b 100644 --- a/apps/macos/Sequins/ViewModels/AssistantViewModel.swift +++ b/apps/macos/Sequins/ViewModels/AssistantViewModel.swift @@ -393,7 +393,34 @@ final class AssistantViewModel { guard !seql.isEmpty else { return nil } let title = (obj["title"] as? String) ?? "Visualization" let shape = (obj["chart_type"] as? String) ?? (obj["shape"] as? String) - return SavedVisualization(seql: seql, title: title, shape: shape) + let options = Self.parseOptions(from: obj["options"]) + return SavedVisualization(seql: seql, title: title, shape: shape, options: options) + } + + /// Parse a presentation-options object (snake_case, as the model emits it) into a + /// `VisualizationOptions`. Missing/invalid fields fall back to unset. + static func parseOptions(from raw: Any?) -> VisualizationOptions { + guard let obj = raw as? [String: Any] else { return VisualizationOptions() } + func dbl(_ k: String) -> Double? { + if let d = obj[k] as? Double { return d } + if let n = obj[k] as? NSNumber { return n.doubleValue } + return nil + } + let thresholds: [VizThreshold] = (obj["thresholds"] as? [[String: Any]] ?? []).compactMap { t in + let v = (t["value"] as? Double) ?? (t["value"] as? NSNumber)?.doubleValue + guard let value = v else { return nil } + return VizThreshold(value: value, color: t["color"] as? String, label: t["label"] as? String) + } + return VisualizationOptions( + unit: obj["unit"] as? String, + yScale: obj["y_scale"] as? String, + yMin: dbl("y_min"), + yMax: dbl("y_max"), + stacked: obj["stacked"] as? Bool, + legend: obj["legend"] as? Bool, + seriesLimit: (obj["series_limit"] as? Int) ?? (obj["series_limit"] as? NSNumber)?.intValue, + thresholds: thresholds + ) } private func buildRequestJSON(userText: String, model: String?) -> String { @@ -435,6 +462,32 @@ final class AssistantViewModel { "enum": VizType.allCases.map { $0.rawValue }, "description": "Optional chart type. Omit to let the client choose.", ], + "options": [ + "type": "object", + "description": "Optional presentation overrides.", + "properties": [ + "unit": ["type": "string", "description": "Value unit for axes/labels (e.g. ms, bytes, req/s)."], + "y_scale": ["type": "string", "enum": ["linear", "log"], "description": "Y-axis scale."], + "y_min": ["type": "number", "description": "Force y-axis lower bound."], + "y_max": ["type": "number", "description": "Force y-axis upper bound."], + "stacked": ["type": "boolean", "description": "Stack series instead of overlaying."], + "legend": ["type": "boolean", "description": "Show a series legend."], + "series_limit": ["type": "integer", "description": "Cap the number of series rendered (top-N)."], + "thresholds": [ + "type": "array", + "description": "Horizontal reference lines (e.g. SLO boundaries).", + "items": [ + "type": "object", + "properties": [ + "value": ["type": "number"], + "color": ["type": "string"], + "label": ["type": "string"], + ], + "required": ["value"], + ], + ], + ], + ], ], "required": ["query", "title"], ], diff --git a/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift b/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift index 03c58e39..464a6cd5 100644 --- a/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift +++ b/apps/macos/Sequins/Views/Explore/ExploreTimeSeriesView.swift @@ -7,9 +7,10 @@ struct ExploreTimeSeriesView: View { let columns: [String] let rows: [[Any?]] var columnTypes: [NodeTypeLabel] = [] + var options: VisualizationOptions = VisualizationOptions() var body: some View { - TimeSeriesChart(columns: columns, rows: rows, columnTypes: columnTypes) + TimeSeriesChart(columns: columns, rows: rows, columnTypes: columnTypes, options: options) .padding() } } diff --git a/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift b/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift index 1069fc27..87f36144 100644 --- a/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift +++ b/apps/macos/Sequins/Views/Visualization/TimeSeriesChart.swift @@ -16,6 +16,8 @@ struct TimeSeriesChart: View { var filled: Bool = false /// Stack the areas/series (area only). var stacked: Bool = false + /// Presentation overrides (unit, legend, thresholds, series limit, y-scale). + var options: VisualizationOptions = VisualizationOptions() private struct Datum: Identifiable { let id = UUID() @@ -33,9 +35,29 @@ struct TimeSeriesChart: View { } /// Numeric "value" columns (measures when roles are known, else every column after - /// the first that carries numbers). + /// the first that carries numbers), capped to `options.seriesLimit` by peak magnitude. private var seriesColumns: [(index: Int, name: String)] { - VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles) + let cols = VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles) + guard let limit = options.seriesLimit, limit > 0, cols.count > Int(limit) else { + return cols + } + let ranked = cols.sorted { peakMagnitude($0.index) > peakMagnitude($1.index) } + return Array(ranked.prefix(Int(limit))) + } + + /// Largest absolute value in a column, for ranking series under `series_limit`. + private func peakMagnitude(_ index: Int) -> Double { + var m = 0.0 + for row in rows where index < row.count { + if let v = VizFormat.numeric(row[index]) { m = max(m, abs(v)) } + } + return m + } + + /// Legend visibility: explicit `options.legend`, else visible only when multi-series. + private var legendVisibility: Visibility { + if let l = options.legend { return l ? .visible : .hidden } + return seriesColumns.count > 1 ? .visible : .hidden } private var data: [Datum] { @@ -97,16 +119,18 @@ struct TimeSeriesChart: View { .foregroundStyle(.secondary.opacity(0.4)) .lineStyle(StrokeStyle(lineWidth: 1, dash: [3])) } + thresholdMarks } .chartYAxis { AxisMarks { value in AxisGridLine() AxisValueLabel { - if let v = value.as(Double.self) { Text(VizFormat.compact(v)) } + if let v = value.as(Double.self) { Text(VizFormat.compact(v) + options.unitSuffix) } } } } - .chartLegend(seriesColumns.count > 1 ? .visible : .hidden) + .chartYPresentation(options) + .chartLegend(legendVisibility) .chartOverlay { proxy in GeometryReader { geo in let frame = proxy.plotFrame.map { geo[$0] } ?? .zero @@ -144,7 +168,7 @@ struct TimeSeriesChart: View { Text(VizFormat.axisTime(nearest, includeSeconds: true)) .font(.caption2).foregroundStyle(.secondary) ForEach(rows, id: \.0) { name, y in - Text("\(name): \(VizFormat.number(y))").font(.caption2) + Text("\(name): \(VizFormat.number(y))\(options.unitSuffix)").font(.caption2) } } .padding(6) @@ -160,18 +184,78 @@ struct TimeSeriesChart: View { // MARK: - Numeric fallback private func numericChart(_ points: [Datum]) -> some View { - Chart(points) { p in - LineMark(x: .value(columns.first ?? "x", p.num), y: .value("value", p.y)) - .foregroundStyle(by: .value("Series", p.series)) - .interpolationMethod(.monotone) + Chart { + ForEach(points) { p in + LineMark(x: .value(columns.first ?? "x", p.num), y: .value("value", p.y)) + .foregroundStyle(by: .value("Series", p.series)) + .interpolationMethod(.monotone) + } + thresholdMarks } .chartYAxis { AxisMarks { value in AxisGridLine() - AxisValueLabel { if let v = value.as(Double.self) { Text(VizFormat.compact(v)) } } + AxisValueLabel { if let v = value.as(Double.self) { Text(VizFormat.compact(v) + options.unitSuffix) } } } } - .chartLegend(seriesColumns.count > 1 ? .visible : .hidden) + .chartYPresentation(options) + .chartLegend(legendVisibility) .padding(.vertical, 4) } + + // MARK: - Thresholds + + /// Horizontal reference lines (SLO/alert boundaries) drawn across the plot. + @ChartContentBuilder + private var thresholdMarks: some ChartContent { + ForEach(Array(options.thresholds.enumerated()), id: \.offset) { _, t in + RuleMark(y: .value("threshold", t.value)) + .foregroundStyle(thresholdColor(t.color)) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + .annotation(position: .top, alignment: .trailing) { + if let label = t.label, !label.isEmpty { + Text(label) + .font(.caption2) + .foregroundStyle(thresholdColor(t.color)) + } + } + } + } + + private func thresholdColor(_ spec: String?) -> Color { + Color(cssLike: spec) ?? .orange + } +} + +extension Color { + /// Parse a CSS-like color: a few common names or a `#rgb`/`#rrggbb` hex string. + /// Returns `nil` for empty/unrecognized input so callers can pick a default. + init?(cssLike spec: String?) { + guard let raw = spec?.trimmingCharacters(in: .whitespaces), !raw.isEmpty else { return nil } + switch raw.lowercased() { + case "red": self = .red + case "orange": self = .orange + case "yellow": self = .yellow + case "green": self = .green + case "blue": self = .blue + case "purple": self = .purple + case "pink": self = .pink + case "gray", "grey": self = .gray + case "black": self = .black + case "white": self = .white + default: + var hex = raw + if hex.hasPrefix("#") { hex.removeFirst() } + if hex.count == 3 { + hex = hex.map { "\($0)\($0)" }.joined() + } + guard hex.count == 6, let v = UInt64(hex, radix: 16) else { return nil } + self = Color( + .sRGB, + red: Double((v >> 16) & 0xff) / 255, + green: Double((v >> 8) & 0xff) / 255, + blue: Double(v & 0xff) / 255 + ) + } + } } diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift index 31fdff85..8d236b5e 100644 --- a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift +++ b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift @@ -74,7 +74,8 @@ struct VisualizationView: View { rows: runner.rows, columnTypes: runner.columnTypes, columnRoles: runner.columnRoles, - previousValue: previousStatValue + previousValue: previousStatValue, + options: visualization.options ) } } @@ -111,6 +112,8 @@ struct VizRenderer: View { var columnTypes: [NodeTypeLabel] = [] var columnRoles: [SeQLColumnRole] = [] var previousValue: Double? + /// Presentation overrides (unit, y-scale, stacking, legend, thresholds, …). + var options: VisualizationOptions = VisualizationOptions() /// A chart type that plots measures but has none to plot degrades to a table, so a /// result with rows always shows something rather than an empty chart. @@ -119,19 +122,23 @@ struct VizRenderer: View { VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles).isEmpty { return .table } + // `stacked` option promotes a plain bar chart to a stacked one. + if vizType == .bar, options.stacked == true { + return .stackedBar + } return vizType } var body: some View { switch effectiveType { case .line: - ExploreTimeSeriesView(columns: columns, rows: rows, columnTypes: columnTypes) + ExploreTimeSeriesView(columns: columns, rows: rows, columnTypes: columnTypes, options: options) case .area: - AreaChartView(columns: columns, rows: rows, columnTypes: columnTypes, columnRoles: columnRoles) + AreaChartView(columns: columns, rows: rows, columnTypes: columnTypes, columnRoles: columnRoles, options: options) case .bar: - BarChartView(columns: columns, rows: rows, stacked: false, columnTypes: columnTypes, columnRoles: columnRoles) + BarChartView(columns: columns, rows: rows, stacked: false, columnTypes: columnTypes, columnRoles: columnRoles, options: options) case .stackedBar: - BarChartView(columns: columns, rows: rows, stacked: true, columnTypes: columnTypes, columnRoles: columnRoles) + BarChartView(columns: columns, rows: rows, stacked: true, columnTypes: columnTypes, columnRoles: columnRoles, options: options) case .pie: PieChartView(columns: columns, rows: rows, columnTypes: columnTypes, columnRoles: columnRoles) case .gauge: @@ -153,6 +160,23 @@ struct VizRenderer: View { } } +extension View { + /// Apply option-driven y-axis presentation (logarithmic scale and/or an explicit + /// min…max domain). Swift Charts scale modifiers propagate to descendant `Chart`s + /// via the environment, so this can wrap any chart-bearing view. + @ViewBuilder + func chartYPresentation(_ options: VisualizationOptions) -> some View { + let log = options.useLogScale + if let lo = options.yMin, let hi = options.yMax, hi > lo { + self.chartYScale(domain: lo...hi, type: log ? .log : .linear) + } else if log { + self.chartYScale(domain: .automatic(includesZero: false), type: .log) + } else { + self + } + } +} + /// A centered icon + message placeholder (empty/error states). struct VizMessage: View { let icon: String diff --git a/apps/macos/Sequins/Views/Visualization/VizCharts.swift b/apps/macos/Sequins/Views/Visualization/VizCharts.swift index 37f8ea26..ae19ea95 100644 --- a/apps/macos/Sequins/Views/Visualization/VizCharts.swift +++ b/apps/macos/Sequins/Views/Visualization/VizCharts.swift @@ -16,10 +16,13 @@ struct AreaChartView: View { let rows: [[Any?]] var columnTypes: [NodeTypeLabel] = [] var columnRoles: [SeQLColumnRole] = [] + var options: VisualizationOptions = VisualizationOptions() var body: some View { + // Area stacks by default; `stacked: false` overlays filled areas instead. TimeSeriesChart(columns: columns, rows: rows, columnTypes: columnTypes, - columnRoles: columnRoles, filled: true, stacked: true) + columnRoles: columnRoles, filled: true, + stacked: options.stacked ?? true, options: options) } } @@ -31,14 +34,36 @@ struct BarChartView: View { var stacked: Bool = false var columnTypes: [NodeTypeLabel] = [] var columnRoles: [SeQLColumnRole] = [] + var options: VisualizationOptions = VisualizationOptions() private struct Bar: Identifiable { let id = UUID(); let category: String; let value: Double; let series: String } - /// Numeric value columns (measures when roles are known). + /// Numeric value columns (measures when roles are known), capped to + /// `options.seriesLimit` by peak magnitude. private var valueCols: [(index: Int, name: String)] { - VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles) + let cols = VizFormat.valueColumns(columns: columns, rows: rows, roles: columnRoles) + guard let limit = options.seriesLimit, limit > 0, cols.count > Int(limit) else { + return cols + } + let ranked = cols.sorted { peakMagnitude($0.index) > peakMagnitude($1.index) } + return Array(ranked.prefix(Int(limit))) + } + + /// Largest absolute value in a column, for ranking series under `series_limit`. + private func peakMagnitude(_ index: Int) -> Double { + var m = 0.0 + for row in rows where index < row.count { + if let v = VizFormat.numeric(row[index]) { m = max(m, abs(v)) } + } + return m + } + + /// Legend visibility: explicit `options.legend`, else visible only when multi-series. + private var legendVisibility: Visibility { + if let l = options.legend { return l ? .visible : .hidden } + return valueCols.count > 1 ? .visible : .hidden } private var singleSeries: Bool { valueCols.count == 1 } @@ -79,22 +104,35 @@ struct BarChartView: View { if bars.isEmpty { VizMessage(icon: "chart.bar", text: "No numeric data") } else { - Chart(bars) { bar in - let mark = BarMark( - x: .value(columns.first ?? "category", bar.category), - y: .value("value", bar.value) - ) - .foregroundStyle(by: .value("Series", bar.series)) - if stacked { - mark - } else { - mark.position(by: .value("Series", bar.series)) + Chart { + ForEach(bars) { bar in + let mark = BarMark( + x: .value(columns.first ?? "category", bar.category), + y: .value("value", bar.value) + ) + .foregroundStyle(by: .value("Series", bar.series)) + if stacked { + mark + } else { + mark.position(by: .value("Series", bar.series)) + } + } + ForEach(Array(options.thresholds.enumerated()), id: \.offset) { _, t in + RuleMark(y: .value("threshold", t.value)) + .foregroundStyle(Color(cssLike: t.color) ?? .orange) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + .annotation(position: .top, alignment: .trailing) { + if let label = t.label, !label.isEmpty { + Text(label).font(.caption2) + .foregroundStyle(Color(cssLike: t.color) ?? .orange) + } + } } } .chartYAxis { AxisMarks { v in AxisGridLine() - AxisValueLabel { if let d = v.as(Double.self) { Text(VizFormat.compact(d)) } } + AxisValueLabel { if let d = v.as(Double.self) { Text(VizFormat.compact(d) + options.unitSuffix) } } } } .chartXAxis { @@ -102,7 +140,8 @@ struct BarChartView: View { AxisValueLabel(orientation: bars.count > 6 ? .verticalReversed : .horizontal) } } - .chartLegend(valueCols.count > 1 ? .visible : .hidden) + .chartYPresentation(options) + .chartLegend(legendVisibility) .padding() } } diff --git a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift index 52ad8dd5..781d1aa1 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift @@ -10,11 +10,42 @@ public struct SavedVisualization: Codable, Hashable, Sendable { public var seql: String public var title: String public var shape: String? + /// Optional presentation overrides (units, axis scale, stacking, …). Empty on + /// dashboards saved before this blob existed. + public var options: VisualizationOptions - public init(seql: String, title: String, shape: String? = nil) { + public init( + seql: String, + title: String, + shape: String? = nil, + options: VisualizationOptions = VisualizationOptions() + ) { self.seql = seql self.title = title self.shape = shape + self.options = options + } + + private enum CodingKeys: String, CodingKey { case seql, title, shape, options } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.seql = try c.decode(String.self, forKey: .seql) + self.title = try c.decode(String.self, forKey: .title) + self.shape = try c.decodeIfPresent(String.self, forKey: .shape) + self.options = + try c.decodeIfPresent(VisualizationOptions.self, forKey: .options) + ?? VisualizationOptions() + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(seql, forKey: .seql) + try c.encode(title, forKey: .title) + try c.encodeIfPresent(shape, forKey: .shape) + if !options.isEmpty { + try c.encode(options, forKey: .options) + } } /// The app-side visualization type, backed by the free-form `shape` string. @@ -25,6 +56,106 @@ public struct SavedVisualization: Codable, Hashable, Sendable { } } +/// Presentation overrides for a `SavedVisualization` (mirrors +/// `sequins_metadata::VisualizationOptions`). Every field is optional; an all-unset +/// value is considered empty and omitted from the wire format. +public struct VisualizationOptions: Codable, Hashable, Sendable { + /// Value unit shown on axes/labels (e.g. "ms", "bytes", "req/s"). + public var unit: String? + /// Y-axis scale: "linear" (default) or "log". + public var yScale: String? + /// Forced y-axis lower bound. + public var yMin: Double? + /// Forced y-axis upper bound. + public var yMax: Double? + /// Stack series instead of overlaying them. + public var stacked: Bool? + /// Show a series legend. + public var legend: Bool? + /// Cap the number of series rendered (top-N by magnitude). + public var seriesLimit: Int? + /// Horizontal reference lines drawn across the plot. + public var thresholds: [VizThreshold] + + public init( + unit: String? = nil, + yScale: String? = nil, + yMin: Double? = nil, + yMax: Double? = nil, + stacked: Bool? = nil, + legend: Bool? = nil, + seriesLimit: Int? = nil, + thresholds: [VizThreshold] = [] + ) { + self.unit = unit + self.yScale = yScale + self.yMin = yMin + self.yMax = yMax + self.stacked = stacked + self.legend = legend + self.seriesLimit = seriesLimit + self.thresholds = thresholds + } + + private enum CodingKeys: String, CodingKey { + case unit, yScale, yMin, yMax, stacked, legend, seriesLimit, thresholds + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.unit = try c.decodeIfPresent(String.self, forKey: .unit) + self.yScale = try c.decodeIfPresent(String.self, forKey: .yScale) + self.yMin = try c.decodeIfPresent(Double.self, forKey: .yMin) + self.yMax = try c.decodeIfPresent(Double.self, forKey: .yMax) + self.stacked = try c.decodeIfPresent(Bool.self, forKey: .stacked) + self.legend = try c.decodeIfPresent(Bool.self, forKey: .legend) + self.seriesLimit = try c.decodeIfPresent(Int.self, forKey: .seriesLimit) + self.thresholds = try c.decodeIfPresent([VizThreshold].self, forKey: .thresholds) ?? [] + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encodeIfPresent(unit, forKey: .unit) + try c.encodeIfPresent(yScale, forKey: .yScale) + try c.encodeIfPresent(yMin, forKey: .yMin) + try c.encodeIfPresent(yMax, forKey: .yMax) + try c.encodeIfPresent(stacked, forKey: .stacked) + try c.encodeIfPresent(legend, forKey: .legend) + try c.encodeIfPresent(seriesLimit, forKey: .seriesLimit) + if !thresholds.isEmpty { + try c.encode(thresholds, forKey: .thresholds) + } + } + + /// True when no override is set. + public var isEmpty: Bool { + unit == nil && yScale == nil && yMin == nil && yMax == nil + && stacked == nil && legend == nil && seriesLimit == nil && thresholds.isEmpty + } + + /// Whether the y-axis should use a logarithmic scale. + public var useLogScale: Bool { yScale?.lowercased() == "log" } + + /// A leading-space unit suffix for axis/tooltip labels (e.g. `" ms"`), or empty. + public var unitSuffix: String { + if let u = unit, !u.isEmpty { return " \(u)" } + return "" + } +} + +/// A horizontal reference line on a chart (mirrors `sequins_metadata::Threshold`). +public struct VizThreshold: Codable, Hashable, Sendable { + public var value: Double + public var color: String? + public var label: String? + + public init(value: Double, color: String? = nil, label: String? = nil) { + self.value = value + self.color = color + self.label = label + } +} + /// Default dashboard row height, in points (mirrors `DEFAULT_ROW_HEIGHT` in Rust). public let defaultRowHeight: Double = 280 diff --git a/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift b/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift index 1c55fdf3..92fafcb0 100644 --- a/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift +++ b/apps/macos/SequinsData/Tests/SequinsDataTests/DashboardVizTests.swift @@ -62,6 +62,47 @@ final class DashboardVizTests: XCTestCase { XCTAssertEqual(SavedVisualization(seql: "x", title: "t", shape: "trace_tree").vizType, .trace) } + func testVisualizationOptionsRoundTrip() throws { + let viz = SavedVisualization( + seql: "spans last 1h | group by { ts() bin 1m as t } { p99(duration) as latency }", + title: "Latency", + shape: "line", + options: VisualizationOptions( + unit: "ms", + yScale: "log", + yMax: 1000, + stacked: true, + legend: false, + seriesLimit: 5, + thresholds: [VizThreshold(value: 500, color: "red", label: "SLO")] + ) + ) + let data = try DashboardJSON.encoder.encode(viz) + let json = String(decoding: data, as: UTF8.self) + // snake_case wire keys. + XCTAssertTrue(json.contains("y_scale"), json) + XCTAssertTrue(json.contains("series_limit"), json) + + let back = try DashboardJSON.decoder.decode(SavedVisualization.self, from: data) + XCTAssertEqual(back.options.unit, "ms") + XCTAssertTrue(back.options.useLogScale) + XCTAssertEqual(back.options.yMax, 1000) + XCTAssertEqual(back.options.stacked, true) + XCTAssertEqual(back.options.legend, false) + XCTAssertEqual(back.options.seriesLimit, 5) + XCTAssertEqual(back.options.thresholds.first?.value, 500) + XCTAssertEqual(back.options.thresholds.first?.label, "SLO") + XCTAssertEqual(back.options.unitSuffix, " ms") + } + + func testVisualizationOptionsOmittedWhenEmpty() throws { + // A viz with no options must not emit an `options` key (backward-compatible). + let viz = SavedVisualization(seql: "logs last 1h", title: "Logs") + let json = String(decoding: try DashboardJSON.encoder.encode(viz), as: UTF8.self) + XCTAssertFalse(json.contains("options"), json) + XCTAssertTrue(viz.options.isEmpty) + } + func testVizTypeAutoSelect() { XCTAssertEqual(VizType.autoSelect(shape: .timeSeries, columns: ["t", "v"], rows: []), .line) XCTAssertEqual(VizType.autoSelect(shape: .scalar, columns: ["c"], rows: [[1]]), .stat) diff --git a/crates/sequins-assistant/src/model.rs b/crates/sequins-assistant/src/model.rs index 63500a77..15765964 100644 --- a/crates/sequins-assistant/src/model.rs +++ b/crates/sequins-assistant/src/model.rs @@ -446,19 +446,34 @@ Prefer discovery tools over guessing — observability data is dominated by attr ## Presenting results -- `render_visualization(query, title, chart_type?)` — show a chart INLINE in the chat for a - one-off answer. `chart_type` is optional (`line`/`bar`/`stat`/`table`/`heatmap`/…); omit to - auto-select. The app re-runs the query to render it. +- `render_visualization(query, title, chart_type?, options?)` — show a chart INLINE in the chat + for a one-off answer. `chart_type` is optional (`line`/`bar`/`stat`/`table`/`heatmap`/…); omit + to auto-select. The app re-runs the query to render it. +- `recommend_chart(query)` — unsure which type fits? This runs the query and returns the best + chart type for its result shape plus a short rationale. Use it before `add_chart` when picking + a type is non-obvious. + +### Presentation options +Both `render_visualization` and the dashboard `add_chart`/`update_chart` tools accept an +`options` object to refine a chart. All fields are optional: +- `unit` (e.g. `"ms"`, `"bytes"`, `"req/s"`) — labels axes and tooltips. +- `y_scale`: `"linear"` (default) or `"log"` — use `log` for wide-range/latency data. +- `y_min` / `y_max` — pin the y-axis (set both for an explicit domain). +- `stacked` (bool) — stack series instead of overlaying (bar/area). +- `legend` (bool) — force the series legend on/off. +- `series_limit` (int) — cap to the top-N series by magnitude to reduce clutter. +- `thresholds`: `[{value, color?, label?}]` — horizontal reference lines (SLO/alert boundaries). ## Dashboards Read before you edit, and address charts by position: - `list_dashboards` / `get_dashboard(dashboard)` — see dashboards and each chart's `[row,col]` - position, title, weight, type, and query. Always `get_dashboard` before editing. + position, title, weight, type, query, and any `options`. Always `get_dashboard` before editing. - `create_dashboard(title)` then `add_chart(dashboard, query, title, chart_type?, row?, - position?, weight?)` — build/populate. Omit `row` to add a new full-width row; give `row` - (and `position`/`weight`) to place charts side by side. -- `update_chart(dashboard, row, column, …)` — edit a chart's title/query/type. + position?, weight?, options?)` — build/populate. Omit `row` to add a new full-width row; give + `row` (and `position`/`weight`) to place charts side by side. +- `update_chart(dashboard, row, column, …, options?)` — edit a chart's title/query/type; passing + `options` replaces the chart's current presentation options. - `arrange_dashboard(dashboard, rows:[{height?, panels:[{from_row, from_column, weight?}]}])` — move/resize/reorder in one call. Charts are referenced by current position; set `weight` for column-width ratios and `height` for rows. Charts you omit are removed. diff --git a/crates/sequins-assistant/src/tools/ops.rs b/crates/sequins-assistant/src/tools/ops.rs index 4b0beff7..dbeb2f2a 100644 --- a/crates/sequins-assistant/src/tools/ops.rs +++ b/crates/sequins-assistant/src/tools/ops.rs @@ -28,7 +28,8 @@ use sequins_arrow_schema::{PromotedAttribute, SignalType}; use sequins_datafusion_backend::{hot_signal_tables, hot_signal_type_for_table, DataFusionBackend}; use sequins_flight::{decode_metadata, ipc_to_batch, SeqlMetadata}; use sequins_metadata::{ - Dashboard, DashboardApi, DashboardRow, RowPanel, SavedVisualization, DEFAULT_ROW_HEIGHT, + Dashboard, DashboardApi, DashboardRow, RowPanel, SavedVisualization, Threshold, + VisualizationOptions, DEFAULT_ROW_HEIGHT, }; use sequins_series_index::SeriesIndex; use sequins_traits::QueryApi; @@ -176,6 +177,13 @@ pub struct MetricLabelValuesArgs { pub metric: Option, } +/// Arguments for `recommend_chart`. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct RecommendChartArgs { + /// The SeQL query whose result should be visualized. + pub query: String, +} + /// Arguments for `overview` (none). #[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)] pub struct OverviewArgs {} @@ -271,6 +279,9 @@ pub struct AddChartArgs { /// Relative width weight within the row (default 1.0). #[serde(default)] pub weight: Option, + /// Optional presentation overrides (unit, y_scale, stacked, legend, …). + #[serde(default)] + pub options: Option, } /// Arguments for `update_chart`. @@ -288,6 +299,9 @@ pub struct UpdateChartArgs { pub query: Option, #[serde(default)] pub chart_type: Option, + /// Optional presentation overrides. Replaces the chart's current options when set. + #[serde(default)] + pub options: Option, } /// Arguments for `arrange_dashboard` — a declarative new layout referencing existing @@ -320,6 +334,71 @@ pub struct ArrangePanel { pub weight: Option, } +/// Presentation overrides accepted by `add_chart`/`update_chart`; converts into a +/// [`VisualizationOptions`] blob the renderers honor. Every field is optional. +#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)] +pub struct ChartOptionsArgs { + /// Value unit shown on axes/labels (e.g. "ms", "bytes", "req/s"). + #[serde(default)] + pub unit: Option, + /// Y-axis scale: "linear" (default) or "log". + #[serde(default)] + pub y_scale: Option, + /// Force the y-axis lower bound. + #[serde(default)] + pub y_min: Option, + /// Force the y-axis upper bound. + #[serde(default)] + pub y_max: Option, + /// Stack series instead of overlaying them (area/bar charts). + #[serde(default)] + pub stacked: Option, + /// Show a series legend. + #[serde(default)] + pub legend: Option, + /// Cap the number of series rendered (top-N by magnitude). + #[serde(default)] + pub series_limit: Option, + /// Horizontal reference lines (e.g. SLO/alert boundaries). + #[serde(default)] + pub thresholds: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +pub struct ThresholdArg { + /// Y-value at which to draw the line. + pub value: f64, + /// Optional color (e.g. "#ff0000" or "red"). + #[serde(default)] + pub color: Option, + /// Optional label for the line. + #[serde(default)] + pub label: Option, +} + +impl From for VisualizationOptions { + fn from(a: ChartOptionsArgs) -> Self { + VisualizationOptions { + unit: a.unit.filter(|s| !s.is_empty()), + y_scale: a.y_scale.filter(|s| !s.is_empty()), + y_min: a.y_min, + y_max: a.y_max, + stacked: a.stacked, + legend: a.legend, + series_limit: a.series_limit, + thresholds: a + .thresholds + .into_iter() + .map(|t| Threshold { + value: t.value, + color: t.color.filter(|s| !s.is_empty()), + label: t.label.filter(|s| !s.is_empty()), + }) + .collect(), + } + } +} + // --------------------------------------------------------------------------- // Tools — holds the backend; every op is a method returning rendered text. // --------------------------------------------------------------------------- @@ -681,6 +760,50 @@ impl Tools { Ok(out) } + /// Recommend a chart type for a query's result, from its inferred shape and column + /// roles (dimensions vs measures) — the same signal the client renderer uses, so the + /// model can pick a `chart_type` that actually fits before rendering/saving. + pub async fn recommend_chart(&self, args: RecommendChartArgs) -> Result { + use seql_ast::schema::ColumnRole; + let mut stream = self.backend.query(&args.query).await?; + let mut shape = String::from("table"); + let mut roles: Vec = Vec::new(); + let mut names: Vec = Vec::new(); + let mut rows = 0usize; + while let Some(frame) = stream.next().await { + let fd = frame?; + let Some(meta) = decode_metadata(&fd.app_metadata) else { + continue; + }; + match meta { + SeqlMetadata::Schema { + table: None, + shape: s, + columns, + .. + } => { + shape = s.as_str().to_string(); + for c in &columns { + names.push(c.name.clone()); + roles.push(c.role); + } + } + SeqlMetadata::Data { table: None } => { + if let Ok(b) = ipc_to_batch(&fd.data_body) { + rows += b.num_rows(); + } + } + _ => {} + } + } + let (chart, why) = recommend_chart_type(&shape, &roles, rows); + Ok(format!( + "For `{}`:\n- shape: {shape}, {rows} rows\n- columns: {}\n- recommended chart_type: {chart}\n- why: {why}", + args.query, + names.join(", "), + )) + } + /// A compact per-signal-table overview: row counts and (where a time column /// exists) the time span, flagging empty tables so the model avoids them. pub async fn overview(&self, _args: OverviewArgs) -> Result { @@ -1044,6 +1167,7 @@ impl Tools { seql: args.query, title: args.title, shape: args.chart_type, + options: args.options.map(Into::into).unwrap_or_default(), }, weight: args.weight.unwrap_or(1.0), }; @@ -1089,6 +1213,9 @@ impl Tools { if let Some(ct) = args.chart_type { panel.visualization.shape = Some(ct); } + if let Some(opts) = args.options { + panel.visualization.options = opts.into(); + } let d = api.save_dashboard(d).await?; Ok(format!( "Updated chart [{},{}].\n{}", @@ -1237,6 +1364,45 @@ fn human_duration_ns(ns: u64) -> String { parts.join(" ") } +/// Map a result's shape + column roles to a recommended chart type (mirrors the client +/// renderer's role-aware auto-selection). Returns `(chart_type, reason)`. +fn recommend_chart_type( + shape: &str, + roles: &[seql_ast::schema::ColumnRole], + rows: usize, +) -> (&'static str, String) { + use seql_ast::schema::ColumnRole::*; + match shape { + "timeseries" => ("line", "time series → line (or area to stack).".to_string()), + "scalar" => ("stat", "a single value → stat.".to_string()), + "heatmap" => ("heatmap", "distribution → heatmap.".to_string()), + "trace_tree" | "trace_timeline" => ("trace", "spans → trace view.".to_string()), + "pattern_groups" => ("table", "log patterns → table.".to_string()), + _ => { + let dims = roles + .iter() + .filter(|r| matches!(r, GroupKey | Field)) + .count(); + let measures = roles + .iter() + .filter(|r| matches!(r, Aggregation | Computed)) + .count(); + if measures == 0 { + ("table", "no measure columns to plot → table.".to_string()) + } else if dims >= 2 && measures == 1 { + ( + "heatmap", + "two dimensions × one measure → heatmap (or table).".to_string(), + ) + } else if dims == 1 && rows > 1 && rows <= 24 { + ("bar", "one category + a measure → bar.".to_string()) + } else { + ("table", "wide or large result → table.".to_string()) + } + } + } +} + /// Render a dashboard's structure for the model: rows with heights, and each chart's /// `[row,col]` position, title, weight, type, and query — the addresses edit tools use. fn render_dashboard(d: &Dashboard) -> String { @@ -1260,11 +1426,46 @@ fn render_dashboard(d: &Dashboard) -> String { p.visualization.shape.as_deref().unwrap_or("auto"), p.visualization.seql )); + let opts = render_options(&p.visualization.options); + if !opts.is_empty() { + out.push_str(&format!(" options: {opts}\n")); + } } } out } +/// Render a compact one-line summary of a chart's presentation options, or an empty +/// string when none are set. +fn render_options(o: &VisualizationOptions) -> String { + let mut parts = Vec::new(); + if let Some(u) = &o.unit { + parts.push(format!("unit={u}")); + } + if let Some(s) = &o.y_scale { + parts.push(format!("y_scale={s}")); + } + if let Some(v) = o.y_min { + parts.push(format!("y_min={v}")); + } + if let Some(v) = o.y_max { + parts.push(format!("y_max={v}")); + } + if let Some(v) = o.stacked { + parts.push(format!("stacked={v}")); + } + if let Some(v) = o.legend { + parts.push(format!("legend={v}")); + } + if let Some(v) = o.series_limit { + parts.push(format!("series_limit={v}")); + } + if !o.thresholds.is_empty() { + parts.push(format!("thresholds={}", o.thresholds.len())); + } + parts.join(", ") +} + /// Resolve an attribute key to a promoted column name present in `cols`, accepting the /// OTLP dotted key, the underscore column name, or a raw existing column. fn resolve_promoted_column(cols: &[String], key: &str) -> Option { @@ -1583,6 +1784,11 @@ mod tests { row: None, position: None, weight: None, + options: Some(ChartOptionsArgs { + unit: Some("ms".into()), + y_scale: Some("log".into()), + ..Default::default() + }), }) .await .unwrap(); @@ -1595,9 +1801,15 @@ mod tests { row: Some(0), position: None, weight: Some(2.0), + options: None, }) .await .unwrap(); + // The options set on the first chart round-trip into the rendered layout. + assert!( + after.contains("unit=ms") && after.contains("y_scale=log"), + "{after}" + ); // Second chart added into row 0 → two side-by-side panels. assert!( after.contains("[0,0]") && after.contains("[0,1]"), @@ -1612,6 +1824,7 @@ mod tests { title: Some("Spans per minute".into()), query: None, chart_type: None, + options: None, }) .await .unwrap(); @@ -1666,4 +1879,43 @@ mod tests { assert!(out.contains("shape:")); assert!(out.contains("columns:")); } + + #[tokio::test] + async fn recommend_chart_reads_result_shape() { + let (tools, _t) = seeded_tools(6).await; + let out = tools + .recommend_chart(RecommendChartArgs { + query: "spans last 1h | group by { ts() bin 1m as bucket } { count() as n }".into(), + }) + .await + .unwrap(); + assert!(out.contains("recommended chart_type:"), "{out}"); + assert!(out.contains("shape:"), "{out}"); + } + + #[test] + fn recommend_chart_type_maps_shapes() { + use seql_ast::schema::ColumnRole; + // A time bucket + one measure → a line chart. + let (kind, _) = recommend_chart_type( + "timeseries", + &[ColumnRole::GroupKey, ColumnRole::Aggregation], + 30, + ); + assert_eq!(kind, "line"); + // A single scalar → a stat. + let (kind, _) = recommend_chart_type("scalar", &[ColumnRole::Aggregation], 1); + assert_eq!(kind, "stat"); + // Two dimensions + one measure → a heatmap. + let (kind, _) = recommend_chart_type( + "table", + &[ + ColumnRole::GroupKey, + ColumnRole::GroupKey, + ColumnRole::Aggregation, + ], + 50, + ); + assert_eq!(kind, "heatmap"); + } } diff --git a/crates/sequins-assistant/src/tools/registry.rs b/crates/sequins-assistant/src/tools/registry.rs index 16ca74c5..fa623018 100644 --- a/crates/sequins-assistant/src/tools/registry.rs +++ b/crates/sequins-assistant/src/tools/registry.rs @@ -17,8 +17,8 @@ use super::ops::{ AddChartArgs, ArrangeDashboardArgs, AttributeValuesArgs, ColumnProfileArgs, CreateDashboardArgs, DescribeSchemaArgs, ExplainArgs, GetDashboardArgs, ListAttributesArgs, ListDashboardsArgs, ListMetricsArgs, ListTablesArgs, MetricLabelValuesArgs, MetricLabelsArgs, - OverviewArgs, RenameDashboardArgs, RunSeqlArgs, RunSqlArgs, SampleArgs, TimeRangeArgs, - UpdateChartArgs, ValidateSeqlArgs, + OverviewArgs, RecommendChartArgs, RenameDashboardArgs, RunSeqlArgs, RunSqlArgs, SampleArgs, + TimeRangeArgs, UpdateChartArgs, ValidateSeqlArgs, }; use super::{OpError, Tools}; @@ -50,6 +50,7 @@ pub const TOOL_NAMES: &[&str] = &[ "run_sql", "validate_seql", "run_seql", + "recommend_chart", "list_dashboards", "get_dashboard", "create_dashboard", @@ -146,6 +147,11 @@ pub fn specs() -> Vec { description: "Execute a SeQL query and summarize its result: shape, columns, row count, sample rows, and stats. The final answer must be a SeQL query.", parameters: schema::(), }, + ToolSpec { + name: "recommend_chart", + description: "Run a SeQL query and recommend the best chart type for its result shape (line, bar, stat, heatmap, table, …), with a short rationale. Use before add_chart when unsure which type fits.", + parameters: schema::(), + }, ToolSpec { name: "list_dashboards", description: "List saved dashboards with ids, titles, and chart counts.", @@ -226,6 +232,7 @@ pub async fn invoke(tools: &Tools, name: &str, args: serde_json::Value) -> Resul "run_sql" => tools.run_sql(parse(args)?).await, "validate_seql" => tools.validate_seql(parse(args)?).await, "run_seql" => tools.run_seql(parse(args)?).await, + "recommend_chart" => tools.recommend_chart(parse(args)?).await, "list_dashboards" => tools.list_dashboards(parse(args)?).await, "get_dashboard" => tools.get_dashboard(parse(args)?).await, "create_dashboard" => tools.create_dashboard(parse(args)?).await, diff --git a/crates/sequins-metadata/src/lib.rs b/crates/sequins-metadata/src/lib.rs index dea089d9..2ffef7df 100644 --- a/crates/sequins-metadata/src/lib.rs +++ b/crates/sequins-metadata/src/lib.rs @@ -14,5 +14,5 @@ pub use error::{MetadataError, Result}; pub use store::{AppStateStore, DashboardApi}; pub use types::{ Conversation, ConversationItem, Dashboard, DashboardRow, RowPanel, SavedVisualization, - DEFAULT_ROW_HEIGHT, + Threshold, VisualizationOptions, DEFAULT_ROW_HEIGHT, }; diff --git a/crates/sequins-metadata/src/store.rs b/crates/sequins-metadata/src/store.rs index 3c53032c..dd2505ab 100644 --- a/crates/sequins-metadata/src/store.rs +++ b/crates/sequins-metadata/src/store.rs @@ -338,6 +338,7 @@ mod tests { seql: "logs last 1h".into(), title: "Recent logs".into(), shape: Some("table".into()), + options: Default::default(), }, weight: 1.0, }], diff --git a/crates/sequins-metadata/src/types.rs b/crates/sequins-metadata/src/types.rs index 071cc882..32b64b68 100644 --- a/crates/sequins-metadata/src/types.rs +++ b/crates/sequins-metadata/src/types.rs @@ -116,4 +116,59 @@ pub struct SavedVisualization { pub title: String, #[serde(default)] pub shape: Option, + /// Optional presentation overrides (units, axis scale, stacking, …). Absent on + /// older saved dashboards; defaults to empty. + #[serde(default, skip_serializing_if = "VisualizationOptions::is_empty")] + pub options: VisualizationOptions, +} + +/// Presentation overrides for a [`SavedVisualization`]. Every field is optional so +/// dashboards saved before this blob existed deserialize unchanged, and an all-unset +/// value is omitted from serialized output. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct VisualizationOptions { + /// Value unit shown on axes/labels (e.g. `"ms"`, `"bytes"`, `"req/s"`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unit: Option, + /// Y-axis scale: `"linear"` (default) or `"log"`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y_scale: Option, + /// Force the y-axis lower bound. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y_min: Option, + /// Force the y-axis upper bound. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub y_max: Option, + /// Stack series instead of overlaying them (area/bar charts). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stacked: Option, + /// Show a series legend. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub legend: Option, + /// Cap the number of series rendered (top-N by magnitude). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub series_limit: Option, + /// Horizontal reference lines drawn across the plot. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub thresholds: Vec, +} + +impl VisualizationOptions { + /// True when no override is set (used to omit the blob from serialized output). + pub fn is_empty(&self) -> bool { + *self == VisualizationOptions::default() + } +} + +/// A horizontal reference line on a chart (e.g. an SLO or alert boundary). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Threshold { + /// Y-value at which the line is drawn. + pub value: f64, + /// Optional CSS-style color (e.g. `"#ff0000"` or `"red"`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + /// Optional label for the line. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, } From c927d363f4ad7488a268bc53d2a0c9b66311cde9 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 28 Jul 2026 15:52:37 +0800 Subject: [PATCH 08/10] fix(metadata): silence clippy::explicit_counter_loop in append_response MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI runs clippy with `-D warnings`, where the manual `position` counter in `AppStateStore::append_response` fails `clippy::explicit_counter_loop`. Zip the item iterator with an open-ended range starting at the current item count instead — same positions assigned, no manual increment. Co-Authored-By: Claude Opus 5 --- crates/sequins-metadata/src/store.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/sequins-metadata/src/store.rs b/crates/sequins-metadata/src/store.rs index dd2505ab..ee6daad0 100644 --- a/crates/sequins-metadata/src/store.rs +++ b/crates/sequins-metadata/src/store.rs @@ -148,10 +148,9 @@ impl AppStateStore { if conv.title.is_none() { conv.title = title; } - let mut position = conv.items.len() as u32; - for mut item in input_items.into_iter().chain(output_items) { + let start = conv.items.len() as u32; + for (position, mut item) in (start..).zip(input_items.into_iter().chain(output_items)) { item.position = position; - position += 1; conv.items.push(item); } conv.updated_at_ns = now; From d310ffe8ebf3d8aebd4874d70bfc5bf6c5d9284a Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 28 Jul 2026 18:21:43 +0800 Subject: [PATCH 09/10] fix(otlp): drop redundant reference in profiles mapping_id format! Rust 1.97's clippy flags `&filename` in the `format!` as `useless_borrows_in_formatting`, failing CI under `-D warnings`. Format args are borrowed implicitly, so dropping the `&` leaves `filename` available for the `MappingData` construction below. Co-Authored-By: Claude Opus 5 --- crates/sequins-otlp/src/profiles.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/sequins-otlp/src/profiles.rs b/crates/sequins-otlp/src/profiles.rs index 633dcf37..80a3b499 100644 --- a/crates/sequins-otlp/src/profiles.rs +++ b/crates/sequins-otlp/src/profiles.rs @@ -200,7 +200,7 @@ pub fn otlp_profiles_to_batches( // Build mappings from mapping_table for (i, m) in dict.mapping_table.iter().enumerate() { let filename = get_str(m.filename_strindex); - let mapping_id = fnv1a_64(format!("{}{}", i, &filename).as_bytes()); + let mapping_id = fnv1a_64(format!("{}{}", i, filename).as_bytes()); mapping_map.entry(mapping_id).or_insert(MappingData { filename, build_id: None, From d84ba94a9a555d264352b4ef287fccc5d0dca870 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 28 Jul 2026 21:21:30 +0800 Subject: [PATCH 10/10] fix(test): deterministic bloom seed for pruning test `bloom_pruning_rejects_missing_values_for_bloom_fields` asserted that `trace-404` is pruned by a filter built over {trace-1, trace-2}. Bloom filters admit false positives, and `Bloom::new_for_fp_rate` draws random sip keys per instance, so the assertion held only when the seed happened to cooperate. At n=2 / fpr=0.01 the filter is just 24 bits with 9 hash functions, so it is far more saturated than the nominal rate suggests: measured over 2000 random seeds, `trace-404` collides 3.25% of the time. That is roughly 1 CI failure in 31, on a crate unrelated to whatever is being changed. Add a `test-util` feature to sequins-companion-index exposing `BloomFilterSet::build_with_seed` (via `new_for_fp_rate_with_seed`), and pin the test to a seed verified to reject `trace-404` while keeping both members. The feature is off in production builds; sequins-vortex-indexed-layout enables it as a dev-dependency, since the test and the type live in different crates. Also add the complementary no-false-negative case, which holds for any seed. Co-Authored-By: Claude Opus 5 --- crates/sequins-companion-index/Cargo.toml | 5 ++++ crates/sequins-companion-index/src/bloom.rs | 26 +++++++++++++++++++ .../sequins-vortex-indexed-layout/Cargo.toml | 5 ++++ .../src/reader.rs | 25 +++++++++++++++++- 4 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/sequins-companion-index/Cargo.toml b/crates/sequins-companion-index/Cargo.toml index 91e13a1d..40014806 100644 --- a/crates/sequins-companion-index/Cargo.toml +++ b/crates/sequins-companion-index/Cargo.toml @@ -20,5 +20,10 @@ serde = { workspace = true } serde_json = { workspace = true } bincode = { workspace = true } +[features] +# Deterministic-seed index constructors, for tests that need reproducible +# filters. Not enabled in production builds. +test-util = [] + [dev-dependencies] tempfile = { workspace = true } diff --git a/crates/sequins-companion-index/src/bloom.rs b/crates/sequins-companion-index/src/bloom.rs index a9198900..78986ba1 100644 --- a/crates/sequins-companion-index/src/bloom.rs +++ b/crates/sequins-companion-index/src/bloom.rs @@ -49,6 +49,32 @@ impl BloomFilterSet { self.filters.insert(field_name, bloom); } + /// Build a bloom filter for a field from a fixed `seed`, producing a + /// bit-for-bit reproducible filter. + /// + /// [`build`](Self::build) draws random sip keys per filter, so *which* + /// non-members collide as false positives varies from run to run. A test + /// asserting that one specific absent value is pruned is therefore flaky + /// against `build` — pinning the seed makes that assertion deterministic. + /// + /// Only the hash keys are pinned; the false-positive rate itself is + /// unchanged, so callers still must not treat a `true` result as proof of + /// membership. + #[cfg(feature = "test-util")] + pub fn build_with_seed(&mut self, field_name: String, values: I, fpr: f64, seed: &[u8; 32]) + where + I: IntoIterator, + { + let values_vec: Vec = values.into_iter().collect(); + let mut bloom = Bloom::new_for_fp_rate_with_seed(values_vec.len(), fpr, seed); + + for value in values_vec { + bloom.set(&value); + } + + self.filters.insert(field_name, bloom); + } + /// Check if a value might be in the filter for a given field /// /// Returns: diff --git a/crates/sequins-vortex-indexed-layout/Cargo.toml b/crates/sequins-vortex-indexed-layout/Cargo.toml index ff203154..39d59781 100644 --- a/crates/sequins-vortex-indexed-layout/Cargo.toml +++ b/crates/sequins-vortex-indexed-layout/Cargo.toml @@ -28,3 +28,8 @@ tempfile = { workspace = true } # Arrow (for reader expression handling) arrow = { workspace = true } datafusion = { workspace = true } + +[dev-dependencies] +# `test-util` exposes the deterministic-seed bloom constructor the pruning +# tests need; random seeds make specific false-positive assertions flaky. +sequins-companion-index = { workspace = true, features = ["test-util"] } diff --git a/crates/sequins-vortex-indexed-layout/src/reader.rs b/crates/sequins-vortex-indexed-layout/src/reader.rs index ccb64e7c..88ae75d6 100644 --- a/crates/sequins-vortex-indexed-layout/src/reader.rs +++ b/crates/sequins-vortex-indexed-layout/src/reader.rs @@ -350,17 +350,40 @@ mod tests { assert!(bloom_may_match_equalities(&bloom, &equalities)); } + /// Fixed seed under which `trace-404` is not a false positive against + /// `{trace-1, trace-2}`. With `build`'s random seeds it collides ~3% of the + /// time, which made this test fail intermittently in CI. + const PRUNING_SEED: [u8; 32] = [0u8; 32]; + #[test] fn bloom_pruning_rejects_missing_values_for_bloom_fields() { let mut bloom = BloomFilterSet::new(); - bloom.build( + bloom.build_with_seed( "trace_id".to_string(), vec!["trace-1".to_string(), "trace-2".to_string()], 0.01, + &PRUNING_SEED, ); let equalities = vec![("trace_id".to_string(), "trace-404".to_string())]; assert!(!bloom_may_match_equalities(&bloom, &equalities)); } + + #[test] + fn bloom_pruning_keeps_present_values_for_bloom_fields() { + let mut bloom = BloomFilterSet::new(); + bloom.build_with_seed( + "trace_id".to_string(), + vec!["trace-1".to_string(), "trace-2".to_string()], + 0.01, + &PRUNING_SEED, + ); + + // Bloom filters admit false positives but never false negatives, so an + // inserted value must always survive pruning — seed independent. + let equalities = vec![("trace_id".to_string(), "trace-1".to_string())]; + + assert!(bloom_may_match_equalities(&bloom, &equalities)); + } }