From 51d29a98d50e0046a1abbd831f8ff0e10248060a Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:32:51 -0600 Subject: [PATCH] =?UTF-8?q?atlas-core:=20core=20search=20library=20?= =?UTF-8?q?=E2=80=94=20Atlas=20epic=20#5350=20step=202=20(#5352)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The search pipeline as a library, a semantics-exact port of the production Python atlas_search.py, building on step 1's atlas-embed (#5351): - Filters + sensitivity ceilings (shareable < personal < local-only < secret-bearing; default personal; NULL never passes — fail-closed), enforced inside branch construction (filter-before-rank) on both backends. - FTS branch + vector branch, RRF fusion k=10, pool 100/branch defaults; envelope rendering (flat, grouped, get-chunk) byte-equal to the Python's. - All three vector backends behind the SearchBackend trait: exact scan (default; the production path), index fetch-to-fill (depth doubles to a 3200 cap until the pool survives the filter), index fixed-fetch. The default flips only at #5356 from A/B evidence. - Turso over the HTTPS /v2/pipeline API, read-only token flow (env -> Bitwarden -> 20h cache -> turso CLI mint); the library never issues writes. Local mode against SQLite publish files with temp-view schema normalization and vector side stores joined by content hash (never chunk_id). - Query embedding via atlas-embed at the library boundary: documents prompt-free, queries get the "query: " prefix; the embedder session is &mut self, so AtlasEmbedder serializes on a mutex — one resident session per process by design. Verification (step gate): - 16 unit tests (RRF decompositions, ceiling clamping, filter-before-rank, fetch-to-fill escalation vs a recording fake, round6/Python float parity). - 4 parity tests against fixtures recorded from the production Python (gen_core_fixtures.py): all 12 search envelopes and 2 get-chunk envelopes byte-equal, Turso branch SQL byte-for-byte, allowed-ids / index-fill / index-fixed call sequences exact. - Live smoke (examples/live_smoke.rs, read-only, production corpus): 6 of 6 diverse questions — Rust scan-path fused top-10 identical to the deployed Python CLI's. - cargo test --workspace green, clippy 0 warnings, fmt clean. --- pkgs/atlas-search/Cargo.lock | 407 ++++- pkgs/atlas-search/Cargo.toml | 2 +- .../atlas-search/crates/atlas-core/Cargo.toml | 19 + .../crates/atlas-core/examples/live_smoke.rs | 148 ++ .../crates/atlas-core/src/backend.rs | 52 + .../crates/atlas-core/src/embed.rs | 120 ++ .../crates/atlas-core/src/error.rs | 27 + .../crates/atlas-core/src/filters.rs | 620 +++++++ .../crates/atlas-core/src/fusion.rs | 206 +++ .../atlas-search/crates/atlas-core/src/lib.rs | 47 + .../crates/atlas-core/src/local.rs | 662 +++++++ .../crates/atlas-core/src/search.rs | 472 +++++ .../crates/atlas-core/src/turso.rs | 695 ++++++++ .../crates/atlas-core/src/types.rs | 275 +++ .../crates/atlas-core/tests/parity.rs | 428 +++++ .../fixtures/core-expectations.json | 1573 +++++++++++++++++ pkgs/atlas-search/fixtures/fixture_corpus.sql | 90 + pkgs/atlas-search/fixtures/fixture_spec.json | 1 + .../fixtures/gen_core_fixtures.py | 197 +++ 19 files changed, 6036 insertions(+), 5 deletions(-) create mode 100644 pkgs/atlas-search/crates/atlas-core/Cargo.toml create mode 100644 pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/backend.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/embed.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/error.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/filters.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/fusion.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/lib.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/local.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/search.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/turso.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/src/types.rs create mode 100644 pkgs/atlas-search/crates/atlas-core/tests/parity.rs create mode 100644 pkgs/atlas-search/fixtures/core-expectations.json create mode 100644 pkgs/atlas-search/fixtures/fixture_corpus.sql create mode 100644 pkgs/atlas-search/fixtures/fixture_spec.json create mode 100644 pkgs/atlas-search/fixtures/gen_core_fixtures.py diff --git a/pkgs/atlas-search/Cargo.lock b/pkgs/atlas-search/Cargo.lock index 29eb3d5ef7..af5f4d26a6 100644 --- a/pkgs/atlas-search/Cargo.lock +++ b/pkgs/atlas-search/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "ahash" version = "0.8.12" @@ -9,7 +15,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ "cfg-if", - "getrandom", + "getrandom 0.3.4", "once_cell", "serde", "version_check", @@ -25,6 +31,19 @@ dependencies = [ "memchr", ] +[[package]] +name = "atlas-core" +version = "0.1.0" +dependencies = [ + "atlas-embed", + "base64 0.22.1", + "rusqlite", + "serde", + "serde_json", + "thiserror", + "ureq", +] + [[package]] name = "atlas-embed" version = "0.1.0" @@ -48,12 +67,30 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "castaway" version = "0.2.4" @@ -94,6 +131,15 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -200,24 +246,76 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "esaxx-rs" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -230,12 +328,62 @@ dependencies = [ "wasip2", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "itertools" version = "0.14.0" @@ -267,6 +415,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "log" version = "0.4.35" @@ -311,6 +470,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "monostate" version = "0.1.18" @@ -444,6 +613,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -530,7 +705,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ - "getrandom", + "getrandom 0.3.4", ] [[package]] @@ -599,6 +774,69 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -647,6 +885,8 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash 0.2.0", + "indexmap", "itoa", "memchr", "serde", @@ -660,6 +900,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "smallvec" version = "1.16.4" @@ -672,7 +918,7 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" dependencies = [ - "base64", + "base64 0.13.1", "nom", "serde", "unicode-segmentation", @@ -690,6 +936,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -744,7 +996,7 @@ dependencies = [ "dary_heap", "derive_builder", "esaxx-rs", - "getrandom", + "getrandom 0.3.4", "itertools", "log", "macro_rules_attribute", @@ -811,12 +1063,65 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -826,12 +1131,94 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -858,6 +1245,18 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/pkgs/atlas-search/Cargo.toml b/pkgs/atlas-search/Cargo.toml index dbbe244204..91775b88b6 100644 --- a/pkgs/atlas-search/Cargo.toml +++ b/pkgs/atlas-search/Cargo.toml @@ -4,7 +4,7 @@ # Self-contained workspace on the pkgs/id pattern. Crates land one step at # a time; step 1 (#5351) is atlas-embed only. [workspace] -members = ["crates/atlas-embed"] +members = ["crates/atlas-embed", "crates/atlas-core"] resolver = "2" [workspace.package] diff --git a/pkgs/atlas-search/crates/atlas-core/Cargo.toml b/pkgs/atlas-search/crates/atlas-core/Cargo.toml new file mode 100644 index 0000000000..d741af697d --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "atlas-core" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Atlas search semantics as a library: filters and sensitivity ceilings, FTS + vector branches, RRF fusion, the result envelope, Turso and Local backends. A faithful port of the Python atlas_search.py (developing-today/code#5352, design section 4)." + +[dependencies] +atlas-embed = { path = "../atlas-embed" } +base64 = "0.22" +rusqlite = { version = "0.37", features = ["bundled"] } +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["preserve_order"] } +thiserror = "2" +ureq = { version = "3", features = ["rustls"] } + +[dev-dependencies] +serde_json = { version = "1", features = ["preserve_order"] } diff --git a/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs b/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs new file mode 100644 index 0000000000..fa96cf395b --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/examples/live_smoke.rs @@ -0,0 +1,148 @@ +//! LIVE SMOKE (manual; not a CI test) — step 2's verification +//! gate, second half: for a handful of diverse real questions, +//! the Rust scan path's fused top-10 over production Turso must +//! match the deployed Python CLI's top-10 exactly (same corpus, +//! same config: hybrid, pool 100, ceiling personal, RRF k=10). +//! +//! READ-ONLY against production: the Turso token flow resolves +//! a read-only token (env → Bitwarden → 20h cache → mint), and +//! both implementations only ever SELECT. +//! +//! Run on the laptop: +//! +//! ```sh +//! source ~/step2-env.sh +//! cargo run -p atlas-core --example live_smoke --release +//! ``` +//! +//! Env knobs: `ATLAS_ORT_LIB` (default: the v3 venv's +//! libonnxruntime), `ATLAS_MODEL_DIR` (default: the pinned HF +//! snapshot from step 1). Questions can be passed as arguments; +//! otherwise a built-in diverse set is used. +//! +//! Loader note: dlopen'ing the venv's libonnxruntime needs an +//! x86-64 `libstdc++.so.6` + `libz.so.1` on `LD_LIBRARY_PATH` +//! (the Python wrapper probes the nix store for the same pair). +//! Prefix the run with e.g. +//! `LD_LIBRARY_PATH=/nix/store/<...>-gcc-<...>-lib/lib:/nix/store/<...>-zlib-<...>/lib`. +//! Step 5's nix packaging must carry both in the closure (the +//! opencode#1554 lesson, designed into #5355). +//! +//! Recorded run (2026-11-04, production corpus, scan backend): +//! 6 of 6 questions matched the Python CLI's top-10 exactly. + +use std::process::Command; + +use atlas_core::{ + AtlasEmbedder, DEFAULT_VEC_TABLE, Filters, SearchOptions, TursoBackend, run_search, +}; +use serde_json::Value as Json; + +const DEFAULT_ORT_LIB: &str = "/home/user/atlas/v3-venv/lib/python3.14/site-packages/onnxruntime/capi/libonnxruntime.so.1.31.1"; +const DEFAULT_MODEL_DIR: &str = "/home/user/.cache/huggingface/hub/models--Snowflake--snowflake-arctic-embed-m-v2.0/snapshots/95c2741480856aa9666782eb4afe11959938017f"; +const PYTHON_CLI: &str = "/home/user/.local/bin/atlas-search"; + +const DEFAULT_QUESTIONS: [&str; 6] = [ + "how do we back up the database", + "what did we decide about the Muse subscription quota pools", + "nixpkgs update workflow for the fleet", + "how does the atlas search ranking work", + "what happened with the cutter package build failure", + "explain the reflective event archive design", +]; + +fn top10(env: &Json) -> Vec { + env["results"] + .as_array() + .map(|rs| rs.iter().filter_map(|r| r["chunk_id"].as_i64()).collect()) + .unwrap_or_default() +} + +fn python_top10(question: &str) -> Result, String> { + let out = Command::new(PYTHON_CLI) + .args(["search", question]) + .output() + .map_err(|e| format!("spawn python cli: {e}"))?; + if !out.status.success() { + return Err(format!( + "python cli exit {}: {}", + out.status, + String::from_utf8_lossy(&out.stderr) + )); + } + let env: Json = serde_json::from_slice(&out.stdout) + .map_err(|e| format!("python cli output not JSON: {e}"))?; + Ok(top10(&env)) +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let questions: Vec = if args.is_empty() { + DEFAULT_QUESTIONS.iter().map(|s| s.to_string()).collect() + } else { + args + }; + let ort_lib = std::env::var("ATLAS_ORT_LIB").unwrap_or_else(|_| DEFAULT_ORT_LIB.to_string()); + let model_dir = + std::env::var("ATLAS_MODEL_DIR").unwrap_or_else(|_| DEFAULT_MODEL_DIR.to_string()); + + let embedder = atlas_embed::Embedder::load( + std::path::Path::new(&model_dir), + std::path::Path::new(&ort_lib), + ) + .expect("load embedder"); + let embedder = AtlasEmbedder::new(embedder); + let backend = TursoBackend::new(DEFAULT_VEC_TABLE).expect("turso backend (token flow)"); + let filters = Filters::new( + Vec::new(), + Vec::new(), + Vec::new(), + Vec::new(), + "personal", + None, + None, + ) + .expect("filters"); + + let mut failures = 0; + for q in &questions { + let opts = SearchOptions::new(q.clone()); + let rust_env = match run_search(&backend, &embedder, &filters, &opts) { + Ok(env) => env, + Err(e) => { + println!("Q: {q}\n RUST ERROR: {e}"); + failures += 1; + continue; + } + }; + let rust_top = top10(&rust_env); + let py_top = match python_top10(q) { + Ok(v) => v, + Err(e) => { + println!("Q: {q}\n PYTHON ERROR: {e}"); + failures += 1; + continue; + } + }; + if rust_top == py_top { + println!("Q: {q}\n MATCH top10 = {rust_top:?}"); + } else { + failures += 1; + let first_diff = rust_top + .iter() + .zip(py_top.iter()) + .position(|(a, b)| a != b) + .unwrap_or_else(|| rust_top.len().min(py_top.len())); + println!( + "Q: {q}\n MISMATCH (first diff at rank {})\n rust: {rust_top:?}\n python: {py_top:?}", + first_diff + 1 + ); + } + } + println!( + "\n{} of {} questions matched exactly", + questions.len() - failures, + questions.len() + ); + std::process::exit(if failures == 0 { 0 } else { 1 }); +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/backend.rs b/pkgs/atlas-search/crates/atlas-core/src/backend.rs new file mode 100644 index 0000000000..fea4ab639c --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/backend.rs @@ -0,0 +1,52 @@ +//! The `SearchBackend` seam (design section 4): everything the +//! search orchestration needs from a data source, with the ceiling +//! enforced inside branch construction. Two implementations ship in +//! this crate: [`crate::turso::TursoBackend`] (libsql HTTPS pipeline, +//! read-only token) and [`crate::local::LocalBackend`] (SQLite +//! publish files; side stores joined by content hash). + +use crate::error::Result; +use crate::filters::Filters; +use crate::types::{BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow}; + +pub trait SearchBackend { + /// `"turso"` or `"local"` (the envelope's `backend` field). + fn name(&self) -> &'static str; + + fn vec_table(&self) -> &str; + + /// Notes the backend has accumulated (setup notes, load-time + /// coverage notes), in the order the Python appends them to + /// `be.notes`. The orchestration snapshots this before and after + /// the branch run, mirroring the Python's late-note fold. + fn notes(&self) -> Vec; + + /// Whether a vector store backs this backend (`None` = the + /// question does not apply, i.e. Turso). Drives the Python's + /// "no vector store found" note for the local backend. + fn has_vector_store(&self) -> Option { + None + } + + /// Run the branches and return the pre-filtered, ranked pools. + /// Classification filters and the sensitivity ceiling are + /// applied inside, BEFORE ranking — a restricted chunk is never + /// ranked, scored, or snippeted for a caller whose ceiling + /// excludes it. + fn branch_pools(&self, q: &BranchQuery, filters: &Filters) -> Result; + + /// Detail rows for explicit chunk ids (the Python's + /// `fetch_details`). Like the Python, this is a by-id lookup + /// with no ceiling filtering: the search path only ever passes + /// ids its pre-filtered branches produced, and `get-chunk` is an + /// explicit-id tool. Absent ids are simply missing from the + /// result. + fn chunk_details(&self, ids: &[i64]) -> Result>; + + /// Same-message neighbor rows around (`message_id`, any + /// `chunk_idx` in the window), ordered by chunk_idx. + fn neighbors(&self, message_id: &str, chunk_idx: i64, n: i64) -> Result>; + + /// One message row by id (for `--with-message` payloads). + fn message(&self, message_id: &str) -> Result>; +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/embed.rs b/pkgs/atlas-search/crates/atlas-core/src/embed.rs new file mode 100644 index 0000000000..0150e43693 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/embed.rs @@ -0,0 +1,120 @@ +//! Query embedding at the library boundary (design sections 4/5). +//! +//! The Python's `embed_query` contract for the Snowflake model: +//! sentence-transformers applies the model's own query prompt +//! (`prompt_name="query"`), then truncation (Matryoshka) slices, +//! then the vector is L2-renormalized. atlas-embed deliberately +//! ships the prompt step to this layer: for +//! `snowflake-arctic-embed-m-v2.0` the shipped query prompt is the +//! string prefix `"query: "`, and the production corpus was embedded +//! prompt-free on the document side (documents never pass through +//! here). + +use std::sync::Mutex; + +use crate::error::{Error, Result}; + +/// The query prompt ST applies for the pinned model +/// (`config_sentence_transformers.json`: `prompts.query`). +pub const QUERY_PROMPT: &str = "query: "; + +/// A query embedder: raw text in, production-shaped query vector +/// out (prompt applied by the implementation, truncated and +/// renormalized by the shared tail in this module). +pub trait QueryEmbedder { + fn embed_query(&self, text: &str, trunc: usize) -> Result>; +} + +/// The shared tail of the Python's `embed_query`: slice to `trunc` +/// dims if asked, then renormalize; a zero vector is fatal there and +/// here. The norm is NumPy's (pairwise f32 sum of squares), via +/// atlas-embed's replicated summation. +pub fn finish_query_vector(mut v: Vec, trunc: usize) -> Result> { + if trunc > 0 { + v.truncate(trunc); + } + let squares: Vec = v.iter().map(|x| x * x).collect(); + let n = atlas_embed::pairwise_sum_f32(&squares).sqrt(); + if n == 0.0 { + return Err(Error::fatal("query embedding produced a zero vector")); + } + for x in v.iter_mut() { + *x /= n; + } + Ok(v) +} + +/// A fixed-vector embedder for tests and fixture work: stands in for +/// a real model exactly where the Python's fixture generator +/// monkeypatches `embed_query`. The prompt step is bypassed (the +/// recorded vector already represents a query embedding). +pub struct FixedEmbedder { + pub raw: Vec, +} + +impl QueryEmbedder for FixedEmbedder { + fn embed_query(&self, _text: &str, trunc: usize) -> Result> { + finish_query_vector(self.raw.clone(), trunc) + } +} + +/// The production query embedder over atlas-embed. The embedder's +/// `Session::run` takes `&mut self` (step 1 finding), so concurrent +/// callers serialize on a mutex: one resident session, queries +/// served one at a time. Serve mode (step 4) should hold exactly one +/// of these per process (or a small pool behind the same mutex +/// shape) rather than an embedder per request — session load is the +/// expensive, ~1.6 GB-RSS part, and it is shared state by design. +pub struct AtlasEmbedder { + inner: Mutex, +} + +impl AtlasEmbedder { + pub fn new(embedder: atlas_embed::Embedder) -> AtlasEmbedder { + AtlasEmbedder { + inner: Mutex::new(embedder), + } + } +} + +impl QueryEmbedder for AtlasEmbedder { + fn embed_query(&self, text: &str, trunc: usize) -> Result> { + let prompted = format!("{QUERY_PROMPT}{text}"); + let mut guard = self + .inner + .lock() + .map_err(|_| Error::Embed("embedder mutex poisoned".to_string()))?; + let out = guard + .embed(&[prompted.as_str()]) + .map_err(|e| Error::Embed(e.to_string()))?; + let v = out.into_iter().next().map(|a| a.to_vec()).ok_or_else(|| { + Error::Embed("embedder returned no vector for a single input".to_string()) + })?; + finish_query_vector(v, trunc) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finish_normalizes_and_truncates() { + let v = finish_query_vector(vec![3.0, 4.0], 0).unwrap(); + assert!((v[0] - 0.6).abs() < 1e-7 && (v[1] - 0.8).abs() < 1e-7); + let v = finish_query_vector(vec![3.0, 4.0, 5.0], 2).unwrap(); + assert_eq!(v.len(), 2); + assert!((v[0] - 0.6).abs() < 1e-7); + assert!(finish_query_vector(vec![0.0, 0.0], 0).is_err()); + } + + #[test] + fn fixed_embedder_roundtrip() { + let e = FixedEmbedder { + raw: vec![0.9, 0.3, 0.1], + }; + let v = e.embed_query("anything", 0).unwrap(); + let n = (0.9f32 * 0.9 + 0.3 * 0.3 + 0.1 * 0.1).sqrt(); + assert!((v[0] - 0.9 / n).abs() < 1e-6); + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/error.rs b/pkgs/atlas-search/crates/atlas-core/src/error.rs new file mode 100644 index 0000000000..aa8e618b5f --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/error.rs @@ -0,0 +1,27 @@ +//! Error type for atlas-core. Messages that correspond to the +//! Python's `die()` texts keep the Python's wording, so CLI surfaces +//! (step 3) print what the Python prints today. + +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// A user-facing fatal, mirroring a Python `die()` message. + #[error("{0}")] + Fatal(String), + /// A backend/transport/SQL failure. + #[error("{0}")] + Backend(String), + /// Query embedding failure (including atlas-embed's). + #[error("{0}")] + Embed(String), +} + +impl Error { + pub fn fatal(msg: impl Into) -> Error { + Error::Fatal(msg.into()) + } + pub fn backend(msg: impl Into) -> Error { + Error::Backend(msg.into()) + } +} + +pub type Result = std::result::Result; diff --git a/pkgs/atlas-search/crates/atlas-core/src/filters.rs b/pkgs/atlas-search/crates/atlas-core/src/filters.rs new file mode 100644 index 0000000000..3e58db15b0 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/filters.rs @@ -0,0 +1,620 @@ +//! Filters, sensitivity ceilings, and SQL construction — a faithful +//! port of the Python's `Filters` class and the branch/detail SQL +//! builders. SQL strings are assembled with the same fragment +//! concatenation the Python's f-strings use (including the double +//! space the empty Turso `sens_join` leaves in two statements): the +//! strings are the contract with the database, and the parity +//! fixtures record them byte-for-byte. + +use serde_json::{Map, Value as Json}; + +use crate::error::{Error, Result}; +use crate::types::{Stmt, Value}; + +/// The sensitivity ladder, least to most restricted (Python +/// `SENS_ORDER`). A ceiling admits its own level and everything +/// below it. +pub const SENS_ORDER: [&str; 4] = ["shareable", "personal", "local-only", "secret-bearing"]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Sensitivity { + Shareable, + Personal, + LocalOnly, + SecretBearing, +} + +impl Sensitivity { + pub fn from_name(name: &str) -> Option { + match name { + "shareable" => Some(Sensitivity::Shareable), + "personal" => Some(Sensitivity::Personal), + "local-only" => Some(Sensitivity::LocalOnly), + "secret-bearing" => Some(Sensitivity::SecretBearing), + _ => None, + } + } + + pub fn name(self) -> &'static str { + SENS_ORDER[self as usize] + } + + /// Every level a ceiling admits, in ladder order (the Python's + /// `SENS_ORDER[:index+1]`). + pub fn allowed(self) -> Vec<&'static str> { + SENS_ORDER[..=self as usize].to_vec() + } +} + +impl Default for Sensitivity { + /// The production default ceiling. + fn default() -> Self { + Sensitivity::Personal + } +} + +/// The per-backend SQL shape the builders parameterize on (the +/// Python's backend class attributes). +#[derive(Debug, Clone, Copy)] +pub struct BackendShape { + pub sens_expr: &'static str, + pub labels_table: &'static str, + pub sens_join: &'static str, +} + +pub const TURSO_SHAPE: BackendShape = BackendShape { + sens_expr: "c.sensitivity", + labels_table: "session_labels", + sens_join: "", +}; + +pub const LOCAL_SHAPE: BackendShape = BackendShape { + sens_expr: "cs.sensitivity", + labels_table: "v_labels", + sens_join: "LEFT JOIN v_chunk_sens cs ON cs.id = c.id", +}; + +/// The Python's `split_csv`: comma-split, trimmed, empties dropped. +pub fn split_csv(v: Option<&str>) -> Vec { + match v { + None => Vec::new(), + Some(s) => s + .split(',') + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(str::to_string) + .collect(), + } +} + +/// Classification + ceiling filters (the Python's `Filters`). +#[derive(Debug, Clone, Default)] +pub struct Filters { + pub kinds: Vec, + pub topics: Vec, + pub projects: Vec, + pub clients: Vec, + pub max_sensitivity: Sensitivity, + pub since: Option, + /// The `until` date as given (used by `describe` and validation). + pub until: Option, + /// `until` + 1 day, the exclusive SQL bound. + pub until_exclusive: Option, +} + +impl Filters { + /// Build with the Python's validation (its `die()` texts on bad + /// ceiling / date inputs). `until` is stored raw; the exclusive + /// bound is computed from the parsed date. + pub fn new( + kinds: Vec, + topics: Vec, + projects: Vec, + clients: Vec, + max_sensitivity: &str, + since: Option, + until: Option, + ) -> Result { + let ceiling = Sensitivity::from_name(max_sensitivity).ok_or_else(|| { + Error::fatal( + "--max-sensitivity must be one of \ + ['shareable', 'personal', 'local-only', 'secret-bearing']", + ) + })?; + let mut until_exclusive = None; + if let Some(u) = &until { + let d = parse_iso_date(u) + .ok_or_else(|| Error::fatal(format!("--until must be YYYY-MM-DD, got {u}")))?; + until_exclusive = Some(format_iso_date(add_one_day(d))); + } + if let Some(s) = &since { + parse_iso_date(s) + .ok_or_else(|| Error::fatal(format!("--since must be YYYY-MM-DD, got {s}")))?; + } + Ok(Filters { + kinds, + topics, + projects, + clients, + max_sensitivity: ceiling, + since, + until, + until_exclusive, + }) + } + + pub fn allowed_sens(&self) -> Vec<&'static str> { + self.max_sensitivity.allowed() + } + + fn joins(&self, shape: BackendShape) -> String { + format!( + "JOIN messages m ON m.id = c.message_id \ + JOIN sessions s ON s.id = m.session_id \ + LEFT JOIN {} l ON l.session_id = s.id {}", + shape.labels_table, shape.sens_join + ) + } + + /// The Python's `Filters.where`: full WHERE fragment (ceiling + /// always applied; NULL sensitivity never passes) + params. + pub fn where_clause(&self, shape: BackendShape) -> (String, Vec) { + let mut clauses: Vec = Vec::new(); + let mut params: Vec = Vec::new(); + let allowed = self.allowed_sens(); + clauses.push(format!( + "{} IN ({})", + shape.sens_expr, + placeholders(allowed.len()) + )); + params.extend(allowed.iter().map(|s| Value::text(*s))); + for (col, vals) in [("l.kind", &self.kinds), ("s.client", &self.clients)] { + if !vals.is_empty() { + clauses.push(format!("{col} IN ({})", placeholders(vals.len()))); + params.extend(vals.iter().map(|v| Value::text(v.clone()))); + } + } + for (col, vals) in [("l.topics", &self.topics), ("l.projects", &self.projects)] { + for v in vals { + clauses.push(format!("{col} LIKE ?")); + params.push(Value::text(format!("%\"{v}\"%"))); + } + } + if let Some(s) = &self.since { + clauses.push("s.created_at >= ?".to_string()); + params.push(Value::text(s.clone())); + } + if let Some(u) = &self.until_exclusive { + clauses.push("s.created_at < ?".to_string()); + params.push(Value::text(u.clone())); + } + (clauses.join(" AND "), params) + } + + /// The Python's `Filters.session_clauses`: session-level filters + /// only (everything except the ceiling), with caller-chosen + /// aliases, for the Turso vector branch's IN-subquery. + pub fn session_clauses(&self, s_alias: &str, l_alias: &str) -> (Vec, Vec) { + let mut clauses: Vec = Vec::new(); + let mut params: Vec = Vec::new(); + for (col, vals) in [ + (format!("{l_alias}.kind"), &self.kinds), + (format!("{s_alias}.client"), &self.clients), + ] { + if !vals.is_empty() { + clauses.push(format!("{col} IN ({})", placeholders(vals.len()))); + params.extend(vals.iter().map(|v| Value::text(v.clone()))); + } + } + for (col, vals) in [ + (format!("{l_alias}.topics"), &self.topics), + (format!("{l_alias}.projects"), &self.projects), + ] { + for v in vals { + clauses.push(format!("{col} LIKE ?")); + params.push(Value::text(format!("%\"{v}\"%"))); + } + } + if let Some(s) = &self.since { + clauses.push(format!("{s_alias}.created_at >= ?")); + params.push(Value::text(s.clone())); + } + if let Some(u) = &self.until_exclusive { + clauses.push(format!("{s_alias}.created_at < ?")); + params.push(Value::text(u.clone())); + } + (clauses, params) + } + + /// The Python's `Filters.describe` (field order preserved). + pub fn describe(&self) -> Json { + let mut d = Map::new(); + d.insert( + "max_sensitivity".to_string(), + Json::from(self.max_sensitivity.name()), + ); + let mut list = |key: &str, vals: &Vec| { + if !vals.is_empty() { + d.insert(key.to_string(), Json::from(vals.clone())); + } + }; + list("kind", &self.kinds); + list("topic", &self.topics); + list("project", &self.projects); + list("client", &self.clients); + if let Some(s) = &self.since { + d.insert("since".to_string(), Json::from(s.clone())); + } + if let Some(u) = &self.until { + d.insert("until".to_string(), Json::from(u.clone())); + } + Json::Object(d) + } +} + +fn placeholders(n: usize) -> String { + vec!["?"; n].join(",") +} + +/// The FTS branch statement (shared by both backends; the Python +/// builds the identical text in `branch_queries` and in the local +/// path of `run_search`). +pub fn fts_stmt(shape: BackendShape, filters: &Filters, match_expr: &str, pool: usize) -> Stmt { + let (where_sql, params) = filters.where_clause(shape); + let sql = format!( + "SELECT c.id AS cid FROM chunks c \ + JOIN chunks_fts f ON f.rowid = c.id {} \ + WHERE chunks_fts MATCH ? AND {where_sql} \ + ORDER BY bm25(chunks_fts) LIMIT ?", + filters.joins(shape) + ); + let mut args = vec![Value::text(match_expr)]; + args.extend(params); + args.push(Value::Integer(pool as i64)); + Stmt::new(sql, args) +} + +/// The Turso scan vector-branch statement (chunks-join ceiling + +/// optional session-filter IN-subquery; see the Python's +/// `branch_queries` docstring for why the full join is avoided). +pub fn turso_vector_scan_stmt( + vec_table: &str, + filters: &Filters, + qvec_json: &str, + pool: usize, +) -> Stmt { + let allowed = filters.allowed_sens(); + let mut sql = format!( + "SELECT v.chunk_id AS cid, vector_distance_cos(v.vec, vector32(?)) AS dist \ + FROM {vec_table} v JOIN chunks c ON c.id = v.chunk_id \ + WHERE c.sensitivity IN ({})", + placeholders(allowed.len()) + ); + let mut args: Vec = vec![Value::text(qvec_json)]; + args.extend(allowed.iter().map(|s| Value::text(*s))); + let (sess_clauses, sess_params) = filters.session_clauses("s2", "l2"); + if !sess_clauses.is_empty() { + sql.push_str( + " AND v.chunk_id IN (SELECT c2.id FROM chunks c2 \ + JOIN messages m2 ON m2.id = c2.message_id \ + JOIN sessions s2 ON s2.id = m2.session_id \ + LEFT JOIN session_labels l2 ON l2.session_id = s2.id \ + WHERE ", + ); + sql.push_str(&sess_clauses.join(" AND ")); + sql.push(')'); + args.extend(sess_params); + } + sql.push_str(" ORDER BY dist ASC LIMIT ?"); + args.push(Value::Integer(pool as i64)); + Stmt::new(sql, args) +} + +/// The Python's `branch_queries`: [FTS?, vector-scan?] in order. +pub fn branch_queries( + shape: BackendShape, + vec_table: &str, + filters: &Filters, + match_expr: Option<&str>, + qvec_json: Option<&str>, + pool: usize, +) -> Vec { + let mut stmts = Vec::new(); + if let Some(me) = match_expr { + stmts.push(fts_stmt(shape, filters, me, pool)); + } + if let Some(qj) = qvec_json { + stmts.push(turso_vector_scan_stmt(vec_table, filters, qj, pool)); + } + stmts +} + +/// The local vector branch's allowed-id statement (full joins + +/// full where; the Python's local path of `run_search`). +pub fn local_allowed_stmt(shape: BackendShape, filters: &Filters) -> Stmt { + let (where_sql, params) = filters.where_clause(shape); + Stmt::new( + format!( + "SELECT c.id AS cid FROM chunks c {} WHERE {where_sql}", + filters.joins(shape) + ), + params, + ) +} + +/// Sensitivity half of the Python's `turso_allowed_ids`. +pub fn turso_allowed_sens_stmt(filters: &Filters) -> Stmt { + let allowed = filters.allowed_sens(); + Stmt::new( + format!( + "SELECT c.id AS cid FROM chunks c WHERE c.sensitivity IN ({})", + placeholders(allowed.len()) + ), + allowed.iter().map(|s| Value::text(*s)).collect(), + ) +} + +/// Session-filter half of the Python's `turso_allowed_ids` +/// (`None` when no session-level clause applies). +pub fn turso_allowed_session_stmt(filters: &Filters) -> Option { + let (clauses, params) = filters.session_clauses("s2", "l2"); + if clauses.is_empty() { + return None; + } + Some(Stmt::new( + format!( + "SELECT c2.id AS cid FROM chunks c2 \ + JOIN messages m2 ON m2.id = c2.message_id \ + JOIN sessions s2 ON s2.id = m2.session_id \ + LEFT JOIN session_labels l2 ON l2.session_id = s2.id \ + WHERE {}", + clauses.join(" AND ") + ), + params, + )) +} + +/// The index lookup statement (Turso vector branch, index modes). +pub fn vector_top_k_stmt(vec_table: &str, qvec_json: &str, depth: usize) -> Stmt { + Stmt::new( + "SELECT id FROM vector_top_k(?, vector32(?), ?)", + vec![ + Value::text(format!("{vec_table}_idx")), + Value::text(qvec_json), + Value::Integer(depth as i64), + ], + ) +} + +/// Exact distances for index-branch survivors. +pub fn survivor_dist_stmt(vec_table: &str, qvec_json: &str, survivors: &[i64]) -> Stmt { + let mut args = vec![Value::text(qvec_json)]; + args.extend(survivors.iter().map(|i| Value::Integer(*i))); + Stmt::new( + format!( + "SELECT chunk_id AS cid, vector_distance_cos(vec, vector32(?)) AS dist \ + FROM {vec_table} WHERE chunk_id IN ({})", + placeholders(survivors.len()) + ), + args, + ) +} + +/// The Python's `details_sql` with the placeholder list expanded. +pub fn details_sql(shape: BackendShape, n_ids: usize) -> String { + format!( + "SELECT c.id AS chunk_id, c.text AS text, c.chunk_idx AS chunk_idx, \ + c.message_id AS message_id, m.role AS m_role, m.session_id AS session_id, \ + s.title AS s_title, s.client AS s_client, s.created_at AS s_created_at, \ + l.kind AS l_kind, l.topics AS l_topics, l.projects AS l_projects, \ + l.sensitivity AS l_sensitivity, {} AS chunk_sensitivity \ + FROM chunks c \ + JOIN messages m ON m.id = c.message_id \ + JOIN sessions s ON s.id = m.session_id \ + LEFT JOIN {} l ON l.session_id = s.id {} \ + WHERE c.id IN ({})", + shape.sens_expr, + shape.labels_table, + shape.sens_join, + placeholders(n_ids) + ) +} + +pub const NEIGHBORS_SQL: &str = "SELECT id, chunk_idx, text FROM chunks \ + WHERE message_id = ? AND chunk_idx BETWEEN ? AND ? ORDER BY chunk_idx"; + +pub const MESSAGE_SQL: &str = "SELECT id, role, text FROM messages WHERE id = ?"; + +// ------------------------------------------------------------- dates ---- + +/// (year, month, day) for the ISO forms CPython 3.11+'s +/// `date.fromisoformat` accepts for our inputs: `YYYY-MM-DD` and +/// `YYYYMMDD`, validated as a real calendar date. +pub fn parse_iso_date(s: &str) -> Option<(i32, u32, u32)> { + let b = s.as_bytes(); + let (y, m, d); + if b.len() == 10 && b[4] == b'-' && b[7] == b'-' { + y = digits(&b[0..4])?; + m = digits(&b[5..7])?; + d = digits(&b[8..10])?; + } else if b.len() == 8 { + y = digits(&b[0..4])?; + m = digits(&b[4..6])?; + d = digits(&b[6..8])?; + } else { + return None; + } + if !(1..=12).contains(&m) { + return None; + } + let dim = days_in_month(y, m); + if d < 1 || d > dim { + return None; + } + Some((y as i32, m, d)) +} + +fn digits(b: &[u8]) -> Option { + if b.iter().all(|c| c.is_ascii_digit()) { + b.iter() + .try_fold(0u32, |a, c| Some(a * 10 + u32::from(c - b'0'))) + } else { + None + } +} + +fn days_in_month(y: u32, m: u32) -> u32 { + match m { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 => { + if (y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400) { + 29 + } else { + 28 + } + } + _ => 0, + } +} + +pub fn add_one_day((y, m, d): (i32, u32, u32)) -> (i32, u32, u32) { + if d < days_in_month(y as u32, m) { + (y, m, d + 1) + } else if m < 12 { + (y, m + 1, 1) + } else { + (y + 1, 1, 1) + } +} + +pub fn format_iso_date((y, m, d): (i32, u32, u32)) -> String { + format!("{y:04}-{m:02}-{d:02}") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn default_filters() -> Filters { + Filters::new(vec![], vec![], vec![], vec![], "personal", None, None).unwrap() + } + + #[test] + fn ceiling_prefixes() { + assert_eq!(Sensitivity::Shareable.allowed(), vec!["shareable"]); + assert_eq!( + Sensitivity::Personal.allowed(), + vec!["shareable", "personal"] + ); + assert_eq!(Sensitivity::SecretBearing.allowed(), SENS_ORDER.to_vec()); + assert!(Sensitivity::from_name("bogus").is_none()); + } + + #[test] + fn filters_validation_mirrors_python() { + assert!(Filters::new(vec![], vec![], vec![], vec![], "bogus", None, None).is_err()); + assert!( + Filters::new( + vec![], + vec![], + vec![], + vec![], + "personal", + None, + Some("2026-13-01".into()) + ) + .is_err() + ); + assert!( + Filters::new( + vec![], + vec![], + vec![], + vec![], + "personal", + Some("10/01/2026".into()), + None + ) + .is_err() + ); + let f = Filters::new( + vec![], + vec![], + vec![], + vec![], + "personal", + None, + Some("2026-10-31".into()), + ) + .unwrap(); + assert_eq!(f.until_exclusive.as_deref(), Some("2026-11-01")); + } + + #[test] + fn dates() { + assert_eq!(parse_iso_date("2026-02-29"), None); + assert_eq!(parse_iso_date("2028-02-29"), Some((2028, 2, 29))); + assert_eq!(parse_iso_date("20261031"), Some((2026, 10, 31))); + assert_eq!(add_one_day((2026, 12, 31)), (2027, 1, 1)); + assert_eq!(format_iso_date((2026, 11, 1)), "2026-11-01"); + } + + #[test] + fn where_clause_default_ceiling() { + let f = default_filters(); + let (sql, params) = f.where_clause(TURSO_SHAPE); + assert_eq!(sql, "c.sensitivity IN (?,?)"); + assert_eq!( + params, + vec![Value::text("shareable"), Value::text("personal")] + ); + } + + #[test] + fn session_clauses_exclude_ceiling() { + let f = Filters::new( + vec!["code".into()], + vec![], + vec![], + vec![], + "personal", + None, + None, + ) + .unwrap(); + let (clauses, params) = f.session_clauses("s2", "l2"); + assert_eq!(clauses, vec!["l2.kind IN (?)".to_string()]); + assert_eq!(params, vec![Value::text("code")]); + } + + #[test] + fn describe_shape() { + let f = default_filters(); + assert_eq!( + f.describe(), + serde_json::json!({"max_sensitivity": "personal"}) + ); + let f = Filters::new( + vec!["code".into()], + vec![], + vec![], + vec![], + "personal", + Some("2026-10-01".into()), + None, + ) + .unwrap(); + assert_eq!( + f.describe().to_string(), + "{\"max_sensitivity\":\"personal\",\"kind\":[\"code\"],\"since\":\"2026-10-01\"}" + ); + } + + #[test] + fn split_csv_python() { + assert_eq!(split_csv(None), Vec::::new()); + assert_eq!(split_csv(Some("a, b ,,c")), vec!["a", "b", "c"]); + assert_eq!(split_csv(Some("")), Vec::::new()); + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/fusion.rs b/pkgs/atlas-search/crates/atlas-core/src/fusion.rs new file mode 100644 index 0000000000..57f51f12d0 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/fusion.rs @@ -0,0 +1,206 @@ +//! The FTS match-expression builder and reciprocal rank fusion — +//! ports of the Python's `fts_match_expr` and the fusion block of +//! `run_search`. + +use std::collections::HashMap; + +use serde_json::{Map, Value as Json}; + +use crate::types::BranchHit; + +/// Production RRF constant (decided 2026-10-31; the Python's `RRF_K`). +pub const RRF_K: usize = 10; + +/// The Python's `fts_match_expr` (the eval3.py hybrid-branch +/// construction): content words OR-joined as quoted phrases. Words +/// >3 chars, plus short tokens containing a digit (r2, s3, b2) which +/// > the >3 rule would otherwise silently drop. +pub fn fts_match_expr(query: &str) -> Option { + let lower = query.to_lowercase(); + let mut words: Vec = Vec::new(); + let mut cur = String::new(); + for ch in lower.chars() { + if ch.is_ascii_lowercase() || ch.is_ascii_digit() { + cur.push(ch); + } else if !cur.is_empty() { + words.push(std::mem::take(&mut cur)); + } + } + if !cur.is_empty() { + words.push(cur); + } + let kept: Vec<&String> = words + .iter() + .filter(|w| { + let n = w.chars().count(); + n > 3 || (n >= 2 && w.chars().any(|c| c.is_ascii_digit())) + }) + .collect(); + if kept.is_empty() { + None + } else { + Some( + kept.iter() + .map(|w| format!("\"{w}\"")) + .collect::>() + .join(" OR "), + ) + } +} + +/// One fused candidate (the Python's per-chunk fusion dict). +#[derive(Debug, Clone, PartialEq)] +pub struct FusedEntry { + pub chunk_id: i64, + pub score: f64, + pub fts_rank: Option, + pub vector_rank: Option, +} + +impl FusedEntry { + pub fn min_rank(&self) -> usize { + match (self.fts_rank, self.vector_rank) { + (Some(a), Some(b)) => a.min(b), + (Some(a), None) => a, + (None, Some(b)) => b, + (None, None) => usize::MAX, + } + } + + /// `rank_sources` in the Python's insertion order (fts, vector). + pub fn rank_sources_json(&self) -> Json { + let mut m = Map::new(); + if let Some(r) = self.fts_rank { + m.insert("fts".to_string(), Json::from(r)); + } + if let Some(r) = self.vector_rank { + m.insert("vector".to_string(), Json::from(r)); + } + Json::Object(m) + } +} + +/// Fuse the two branch pools: score += 1/(k+rank) per branch, then +/// order by (-score, best rank, chunk_id) — the Python's sort key. +/// Also returns the per-chunk vector distance map the envelope +/// renders (every vector-pool chunk, not only the kept ones). +pub fn fuse( + fts: &[BranchHit], + vector: &[BranchHit], +) -> (Vec, HashMap>) { + let mut entries: Vec = Vec::new(); + let mut by_id: HashMap = HashMap::new(); + let mut get_or_insert = |entries: &mut Vec, cid: i64| -> usize { + if let Some(&i) = by_id.get(&cid) { + return i; + } + let i = entries.len(); + entries.push(FusedEntry { + chunk_id: cid, + score: 0.0, + fts_rank: None, + vector_rank: None, + }); + by_id.insert(cid, i); + i + }; + for (i, hit) in fts.iter().enumerate() { + let rank = i + 1; + let idx = get_or_insert(&mut entries, hit.chunk_id); + entries[idx].score += 1.0 / (RRF_K + rank) as f64; + entries[idx].fts_rank = Some(rank); + } + let mut vec_dist: HashMap> = HashMap::new(); + for (i, hit) in vector.iter().enumerate() { + let rank = i + 1; + let idx = get_or_insert(&mut entries, hit.chunk_id); + entries[idx].score += 1.0 / (RRF_K + rank) as f64; + entries[idx].vector_rank = Some(rank); + vec_dist.insert(hit.chunk_id, hit.dist); + } + entries.sort_by(|a, b| { + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| a.min_rank().cmp(&b.min_rank())) + .then_with(|| a.chunk_id.cmp(&b.chunk_id)) + }); + (entries, vec_dist) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::round6; + + fn hit(cid: i64, dist: Option) -> BranchHit { + BranchHit { + chunk_id: cid, + dist, + } + } + + #[test] + fn match_expr_rules() { + assert_eq!( + fts_match_expr("how do we back up the database").as_deref(), + Some("\"back\" OR \"database\"") + ); + // short digit tokens survive; plain short words do not + assert_eq!( + fts_match_expr("is r2 down or s3").as_deref(), + Some("\"r2\" OR \"down\" OR \"s3\"") + ); + assert_eq!(fts_match_expr("how do we"), None); + assert_eq!(fts_match_expr(""), None); + // case folds; punctuation separates + assert_eq!( + fts_match_expr("Back-up, DATABASE!").as_deref(), + Some("\"back\" OR \"database\"") + ); + } + + #[test] + fn rrf_known_decompositions() { + // 1/(10+1) + 1/(10+1) = 0.181818 (fixture hybrid_default top hit) + let (fused, _) = fuse(&[hit(1, None)], &[hit(1, Some(0.001))]); + assert_eq!(round6(fused[0].score), 0.181818); + // 1/(10+2) + 1/(10+1) = 0.174242 (production-verified example) + let (fused, _) = fuse( + &[hit(9, None), hit(1, None)], + &[hit(1, Some(0.001)), hit(9, Some(0.5))], + ); + assert_eq!(fused[0].chunk_id, 1); + assert_eq!(round6(fused[0].score), 0.174242); + assert_eq!( + fused[0].rank_sources_json().to_string(), + "{\"fts\":2,\"vector\":1}" + ); + // single-branch: 1/(10+1) = 0.090909 + let (fused, _) = fuse(&[], &[hit(7, Some(0.9))]); + assert_eq!(round6(fused[0].score), 0.090909); + // 1/(10+3) + 1/(10+84) = 0.087561 (production-verified example) + let mut vec: Vec = (0..83).map(|i| hit(1000 + i, Some(0.5))).collect(); + vec.push(hit(42, Some(0.5))); + let (fused, dist) = fuse(&[hit(1, None), hit(2, None), hit(42, None)], &vec); + let e42 = fused.iter().find(|e| e.chunk_id == 42).unwrap(); + assert_eq!(round6(e42.score), 0.087561); + assert_eq!(dist.get(&42), Some(&Some(0.5))); + } + + #[test] + fn fuse_sort_tie_breaks() { + // equal fused scores fall to best rank, then chunk_id + let (fused, _) = fuse( + &[hit(5, None), hit(3, None)], + &[hit(3, Some(0.1)), hit(5, Some(0.2))], + ); + // both chunks: 1/11+1/12 vs 1/12+1/11 -- identical sums; chunk 3 + // has best rank 1 (vector), chunk 5 has best rank 1 (fts): + // still tied -> chunk_id order + assert_eq!(fused[0].score, fused[1].score); + assert_eq!(fused[0].min_rank(), fused[1].min_rank()); + assert_eq!(fused[0].chunk_id, 3); + assert_eq!(fused[1].chunk_id, 5); + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs new file mode 100644 index 0000000000..68f815318d --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -0,0 +1,47 @@ +//! atlas-core — the Atlas corpus-search pipeline as a library +//! (developing-today/code#5352), a semantics-exact port of the +//! production Python `atlas_search.py`. +//! +//! Shape: a [`SearchBackend`] (Turso over the HTTPS pipeline +//! API, or a local SQLite publish file) gathers an FTS pool and +//! a vector pool with the caller's sensitivity ceiling and +//! filters applied **inside the branch queries** — before any +//! ranking — and [`run_search`] fuses the pools with reciprocal +//! rank fusion (k = 10, pool 100/branch by default). +//! +//! Vector strategies all live behind the backend: +//! [`VectorBackend::Scan`] (exact `vector_distance_cos` over the +//! allowed set — the current production path and the default), +//! [`VectorBackend::IndexFill`] (ANN index, depth escalates +//! until the pool survives the filter), and +//! [`VectorBackend::IndexFixed`] (single fixed-depth fetch). +//! Which index strategy becomes the default is decided at the +//! #5356 cutover from A/B evidence, not here. +//! +//! Concurrency note for front-ends (steps 3–4): the library is +//! synchronous; backends are `Send + Sync` behind interior +//! locks. The query embedder is the exception — see +//! [`AtlasEmbedder`]'s docs: ONNX sessions take `&mut self`, so +//! serve mode holds ONE embedder (or a small pool) behind a +//! mutex; session load (~1.6 GB RSS) is shared state by design, +//! never per-request. + +pub mod backend; +pub mod embed; +pub mod error; +pub mod filters; +pub mod fusion; +pub mod local; +pub mod search; +pub mod turso; +pub mod types; + +pub use backend::SearchBackend; +pub use embed::{AtlasEmbedder, FixedEmbedder, QUERY_PROMPT, QueryEmbedder}; +pub use error::{Error, Result}; +pub use filters::{Filters, Sensitivity}; +pub use fusion::{FusedEntry, RRF_K}; +pub use local::LocalBackend; +pub use search::{SearchMode, SearchOptions, run_get_chunk, run_search}; +pub use turso::TursoBackend; +pub use types::{BranchQuery, DEFAULT_MODEL, DEFAULT_VEC_TABLE, VectorBackend}; diff --git a/pkgs/atlas-search/crates/atlas-core/src/local.rs b/pkgs/atlas-search/crates/atlas-core/src/local.rs new file mode 100644 index 0000000000..f5c1909f4a --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/local.rs @@ -0,0 +1,662 @@ +//! The Local backend: SQLite publish files, mirroring the Python's +//! `LocalBackend` — schema-normalizing temp views (labels and +//! chunk sensitivity from the file itself or an attached sibling +//! publish copy), vector side stores joined by **content hash** +//! (never chunk_id: the id spaces differ between stores), and an +//! in-process cosine scan (rusqlite's SQLite has no +//! `vector_distance_cos`; the Python uses numpy the same way). + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use rusqlite::{Connection, OpenFlags}; + +use crate::backend::SearchBackend; +use crate::error::{Error, Result}; +use crate::filters::{ + Filters, LOCAL_SHAPE, MESSAGE_SQL, NEIGHBORS_SQL, details_sql, fts_stmt, local_allowed_stmt, +}; +use crate::types::{ + BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, Row, Stmt, Value, + detail_from_row, +}; + +type RValue = rusqlite::types::Value; + +fn to_rvalue(v: &Value) -> RValue { + match v { + Value::Null => RValue::Null, + Value::Integer(i) => RValue::Integer(*i), + Value::Float(f) => RValue::Real(*f), + Value::Text(s) => RValue::Text(s.clone()), + Value::Blob(b) => RValue::Blob(b.clone()), + } +} + +fn from_rvalue(v: RValue) -> Value { + match v { + RValue::Null => Value::Null, + RValue::Integer(i) => Value::Integer(i), + RValue::Real(f) => Value::Float(f), + RValue::Text(s) => Value::Text(s), + RValue::Blob(b) => Value::Blob(b), + } +} + +#[derive(Debug, Clone)] +enum VecSource { + Main, + IdKey(String), + Mapped(String, String), +} + +struct Matrix { + ids: Vec, + rows: Vec>, +} + +/// (vec file, corpus file whose chunks(id, content_hash) maps its +/// ids) — the Python's KNOWN_VEC_PAIRS. +const KNOWN_VEC_PAIRS: [(&str, &str); 4] = [ + ("~/atlas/v3/vec-bge-small.db", "~/atlas/v3/corpus.db"), + ( + "~/atlas/v3/vec-bge-small-topup.db", + "~/atlas/v3/topup-chunks.db", + ), + ( + "~/atlas/atlas-delta-chunks2.db", + "~/atlas/atlas-delta-chunks2.db", + ), + ("~/atlas/v3/vec-snowflake.db", "~/atlas/v3/corpus.db"), +]; + +fn expanduser(p: &str) -> String { + if let Some(rest) = p.strip_prefix("~/") + && let Some(home) = std::env::var_os("HOME") + { + return PathBuf::from(home) + .join(rest) + .to_string_lossy() + .into_owned(); + } + p.to_string() +} + +pub struct LocalBackend { + db_path: String, + con: Mutex, + vec_table: String, + trunc: usize, + notes: Mutex>, + /// Diagnostics the Python keeps; not part of the envelope. + pub sens_source: String, + pub chunk_sens_source: String, + vec_sources: Vec, + matrix: Mutex>>, +} + +impl LocalBackend { + /// Mirror of the Python constructor: `db_path` must exist; + /// `vecdb_arg` corresponds to `--vecdb` (falling back to the + /// `ATLAS_VEC_DB` env var, as the Python does). + pub fn new( + db_path: &str, + vecdb_arg: Option<&str>, + vec_table: &str, + trunc: usize, + ) -> Result { + if !Path::new(db_path).exists() { + return Err(Error::fatal(format!( + "local backend: DB not found: {db_path}" + ))); + } + let con = Connection::open_with_flags( + format!("file:{db_path}?mode=ro"), + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI, + ) + .map_err(|e| Error::backend(format!("local backend: open {db_path}: {e}")))?; + let mut be = LocalBackend { + db_path: db_path.to_string(), + con: Mutex::new(con), + vec_table: vec_table.to_string(), + trunc, + notes: Mutex::new(Vec::new()), + sens_source: String::new(), + chunk_sens_source: String::new(), + vec_sources: Vec::new(), + matrix: Mutex::new(None), + }; + be.setup_views()?; + be.vec_sources = be.find_vec_sources(vecdb_arg)?; + Ok(be) + } + + fn push_note(&self, note: String) { + self.notes.lock().expect("notes mutex").push(note); + } + + fn tables(&self, schema: &str) -> Result> { + let con = self.con.lock().expect("connection mutex"); + let mut stmt = con + .prepare(&format!( + "SELECT name FROM {schema}.sqlite_master WHERE type IN ('table','view')" + )) + .map_err(|e| Error::backend(e.to_string()))?; + let rows = stmt + .query_map([], |r| r.get::<_, String>(0)) + .map_err(|e| Error::backend(e.to_string()))?; + let mut out = HashSet::new(); + for r in rows { + out.insert(r.map_err(|e| Error::backend(e.to_string()))?); + } + Ok(out) + } + + fn cols(&self, table: &str, schema: &str) -> Result> { + let con = self.con.lock().expect("connection mutex"); + let mut stmt = con + .prepare(&format!("PRAGMA {schema}.table_info({table})")) + .map_err(|e| Error::backend(e.to_string()))?; + let rows = stmt + .query_map([], |r| r.get::<_, String>(1)) + .map_err(|e| Error::backend(e.to_string()))?; + let mut out = HashSet::new(); + for r in rows { + out.insert(r.map_err(|e| Error::backend(e.to_string()))?); + } + Ok(out) + } + + fn exec_void(&self, sql: &str, params: &[RValue]) -> Result<()> { + let con = self.con.lock().expect("connection mutex"); + con.execute(sql, rusqlite::params_from_iter(params.iter())) + .map_err(|e| Error::backend(e.to_string()))?; + Ok(()) + } + + /// The Python's `_setup_views`. + fn setup_views(&mut self) -> Result<()> { + let main_tables = self.tables("main")?; + let mut aux: Option = None; + if !main_tables.contains("session_labels") + || !self.cols("chunks", "main")?.contains("sensitivity") + { + // Look for a publish copy beside the DB (newest first). + let db_abs = std::fs::canonicalize(&self.db_path).unwrap_or_default(); + let dir = db_abs.parent().map(Path::to_path_buf).unwrap_or_default(); + let mut sibs: Vec<(std::time::SystemTime, PathBuf)> = Vec::new(); + if let Ok(rd) = std::fs::read_dir(&dir) { + for ent in rd.flatten() { + let p = ent.path(); + let name = ent.file_name().to_string_lossy().into_owned(); + if name.starts_with("atlas-publish-") && name.ends_with(".db") { + if let Ok(canon) = std::fs::canonicalize(&p) + && canon == db_abs + { + continue; + } + let mtime = ent + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(std::time::SystemTime::UNIX_EPOCH); + sibs.push((mtime, p)); + } + } + } + sibs.sort_by_key(|e| std::cmp::Reverse(e.0)); + for (_, sib) in sibs { + let uri = format!("file:{}?mode=ro", sib.to_string_lossy()); + if self + .exec_void("ATTACH DATABASE ?1 AS aux", &[RValue::Text(uri)]) + .is_ok() + { + aux = Some(sib.to_string_lossy().into_owned()); + break; + } + } + if let Some(a) = &aux { + let base = Path::new(a) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + self.push_note(format!( + "labels/sensitivity attached from sibling publish copy {base}" + )); + } + } + let aux_tables = if aux.is_some() { + self.tables("aux")? + } else { + HashSet::new() + }; + if main_tables.contains("session_labels") { + self.exec_void( + "CREATE TEMP VIEW v_labels AS SELECT * FROM main.session_labels", + &[], + )?; + self.sens_source = "session_labels (this DB)".to_string(); + } else if aux_tables.contains("session_labels") { + self.exec_void( + "CREATE TEMP VIEW v_labels AS SELECT * FROM aux.session_labels", + &[], + )?; + self.sens_source = "session_labels (attached publish copy)".to_string(); + } else { + self.exec_void( + "CREATE TEMP TABLE v_labels (session_id TEXT PRIMARY KEY, client TEXT, \ + kind TEXT, topics TEXT, projects TEXT, sensitivity TEXT, \ + confidence TEXT, scheme TEXT)", + &[], + )?; + self.sens_source = "none — this DB carries no labels".to_string(); + self.push_note( + "no session_labels available: kind/topic/project filters match nothing".to_string(), + ); + } + if self.cols("chunks", "main")?.contains("sensitivity") { + self.exec_void( + "CREATE TEMP VIEW v_chunk_sens AS SELECT id, sensitivity FROM main.chunks", + &[], + )?; + self.chunk_sens_source = "chunks.sensitivity (this DB)".to_string(); + } else if aux.is_some() && self.cols("chunks", "aux")?.contains("sensitivity") { + self.exec_void( + "CREATE TEMP VIEW v_chunk_sens AS SELECT id, sensitivity FROM aux.chunks", + &[], + )?; + self.chunk_sens_source = "chunks.sensitivity (attached publish copy)".to_string(); + } else { + self.exec_void( + "CREATE TEMP TABLE v_chunk_sens (id INTEGER PRIMARY KEY, sensitivity TEXT)", + &[], + )?; + self.chunk_sens_source = "none — no sensitivity data available".to_string(); + self.push_note( + "WARNING: no sensitivity data in this DB and no publish copy beside it; \ + the sensitivity ceiling excludes every chunk (fail-closed). \ + Point --db at a publish copy to search this corpus." + .to_string(), + ); + } + Ok(()) + } + + /// The Python's `_find_vec_sources`. + fn find_vec_sources(&self, vecdb_arg: Option<&str>) -> Result> { + if self.tables("main")?.contains(&self.vec_table) { + return Ok(vec![VecSource::Main]); + } + let env = match vecdb_arg { + Some(v) if !v.is_empty() => Some(v.to_string()), + _ => std::env::var("ATLAS_VEC_DB").ok().filter(|v| !v.is_empty()), + }; + if let Some(env) = env { + return Ok(env + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(|p| VecSource::IdKey(p.to_string())) + .collect()); + } + let mut out = Vec::new(); + let mut seen_vec: HashSet = HashSet::new(); + for (vec_rel, map_rel) in KNOWN_VEC_PAIRS { + let vec_p = expanduser(vec_rel); + let map_p = expanduser(map_rel); + if seen_vec.contains(&vec_p) + || !Path::new(&vec_p).exists() + || !Path::new(&map_p).exists() + { + continue; + } + let probe = Connection::open_with_flags( + format!("file:{vec_p}?mode=ro"), + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI, + ); + let Ok(probe) = probe else { continue }; + let tabs: HashSet = probe + .prepare("SELECT name FROM sqlite_master WHERE type IN ('table','view')") + .and_then(|mut s| { + let rows = s.query_map([], |r| r.get::<_, String>(0))?; + let mut set = HashSet::new(); + for r in rows { + set.insert(r?); + } + Ok(set) + }) + .unwrap_or_default(); + if !tabs.contains(&self.vec_table) { + continue; + } + seen_vec.insert(vec_p.clone()); + out.push(VecSource::Mapped(vec_p, map_p)); + } + if !out.is_empty() { + self.push_note(format!( + "vectors: {} side store(s) mapped by content_hash \ + (id spaces differ between stores; content_hash is the identity)", + out.len() + )); + } + Ok(out) + } + + fn execute(&self, stmt: &Stmt) -> Result> { + let con = self.con.lock().expect("connection mutex"); + let mut prepared = con + .prepare(&stmt.sql) + .map_err(|e| Error::backend(e.to_string()))?; + let col_names: Vec = prepared + .column_names() + .into_iter() + .map(str::to_string) + .collect(); + let params: Vec = stmt.args.iter().map(to_rvalue).collect(); + let mut rows = prepared + .query(rusqlite::params_from_iter(params.iter())) + .map_err(|e| Error::backend(e.to_string()))?; + let mut out = Vec::new(); + while let Some(row) = rows.next().map_err(|e| Error::backend(e.to_string()))? { + let mut pairs = Vec::with_capacity(col_names.len()); + for (i, name) in col_names.iter().enumerate() { + let v = row + .get::<_, RValue>(i) + .map_err(|e| Error::backend(e.to_string()))?; + pairs.push((name.clone(), from_rvalue(v))); + } + out.push(Row::new(pairs)); + } + Ok(out) + } + + fn execute_scalar_i64(&self, sql: &str) -> Result { + let rows = self.execute(&Stmt::new(sql, vec![]))?; + Ok(match rows.first().and_then(|r| r.first_value()) { + Some(Value::Integer(i)) => *i, + Some(Value::Float(f)) => *f as i64, + _ => 0, + }) + } + + /// The Python's `load_matrix` body: gather vectors from + /// all sources (first source wins per chunk), keyed into + /// the main DB's id space (side stores via content hash), + /// rows L2-normalized. + fn build_matrix(&self) -> Result> { + let total_chunks = self.execute_scalar_i64("SELECT count(*) FROM chunks")?; + let mut vec_by_id: HashMap> = HashMap::new(); + let mut mapped_used = false; + for (i, src) in self.vec_sources.iter().enumerate() { + match src { + VecSource::Main => { + let rows = self.execute(&Stmt::new( + format!("SELECT chunk_id, vec FROM main.{}", self.vec_table), + vec![], + ))?; + for r in &rows { + if let (Some(cid), Some(Value::Blob(b))) = + (r.get_i64("chunk_id"), r.get("vec")) + { + vec_by_id.entry(cid).or_insert_with(|| b.clone()); + } + } + } + VecSource::IdKey(path) => { + let schema = format!("vx{i}"); + let uri = format!("file:{path}?mode=ro"); + self.exec_void( + &format!("ATTACH DATABASE ?1 AS {schema}"), + &[RValue::Text(uri)], + )?; + if !self.tables(&schema)?.contains(&self.vec_table) { + continue; + } + let rows = self.execute(&Stmt::new( + format!("SELECT chunk_id, vec FROM {schema}.{}", self.vec_table), + vec![], + ))?; + for r in &rows { + if let (Some(cid), Some(Value::Blob(b))) = + (r.get_i64("chunk_id"), r.get("vec")) + { + vec_by_id.entry(cid).or_insert_with(|| b.clone()); + } + } + } + VecSource::Mapped(vec_p, map_p) => { + mapped_used = true; + let vschema = format!("vm{i}"); + let uri = format!("file:{vec_p}?mode=ro"); + self.exec_void( + &format!("ATTACH DATABASE ?1 AS {vschema}"), + &[RValue::Text(uri)], + )?; + let mschema = if map_p != vec_p { + let mschema = format!("mm{i}"); + let muri = format!("file:{map_p}?mode=ro"); + self.exec_void( + &format!("ATTACH DATABASE ?1 AS {mschema}"), + &[RValue::Text(muri)], + )?; + mschema + } else { + vschema.clone() + }; + if !self.tables(&vschema)?.contains(&self.vec_table) { + continue; + } + let mut id2hash: HashMap = HashMap::new(); + for r in &self.execute(&Stmt::new( + format!("SELECT id, content_hash FROM {mschema}.chunks"), + vec![], + ))? { + if let (Some(id), Some(h)) = (r.get_i64("id"), r.get_text("content_hash")) { + id2hash.insert(id, h.to_string()); + } + } + let mut hash2main: HashMap = HashMap::new(); + for r in &self.execute(&Stmt::new( + "SELECT id, content_hash FROM main.chunks", + vec![], + ))? { + if let (Some(id), Some(h)) = (r.get_i64("id"), r.get_text("content_hash")) { + hash2main.insert(h.to_string(), id); + } + } + let rows = self.execute(&Stmt::new( + format!("SELECT chunk_id, vec FROM {vschema}.{}", self.vec_table), + vec![], + ))?; + for r in &rows { + if let (Some(cid), Some(Value::Blob(b))) = + (r.get_i64("chunk_id"), r.get("vec")) + && let Some(mid) = id2hash.get(&cid).and_then(|h| hash2main.get(h)) + { + vec_by_id.entry(*mid).or_insert_with(|| b.clone()); + } + } + } + } + } + if mapped_used { + self.push_note(format!( + "vector coverage: {} of {} chunks have vectors via content-hash mapping", + vec_by_id.len(), + total_chunks + )); + } + let mut ids: Vec = vec_by_id.keys().copied().collect(); + ids.sort_unstable(); + if ids.is_empty() { + return Ok(None); + } + let mut rows_out: Vec> = Vec::with_capacity(ids.len()); + for id in ids.iter() { + let blob = &vec_by_id[id]; + if !blob.len().is_multiple_of(4) { + return Err(Error::backend(format!( + "vector blob for chunk {id} is {} bytes, not a multiple of 4", + blob.len() + ))); + } + let mut v: Vec = blob + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + if self.trunc > 0 { + v.truncate(self.trunc); + } + let squares: Vec = v.iter().map(|x| x * x).collect(); + let norm = atlas_embed::pairwise_sum_f32(&squares).sqrt(); + if norm > 0.0 { + for x in v.iter_mut() { + *x /= norm; + } + } + rows_out.push(v); + } + Ok(Some(Matrix { + ids, + rows: rows_out, + })) + } + + /// Lazily build (once) and lend the matrix, the way the + /// Python's `load_matrix` returns the cached arrays. + fn with_matrix(&self, f: impl FnOnce(Option<&Matrix>) -> Result) -> Result { + let mut cache = self.matrix.lock().expect("matrix mutex"); + if cache.is_none() { + let built = self.build_matrix()?; + *cache = Some(built); + } + let slot = cache.as_ref().expect("matrix cache filled"); + f(slot.as_ref()) + } + + /// The Python's `vector_search`: cosine sims over the allowed + /// subset (or everything), best `pool` in rank order. + /// Dot products sum with atlas-embed's NumPy-pairwise order; + /// ties keep ascending chunk-id order (the matrix's storage + /// order). numpy's argsort is unstable, so exact float ties are + /// the one place ordering can differ from the Python in + /// principle; well-separated corpora do not produce them. + fn vector_search( + &self, + qvec: &[f32], + allowed: Option<&HashSet>, + pool: usize, + ) -> Result> { + self.with_matrix(|matrix| { + let Some(matrix) = matrix else { + return Ok(Vec::new()); + }; + let mut cand: Vec<(i64, f32)> = Vec::new(); + for (pos, id) in matrix.ids.iter().enumerate() { + if let Some(a) = allowed + && !a.contains(id) + { + continue; + } + let row = &matrix.rows[pos]; + let products: Vec = row.iter().zip(qvec.iter()).map(|(a, b)| a * b).collect(); + let sim = atlas_embed::pairwise_sum_f32(&products); + cand.push((*id, sim)); + } + cand.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + cand.truncate(pool); + Ok(cand) + }) + } +} + +impl SearchBackend for LocalBackend { + fn name(&self) -> &'static str { + "local" + } + + fn vec_table(&self) -> &str { + &self.vec_table + } + + fn notes(&self) -> Vec { + self.notes.lock().expect("notes mutex").clone() + } + + fn has_vector_store(&self) -> Option { + Some(!self.vec_sources.is_empty()) + } + + fn branch_pools(&self, q: &BranchQuery, filters: &Filters) -> Result { + let mut pools = BranchPools::default(); + if let Some(me) = &q.match_expr { + let rows = self.execute(&fts_stmt(LOCAL_SHAPE, filters, me, q.pool))?; + pools.fts = rows + .iter() + .filter_map(|r| { + Some(BranchHit { + chunk_id: r.get_i64("cid")?, + dist: None, + }) + }) + .collect(); + } + if let Some(qvec) = &q.query_vector { + let rows = self.execute(&local_allowed_stmt(LOCAL_SHAPE, filters))?; + let allowed: HashSet = rows.iter().filter_map(|r| r.get_i64("cid")).collect(); + let hits = self.vector_search(qvec, Some(&allowed), q.pool)?; + pools.vector = hits + .into_iter() + .map(|(cid, sim)| BranchHit { + chunk_id: cid, + dist: Some(1.0 - f64::from(sim)), + }) + .collect(); + } + Ok(pools) + } + + fn chunk_details(&self, ids: &[i64]) -> Result> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let sql = details_sql(LOCAL_SHAPE, ids.len()); + let args: Vec = ids.iter().map(|i| Value::Integer(*i)).collect(); + let rows = self.execute(&Stmt::new(sql, args))?; + Ok(rows.iter().filter_map(detail_from_row).collect()) + } + + fn neighbors(&self, message_id: &str, chunk_idx: i64, n: i64) -> Result> { + let rows = self.execute(&Stmt::new( + NEIGHBORS_SQL, + vec![ + Value::text(message_id), + Value::Integer(chunk_idx - n), + Value::Integer(chunk_idx + n), + ], + ))?; + Ok(rows + .iter() + .filter_map(|r| { + Some(NeighborRow { + chunk_id: r.get_i64("id")?, + chunk_idx: r.get_i64("chunk_idx")?, + text: r.get_text("text")?.to_string(), + }) + }) + .collect()) + } + + fn message(&self, message_id: &str) -> Result> { + let rows = self.execute(&Stmt::new(MESSAGE_SQL, vec![Value::text(message_id)]))?; + Ok(rows.first().and_then(|r| { + Some(MessageRow { + id: r.get_text("id")?.to_string(), + role: r.get_text("role").map(str::to_string), + text: r.get_text("text").unwrap_or("").to_string(), + }) + })) + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/search.rs b/pkgs/atlas-search/crates/atlas-core/src/search.rs new file mode 100644 index 0000000000..d983c53d3f --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/search.rs @@ -0,0 +1,472 @@ +//! Search orchestration and envelope rendering — the Python's +//! module-level `run_search` / `run_get_chunk` / `result_entry` / +//! `grouped_output` / `envelope`, minus argparse and printing +//! (front-ends own those). The JSON shapes, field order, note +//! placement and fatal messages mirror the Python exactly; the +//! parity tests diff rendered envelopes against envelopes +//! recorded from the production module. + +use std::collections::HashMap; + +use serde_json::{Map, Value as Json, json}; + +use crate::backend::SearchBackend; +use crate::embed::QueryEmbedder; +use crate::error::{Error, Result}; +use crate::filters::Filters; +use crate::fusion::{FusedEntry, fts_match_expr, fuse}; +use crate::types::{BranchQuery, ChunkDetail, DEFAULT_MODEL, VectorBackend, round6}; + +/// The Python's `MESSAGE_TEXT_CAP`. +pub const MESSAGE_TEXT_CAP: usize = 50_000; + +/// Which branches run — the CLI's `--mode`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SearchMode { + Fts, + Vector, + #[default] + Hybrid, +} + +impl SearchMode { + pub fn as_str(&self) -> &'static str { + match self { + SearchMode::Fts => "fts", + SearchMode::Vector => "vector", + SearchMode::Hybrid => "hybrid", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "fts" => Some(SearchMode::Fts), + "vector" => Some(SearchMode::Vector), + "hybrid" => Some(SearchMode::Hybrid), + _ => None, + } + } + + fn uses_fts(&self) -> bool { + matches!(self, SearchMode::Fts | SearchMode::Hybrid) + } + + fn uses_vector(&self) -> bool { + matches!(self, SearchMode::Vector | SearchMode::Hybrid) + } +} + +/// Everything `run_search` reads from the Python's argparse +/// namespace. Defaults are the production CLI defaults. +#[derive(Debug, Clone)] +pub struct SearchOptions { + pub query: String, + pub mode: SearchMode, + /// Top-k results (grouped: top-k sessions). Default 10. + pub k: usize, + /// Per-branch candidate pool. Default 100. + pub pool: usize, + pub group_by_session: bool, + /// Neighbor chunks to attach around each hit (0 = off). + pub expand: usize, + pub with_message: bool, + /// Provenance strings, recorded verbatim in the envelope's + /// `vector` block (the Python takes them from CLI args). + pub model: String, + pub embedder_label: String, + /// Query-vector truncation (0 = full width). + pub trunc: usize, + pub vector_backend: VectorBackend, +} + +impl Default for SearchOptions { + fn default() -> Self { + SearchOptions { + query: String::new(), + mode: SearchMode::Hybrid, + k: 10, + pool: 100, + group_by_session: false, + expand: 0, + with_message: false, + model: DEFAULT_MODEL.to_string(), + embedder_label: "auto".to_string(), + trunc: 0, + vector_backend: VectorBackend::Scan, + } + } +} + +impl SearchOptions { + pub fn new(query: impl Into) -> Self { + SearchOptions { + query: query.into(), + ..SearchOptions::default() + } + } +} + +/// The Python's `run_search`. The embedder is only invoked for +/// vector/hybrid modes; the filters' ceiling is enforced inside +/// the backend's branch construction (filter-before-rank). +pub fn run_search( + backend: &dyn SearchBackend, + embedder: &dyn QueryEmbedder, + filters: &Filters, + opts: &SearchOptions, +) -> Result { + if opts.mode.uses_vector() + && opts.vector_backend != VectorBackend::Scan + && backend.name() != "turso" + { + return Err(Error::fatal( + "--vector-backend index modes need the turso backend \ + (the vector index lives in the Turso publish)", + )); + } + let match_expr = if opts.mode.uses_fts() { + fts_match_expr(&opts.query) + } else { + None + }; + if opts.mode == SearchMode::Fts && match_expr.is_none() { + return Err(Error::fatal( + "query has no FTS-searchable terms (all words too short); try --mode vector", + )); + } + let qvec = if opts.mode.uses_vector() { + Some(embedder.embed_query(&opts.query, opts.trunc)?) + } else { + None + }; + + let mut notes = backend.notes(); + if backend.has_vector_store() == Some(false) && opts.mode.uses_vector() { + notes.push( + "no vector store found for the local backend; vector branch returned nothing" + .to_string(), + ); + } + let pools = backend.branch_pools( + &BranchQuery { + match_expr, + query_vector: qvec, + pool: opts.pool, + vector_backend: opts.vector_backend, + }, + filters, + )?; + let (ranked, vec_dist) = fuse(&pools.fts, &pools.vector); + + // The local backend learns things mid-search (vector + // coverage); fold any late notes in before rendering. + for n in backend.notes() { + if !notes.contains(&n) { + notes.push(n); + } + } + + let mut out = if opts.group_by_session { + grouped_output(backend, opts, filters, &ranked, &vec_dist, ¬es)? + } else { + let keep = &ranked[..opts.k.min(ranked.len())]; + let ids: Vec = keep.iter().map(|e| e.chunk_id).collect(); + let details = details_map(backend, &ids)?; + let mut results = Vec::new(); + for e in keep { + let Some(d) = details.get(&e.chunk_id) else { + continue; + }; + results.push(result_entry(backend, opts, e, d, &vec_dist)?); + } + envelope(backend, opts, filters, Json::Array(results), ¬es) + }; + if opts.mode.uses_vector() { + // Provenance: exactly which model/table produced the pool. + let mut v = Map::new(); + v.insert("model".into(), Json::String(opts.model.clone())); + v.insert( + "table".into(), + Json::String(backend.vec_table().to_string()), + ); + v.insert("embedder".into(), Json::String(opts.embedder_label.clone())); + v.insert( + "trunc".into(), + if opts.trunc > 0 { + json!(opts.trunc) + } else { + Json::Null + }, + ); + v.insert("pool".into(), json!(opts.pool)); + v.insert( + "vector_backend".into(), + Json::String(opts.vector_backend.as_str().to_string()), + ); + out.as_object_mut() + .expect("envelope is an object") + .insert("vector".into(), Json::Object(v)); + } + Ok(out) +} + +/// The Python's `run_get_chunk`: a by-id lookup with NO +/// sensitivity ceiling (an explicit-id tool, like the Python). +pub fn run_get_chunk(backend: &dyn SearchBackend, chunk_id: i64, neighbors: usize) -> Result { + let details = backend.chunk_details(&[chunk_id])?; + let Some(d) = details.iter().find(|d| d.chunk_id == chunk_id) else { + return Err(Error::fatal(format!("chunk {chunk_id} not found"))); + }; + let mut msg = Map::new(); + msg.insert("id".into(), Json::String(d.message_id.clone())); + msg.insert( + "role".into(), + d.m_role + .as_ref() + .map_or(Json::Null, |r| Json::String(r.clone())), + ); + msg.insert("session_id".into(), Json::String(d.session_id.clone())); + let mut out = Map::new(); + out.insert("chunk_id".into(), json!(d.chunk_id)); + out.insert("text".into(), Json::String(d.text.clone())); + out.insert("chunk_idx".into(), json!(d.chunk_idx)); + out.insert("message".into(), Json::Object(msg)); + out.insert("session".into(), session_obj(d)); + out.insert("session_id".into(), Json::String(d.session_id.clone())); + if neighbors > 0 { + out.insert("context".into(), neighbor_map(backend, d, neighbors)?); + } + let notes = backend.notes(); + if !notes.is_empty() { + out.insert("notes".into(), json!(notes)); + } + Ok(Json::Object(out)) +} + +fn details_map(backend: &dyn SearchBackend, ids: &[i64]) -> Result> { + let rows = backend.chunk_details(ids)?; + Ok(rows.into_iter().map(|d| (d.chunk_id, d)).collect()) +} + +fn envelope( + backend: &dyn SearchBackend, + opts: &SearchOptions, + filters: &Filters, + results: Json, + notes: &[String], +) -> Json { + let mut out = Map::new(); + out.insert("query".into(), Json::String(opts.query.clone())); + out.insert("mode".into(), Json::String(opts.mode.as_str().to_string())); + out.insert("backend".into(), Json::String(backend.name().to_string())); + out.insert("filters_applied".into(), filters.describe()); + out.insert("results".into(), results); + if !notes.is_empty() { + out.insert("notes".into(), json!(notes)); + } + Json::Object(out) +} + +fn session_obj(d: &ChunkDetail) -> Json { + let mut s = Map::new(); + s.insert( + "title".into(), + d.s_title + .as_ref() + .map_or(Json::Null, |v| Json::String(v.clone())), + ); + s.insert( + "client".into(), + d.s_client + .as_ref() + .map_or(Json::Null, |v| Json::String(v.clone())), + ); + s.insert( + "created_at".into(), + d.s_created_at + .as_ref() + .map_or(Json::Null, |v| Json::String(v.clone())), + ); + s.insert( + "kind".into(), + d.l_kind + .as_ref() + .map_or(Json::Null, |v| Json::String(v.clone())), + ); + s.insert( + "topics".into(), + Json::Array(crate::types::parse_json_list(d.l_topics.as_deref())), + ); + s.insert( + "projects".into(), + Json::Array(crate::types::parse_json_list(d.l_projects.as_deref())), + ); + s.insert( + "sensitivity".into(), + d.eff_sensitivity + .as_ref() + .map_or(Json::Null, |v| Json::String(v.clone())), + ); + Json::Object(s) +} + +fn result_entry( + backend: &dyn SearchBackend, + opts: &SearchOptions, + e: &FusedEntry, + d: &ChunkDetail, + vec_dist: &HashMap>, +) -> Result { + let mut entry = Map::new(); + entry.insert("chunk_id".into(), json!(e.chunk_id)); + entry.insert("session_id".into(), Json::String(d.session_id.clone())); + entry.insert("score".into(), json!(round6(e.score))); + entry.insert("rank_sources".into(), e.rank_sources_json()); + entry.insert("text".into(), Json::String(d.text.clone())); + entry.insert("session".into(), session_obj(d)); + entry_chunk_extras(backend, opts, e, d, vec_dist, &mut entry)?; + Ok(Json::Object(entry)) +} + +/// vector_distance / context / message — the trailing fields +/// shared by flat result entries and grouped chunk entries. +fn entry_chunk_extras( + backend: &dyn SearchBackend, + opts: &SearchOptions, + e: &FusedEntry, + d: &ChunkDetail, + vec_dist: &HashMap>, + entry: &mut Map, +) -> Result<()> { + if let Some(Some(dist)) = vec_dist.get(&e.chunk_id) { + entry.insert("vector_distance".into(), json!(round6(*dist))); + } + if opts.expand > 0 { + entry.insert("context".into(), neighbor_map(backend, d, opts.expand)?); + } + if opts.with_message { + entry.insert("message".into(), message_obj(backend, d)?); + } + Ok(()) +} + +/// The Python's `neighbor_map`. +fn neighbor_map(backend: &dyn SearchBackend, d: &ChunkDetail, n: usize) -> Result { + let rows = backend.neighbors(&d.message_id, d.chunk_idx, n as i64)?; + let mut before = Vec::new(); + let mut after = Vec::new(); + for r in &rows { + let item = json!({"chunk_id": r.chunk_id, "text": r.text}); + if r.chunk_idx < d.chunk_idx { + before.push(item); + } else if r.chunk_idx > d.chunk_idx { + after.push(item); + } + } + Ok(json!({"before": before, "after": after})) +} + +/// The Python's `message_obj` (null when the message is gone). +fn message_obj(backend: &dyn SearchBackend, d: &ChunkDetail) -> Result { + let Some(m) = backend.message(&d.message_id)? else { + return Ok(Json::Null); + }; + let truncated = m.text.chars().count() > MESSAGE_TEXT_CAP; + let text: String = m.text.chars().take(MESSAGE_TEXT_CAP).collect(); + Ok(json!({ + "id": m.id, + "role": m.role, + "text": text, + "truncated": truncated, + })) +} + +struct Group { + session_id: String, + score: f64, + hit_count: usize, + first_detail: ChunkDetail, + chunks: Vec<(FusedEntry, ChunkDetail)>, +} + +/// The Python's `grouped_output`: session score = best chunk +/// score; sessions ordered by (best score, hit count), first-seen +/// order breaking full ties (Python's sort is stable; so is +/// Rust's `sort_by`). +fn grouped_output( + backend: &dyn SearchBackend, + opts: &SearchOptions, + filters: &Filters, + ranked: &[FusedEntry], + vec_dist: &HashMap>, + notes: &[String], +) -> Result { + let consideration = &ranked[..(opts.k * 10).max(opts.pool).min(ranked.len())]; + let ids: Vec = consideration.iter().map(|e| e.chunk_id).collect(); + let details = details_map(backend, &ids)?; + let mut order: Vec = Vec::new(); + let mut groups: HashMap = HashMap::new(); + for e in consideration { + let Some(d) = details.get(&e.chunk_id) else { + continue; + }; + let sid = d.session_id.clone(); + if !groups.contains_key(&sid) { + order.push(sid.clone()); + groups.insert( + sid.clone(), + Group { + session_id: sid.clone(), + score: e.score, + hit_count: 0, + first_detail: d.clone(), + chunks: Vec::new(), + }, + ); + } + let g = groups.get_mut(&sid).expect("group just inserted"); + g.hit_count += 1; + if e.score > g.score { + g.score = e.score; + } + g.chunks.push((e.clone(), d.clone())); + } + let mut sorted: Vec = order + .into_iter() + .map(|sid| groups.remove(&sid).expect("group exists")) + .collect(); + sorted.sort_by(|a, b| { + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal) + .then(b.hit_count.cmp(&a.hit_count)) + }); + sorted.truncate(opts.k); + let mut results = Vec::new(); + for g in &sorted { + let mut chunks = Vec::new(); + for (e, d) in g.chunks.iter().take(5) { + let mut ce = Map::new(); + ce.insert("chunk_id".into(), json!(e.chunk_id)); + ce.insert("score".into(), json!(round6(e.score))); + ce.insert("rank_sources".into(), e.rank_sources_json()); + ce.insert("text".into(), Json::String(d.text.clone())); + entry_chunk_extras(backend, opts, e, d, vec_dist, &mut ce)?; + chunks.push(Json::Object(ce)); + } + let mut entry = Map::new(); + entry.insert("session_id".into(), Json::String(g.session_id.clone())); + entry.insert("score".into(), json!(round6(g.score))); + entry.insert("hit_count".into(), json!(g.hit_count)); + entry.insert("session".into(), session_obj(&g.first_detail)); + entry.insert("chunks".into(), Json::Array(chunks)); + results.push(Json::Object(entry)); + } + Ok(envelope( + backend, + opts, + filters, + Json::Array(results), + notes, + )) +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/turso.rs b/pkgs/atlas-search/crates/atlas-core/src/turso.rs new file mode 100644 index 0000000000..b4b7c920af --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/turso.rs @@ -0,0 +1,695 @@ +//! The Turso backend: libsql HTTPS pipeline (`/v2/pipeline`) with a +//! read-only token, mirroring the Python's `TursoBackend` and its +//! token resolution order (env -> Bitwarden by name -> turso CLI +//! mint cache -> turso CLI mint). It never issues writes: every +//! statement this crate builds is a SELECT, and the token it holds +//! is read-only by construction of the resolution chain. + +use std::collections::{HashMap, HashSet}; +use std::io::Read; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use base64::Engine; +use serde_json::{Map, Value as Json, json}; + +use crate::VectorBackend; +use crate::backend::SearchBackend; +use crate::error::{Error, Result}; +use crate::filters::{ + Filters, TURSO_SHAPE, branch_queries, fts_stmt, survivor_dist_stmt, turso_allowed_sens_stmt, + turso_allowed_session_stmt, vector_top_k_stmt, +}; +use crate::types::{ + BranchHit, BranchPools, BranchQuery, ChunkDetail, MessageRow, NeighborRow, Row, Stmt, Value, + detail_from_row, +}; + +pub const TURSO_HOST: &str = "atlas-dezren39.aws-us-east-1.turso.io"; +pub const TURSO_DB: &str = "atlas"; +const BWS_TOKEN_NAMES: [&str; 3] = [ + "turso.atlas-ro-token", + "turso.atlas-read-only-token", + "atlas-ro", +]; + +// ------------------------------------------------------------ hrana ----- + +fn hrana_arg(v: &Value) -> Json { + match v { + Value::Null => json!({"type": "null"}), + Value::Integer(i) => json!({"type": "integer", "value": i.to_string()}), + Value::Float(f) => json!({"type": "float", "value": f}), + Value::Text(s) => json!({"type": "text", "value": s}), + Value::Blob(b) => json!({ + "type": "blob", + "value": base64::engine::general_purpose::STANDARD.encode(b), + }), + } +} + +fn hrana_val(v: &Json) -> Value { + if v.is_null() { + return Value::Null; + } + match v.get("type").and_then(Json::as_str) { + Some("integer") => v + .get("value") + .and_then(Json::as_str) + .and_then(|s| s.parse::().ok()) + .map(Value::Integer) + .unwrap_or(Value::Null), + Some("float") => v + .get("value") + .and_then(Json::as_f64) + .map(Value::Float) + .unwrap_or(Value::Null), + Some("text") => v + .get("value") + .and_then(Json::as_str) + .map(|s| Value::Text(s.to_string())) + .unwrap_or(Value::Null), + Some("blob") => v + .get("value") + .and_then(Json::as_str) + .and_then(|s| base64::engine::general_purpose::STANDARD.decode(s).ok()) + .map(Value::Blob) + .unwrap_or(Value::Null), + _ => Value::Null, + } +} + +/// The query-vector JSON the Python builds with +/// `json.dumps([float(x) for x in qvec])`. +pub fn qvec_json(qvec: &[f32]) -> String { + let vals: Vec = qvec.iter().map(|x| *x as f64).collect(); + serde_json::to_string(&vals).unwrap_or_else(|_| "[]".to_string()) +} + +// --------------------------------------------------------- transport ---- + +/// The pipeline seam: one batched call, one row-set per statement +/// that produced a result. The HTTP implementation is production; +/// tests replay recorded fixtures through a fake. +pub trait PipelineTransport { + fn pipeline(&self, stmts: &[Stmt]) -> Result>>; +} + +pub struct HttpTransport { + agent: ureq::Agent, + url: String, + token: String, +} + +impl HttpTransport { + pub fn new(host: &str, token: String) -> HttpTransport { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(300))) + .http_status_as_error(false) + .build() + .into(); + HttpTransport { + agent, + url: format!("https://{host}/v2/pipeline"), + token, + } + } +} + +impl PipelineTransport for HttpTransport { + fn pipeline(&self, stmts: &[Stmt]) -> Result>> { + let mut requests: Vec = stmts + .iter() + .map(|s| { + json!({ + "type": "execute", + "stmt": { + "sql": s.sql, + "args": s.args.iter().map(hrana_arg).collect::>(), + }, + }) + }) + .collect(); + requests.push(json!({"type": "close"})); + let body = json!({"requests": requests}).to_string(); + let mut resp = self + .agent + .post(&self.url) + .header("Authorization", &format!("Bearer {}", self.token)) + .header("Content-Type", "application/json") + .send(body.as_str()) + .map_err(|e| Error::backend(format!("turso backend: request failed: {e}")))?; + let status = resp.status().as_u16(); + let mut text = String::new(); + resp.body_mut() + .as_reader() + .read_to_string(&mut text) + .map_err(|e| Error::backend(format!("turso backend: read failed: {e}")))?; + if status != 200 { + let snippet: String = text.chars().take(200).collect(); + return Err(Error::fatal(format!( + "turso backend: HTTP {status}: {snippet}" + ))); + } + let out: Json = serde_json::from_str(&text) + .map_err(|e| Error::backend(format!("turso backend: bad JSON: {e}")))?; + let mut results = Vec::new(); + for res in out + .get("results") + .and_then(Json::as_array) + .into_iter() + .flatten() + { + if res.get("type").and_then(Json::as_str) == Some("error") { + let msg = res + .get("error") + .and_then(|e| e.get("message")) + .and_then(Json::as_str) + .unwrap_or(""); + return Err(Error::fatal(format!("turso backend: SQL error: {msg}"))); + } + let Some(result) = res + .get("response") + .and_then(|r| r.get("result")) + .filter(|r| !r.is_null()) + else { + continue; + }; + let cols: Vec = result + .get("cols") + .and_then(Json::as_array) + .map(|cs| { + cs.iter() + .filter_map(|c| c.get("name").and_then(Json::as_str).map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + let mut rows = Vec::new(); + if let Some(raw_rows) = result.get("rows").and_then(Json::as_array) { + for raw in raw_rows { + let mut pairs = Vec::new(); + if let Some(cells) = raw.as_array() { + for (i, cell) in cells.iter().enumerate() { + if let Some(name) = cols.get(i) { + pairs.push((name.clone(), hrana_val(cell))); + } + } + } + rows.push(Row::new(pairs)); + } + } + results.push(rows); + } + Ok(results) + } +} + +// ------------------------------------------------------------- token ---- + +fn home() -> PathBuf { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("~")) +} + +fn token_cache_path() -> PathBuf { + home().join(".cache/atlas-search/turso-token.json") +} + +/// Run a command to completion with a timeout (the Python's +/// subprocess timeouts, coarsely). Returns stdout on success. +fn run_cmd(prog: &str, args: &[&str], envs: &[(&str, &str)], timeout: Duration) -> Option { + let mut cmd = Command::new(prog); + cmd.args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + for (k, v) in envs { + cmd.env(k, v); + } + let mut child = cmd.spawn().ok()?; + let start = std::time::Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => { + if !status.success() { + return None; + } + let mut out = String::new(); + child.stdout.take()?.read_to_string(&mut out).ok()?; + return Some(out); + } + Ok(None) => { + if start.elapsed() > timeout { + let _ = child.kill(); + return None; + } + std::thread::sleep(Duration::from_millis(25)); + } + Err(_) => return None, + } + } +} + +/// The Python's `bws_secret`: fetch one Bitwarden Secrets Manager +/// value by name (the bws CLI, access token from the environment or +/// the fleet's bws-env script). Errors are opaque — the caller +/// treats any failure as "not that source". +fn bws_secret(name: &str) -> Option { + let access = match std::env::var("BWS_ACCESS_TOKEN") { + Ok(t) if !t.is_empty() => t, + _ => { + let script = "source ~/tools/bws-env.sh >/dev/null 2>&1; \ + printf %s \"$BWS_ACCESS_TOKEN\""; + run_cmd("bash", &["-c", script], &[], Duration::from_secs(30))? + } + }; + if access.is_empty() { + return None; + } + let bws = home().join("tools/bin/bws"); + if !bws.exists() { + return None; + } + let bws = bws.to_string_lossy().into_owned(); + let envs = [("BWS_ACCESS_TOKEN", access.as_str())]; + for _ in 0..3 { + let attempt = (|| { + let list = run_cmd( + &bws, + &["secret", "list", "-o", "json"], + &envs, + Duration::from_secs(60), + )?; + let items: Json = serde_json::from_str(&list).ok()?; + let mut sid = None; + for item in items.as_array()? { + if item.get("key").and_then(Json::as_str) == Some(name) { + sid = item.get("id").and_then(Json::as_str).map(str::to_string); + break; + } + } + let sid = sid?; + let got = run_cmd( + &bws, + &["secret", "get", &sid, "-o", "json"], + &envs, + Duration::from_secs(60), + )?; + let val: Json = serde_json::from_str(&got).ok()?; + let v = match &val { + Json::Array(a) => a.first()?.get("value")?, + other => other.get("value")?, + }; + v.as_str().map(str::to_string) + })(); + if attempt.is_some() { + return attempt; + } + } + None +} + +/// The Python's `resolve_turso_token` order, returning (token, +/// source label). Failure carries the Python's composed die text. +pub fn resolve_turso_token() -> Result<(String, String)> { + if let Ok(t) = std::env::var("ATLAS_TURSO_TOKEN") + && !t.is_empty() + { + return Ok((t, "env ATLAS_TURSO_TOKEN".to_string())); + } + for name in BWS_TOKEN_NAMES { + if let Some(t) = bws_secret(name) { + return Ok((t, format!("bitwarden:{name}"))); + } + } + // Cached read-only token minted via the turso CLI (< 20 h old). + if let Ok(text) = std::fs::read_to_string(token_cache_path()) + && let Ok(cache) = serde_json::from_str::>(&text) + { + let fresh = cache + .get("fetched_at") + .and_then(Json::as_f64) + .map(|ts| { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0); + now - ts < 20.0 * 3600.0 + }) + .unwrap_or(false); + if cache.get("db").and_then(Json::as_str) == Some(TURSO_DB) + && fresh + && let Some(t) = cache.get("token").and_then(Json::as_str) + { + return Ok(( + t.to_string(), + "cache (turso CLI read-only mint)".to_string(), + )); + } + } + // Mint read-only via the turso CLI (its tokens carry claim a=ro). + if let Some(out) = run_cmd( + "turso", + &[ + "db", + "tokens", + "create", + TURSO_DB, + "--read-only", + "-e", + "7d", + ], + &[], + Duration::from_secs(60), + ) { + let token = out.trim().to_string(); + if token.matches('.').count() == 2 { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0); + let cache = json!({"db": TURSO_DB, "token": token, "fetched_at": now}); + if let Some(parent) = token_cache_path().parent() { + let _ = std::fs::create_dir_all(parent); + } + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + if let Ok(mut f) = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(token_cache_path()) + { + use std::io::Write; + let _ = f.write_all(cache.to_string().as_bytes()); + } + } + return Ok((token, "turso CLI read-only mint".to_string())); + } + } + Err(Error::fatal( + "turso backend: token did not resolve (no ATLAS_TURSO_TOKEN, no \ + Bitwarden atlas-ro secret, turso CLI mint unavailable). \ + Set ATLAS_TURSO_TOKEN or log the turso CLI in.", + )) +} + +// ----------------------------------------------------------- backend ---- + +pub struct TursoBackend { + transport: T, + vec_table: String, + pub token_source: String, +} + +impl TursoBackend { + /// Connect with a token from the standard resolution chain. + pub fn new(vec_table: &str) -> Result> { + let (token, source) = resolve_turso_token()?; + Ok(TursoBackend { + transport: HttpTransport::new(TURSO_HOST, token), + vec_table: vec_table.to_string(), + token_source: source, + }) + } + + /// Connect with an explicit token (tests, service config). + pub fn with_token(host: &str, token: String, vec_table: &str) -> TursoBackend { + TursoBackend { + transport: HttpTransport::new(host, token), + vec_table: vec_table.to_string(), + token_source: "explicit".to_string(), + } + } +} + +impl TursoBackend { + /// The transport this backend speaks over (test/diagnostic + /// access; the pipeline contract is the hrana HTTP shape). + pub fn transport(&self) -> &T { + &self.transport + } + + pub fn with_transport(transport: T, vec_table: &str) -> TursoBackend { + TursoBackend { + transport, + vec_table: vec_table.to_string(), + token_source: "injected transport".to_string(), + } + } + + fn execute(&self, stmt: &Stmt) -> Result> { + Ok(self + .transport + .pipeline(std::slice::from_ref(stmt))? + .into_iter() + .next() + .unwrap_or_default()) + } + + /// The Python's `turso_allowed_ids`: ceiling set intersected + /// with the session-filter set when any session filter applies. + pub fn allowed_ids(&self, filters: &Filters) -> Result> { + let rows = self.execute(&turso_allowed_sens_stmt(filters))?; + let mut allowed: HashSet = rows.iter().filter_map(|r| r.get_i64("cid")).collect(); + if let Some(stmt) = turso_allowed_session_stmt(filters) { + let rows = self.execute(&stmt)?; + let sess: HashSet = rows.iter().filter_map(|r| r.get_i64("cid")).collect(); + allowed = allowed.intersection(&sess).copied().collect(); + } + Ok(allowed) + } + + /// The Python's `turso_index_branch`. + pub fn index_branch( + &self, + filters: &Filters, + qvec_json: &str, + pool: usize, + vb: VectorBackend, + ) -> Result> { + let allowed = self.allowed_ids(filters)?; + let mut survivors: Vec = Vec::new(); + for depth in index_depths(pool, vb) { + let rows = self.execute(&vector_top_k_stmt(&self.vec_table, qvec_json, depth))?; + survivors = rows + .iter() + .filter_map(|r| r.get_i64("id")) + .filter(|id| allowed.contains(id)) + .take(pool) + .collect(); + if survivors.len() >= pool { + break; + } + } + if survivors.is_empty() { + return Ok(Vec::new()); + } + let rows = self.execute(&survivor_dist_stmt(&self.vec_table, qvec_json, &survivors))?; + let dist: HashMap = rows + .iter() + .filter_map(|r| Some((r.get_i64("cid")?, r.get_f64("dist")?))) + .collect(); + Ok(survivors + .iter() + .map(|cid| BranchHit { + chunk_id: *cid, + dist: dist.get(cid).copied(), + }) + .collect()) + } +} + +/// Retrieval depths for the index modes (the Python's loop): +/// fixed = `[pool]`; fill = pool doubling while < 3200, then 3200. +pub fn index_depths(pool: usize, vb: VectorBackend) -> Vec { + match vb { + VectorBackend::IndexFixed => vec![pool], + VectorBackend::IndexFill => { + if pool == 0 { + // The Python loops forever here (0 doubles to 0); + // a zero pool is a degenerate request, not a hang + // this port reproduces. + return vec![0]; + } + let mut depths = Vec::new(); + let mut d = pool; + while d < 3200 { + depths.push(d); + d *= 2; + } + depths.push(3200); + depths + } + VectorBackend::Scan => Vec::new(), + } +} + +impl SearchBackend for TursoBackend { + fn name(&self) -> &'static str { + "turso" + } + + fn vec_table(&self) -> &str { + &self.vec_table + } + + fn notes(&self) -> Vec { + Vec::new() + } + + fn branch_pools(&self, q: &BranchQuery, filters: &Filters) -> Result { + let qvec_json = q.query_vector.as_ref().map(|v| qvec_json(v)); + let mut pools = BranchPools::default(); + match qvec_json.as_deref() { + // Index strategies: FTS rides its own pipeline call, + // then the index branch (the Python's call pattern). + Some(qj) if q.vector_backend != VectorBackend::Scan => { + if let Some(me) = &q.match_expr { + let stmt = fts_stmt(TURSO_SHAPE, filters, me, q.pool); + let results = self.transport.pipeline(std::slice::from_ref(&stmt))?; + if let Some(rows) = results.into_iter().next() { + pools.fts = rows + .iter() + .filter_map(|r| { + Some(BranchHit { + chunk_id: r.get_i64("cid")?, + dist: None, + }) + }) + .collect(); + } + } + pools.vector = self.index_branch(filters, qj, q.pool, q.vector_backend)?; + } + // Scan (and FTS-only): both branch statements in ONE + // pipeline call, results consumed in statement order. + _ => { + let stmts = branch_queries( + TURSO_SHAPE, + &self.vec_table, + filters, + q.match_expr.as_deref(), + qvec_json.as_deref(), + q.pool, + ); + let results = self.transport.pipeline(&stmts)?; + let mut i = 0; + if q.match_expr.is_some() { + if let Some(rows) = results.get(i) { + pools.fts = rows + .iter() + .filter_map(|r| { + Some(BranchHit { + chunk_id: r.get_i64("cid")?, + dist: None, + }) + }) + .collect(); + } + i += 1; + } + if qvec_json.is_some() + && let Some(rows) = results.get(i) + { + pools.vector = rows + .iter() + .filter_map(|r| { + Some(BranchHit { + chunk_id: r.get_i64("cid")?, + dist: r.get_f64("dist"), + }) + }) + .collect(); + } + } + } + Ok(pools) + } + + fn chunk_details(&self, ids: &[i64]) -> Result> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let sql = crate::filters::details_sql(TURSO_SHAPE, ids.len()); + let args: Vec = ids.iter().map(|i| Value::Integer(*i)).collect(); + let rows = self.execute(&Stmt::new(sql, args))?; + Ok(rows.iter().filter_map(detail_from_row).collect()) + } + + fn neighbors(&self, message_id: &str, chunk_idx: i64, n: i64) -> Result> { + let rows = self.execute(&Stmt::new( + crate::filters::NEIGHBORS_SQL, + vec![ + Value::text(message_id), + Value::Integer(chunk_idx - n), + Value::Integer(chunk_idx + n), + ], + ))?; + Ok(rows + .iter() + .filter_map(|r| { + Some(NeighborRow { + chunk_id: r.get_i64("id")?, + chunk_idx: r.get_i64("chunk_idx")?, + text: r.get_text("text")?.to_string(), + }) + }) + .collect()) + } + + fn message(&self, message_id: &str) -> Result> { + let rows = self.execute(&Stmt::new( + crate::filters::MESSAGE_SQL, + vec![Value::text(message_id)], + ))?; + Ok(rows.first().and_then(|r| { + Some(MessageRow { + id: r.get_text("id")?.to_string(), + role: r.get_text("role").map(str::to_string), + text: r.get_text("text").unwrap_or("").to_string(), + }) + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn depths_fixed_and_fill() { + assert_eq!(index_depths(100, VectorBackend::IndexFixed), vec![100]); + assert_eq!( + index_depths(100, VectorBackend::IndexFill), + vec![100, 200, 400, 800, 1600, 3200] + ); + assert_eq!( + index_depths(3, VectorBackend::IndexFill), + vec![3, 6, 12, 24, 48, 96, 192, 384, 768, 1536, 3072, 3200] + ); + assert_eq!(index_depths(3200, VectorBackend::IndexFill), vec![3200]); + } + + #[test] + fn hrana_roundtrip_shapes() { + assert_eq!( + hrana_arg(&Value::Integer(7)), + json!({"type": "integer", "value": "7"}) + ); + assert_eq!(hrana_arg(&Value::Null), json!({"type": "null"})); + assert_eq!( + hrana_val(&json!({"type": "integer", "value": "42"})), + Value::Integer(42) + ); + assert_eq!( + hrana_val(&json!({"type": "text", "value": "x"})), + Value::text("x") + ); + assert_eq!(hrana_val(&Json::Null), Value::Null); + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/src/types.rs b/pkgs/atlas-search/crates/atlas-core/src/types.rs new file mode 100644 index 0000000000..091259ed2a --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/src/types.rs @@ -0,0 +1,275 @@ +//! Shared value/row model: the least common denominator between the +//! Turso hrana pipeline encoding and rusqlite's value types, mirroring +//! what the Python's row dicts carry. + +use serde_json::Value as Json; + +/// A SQL parameter / column value. +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + Null, + Integer(i64), + Float(f64), + Text(String), + Blob(Vec), +} + +impl Value { + pub fn text(s: impl Into) -> Value { + Value::Text(s.into()) + } + + pub fn as_i64(&self) -> Option { + match self { + Value::Integer(i) => Some(*i), + _ => None, + } + } + + pub fn as_f64(&self) -> Option { + match self { + Value::Float(f) => Some(*f), + Value::Integer(i) => Some(*i as f64), + _ => None, + } + } + + /// Text, preserving Python's `dict.get` semantics: anything that is + /// not a text column reads as `None`. + pub fn as_text(&self) -> Option<&str> { + match self { + Value::Text(s) => Some(s), + _ => None, + } + } + + pub fn is_null(&self) -> bool { + matches!(self, Value::Null) + } +} + +/// One result row: ordered (column name, value) pairs, like the +/// Python's `dict` rows. +#[derive(Debug, Clone, Default)] +pub struct Row { + cols: Vec<(String, Value)>, +} + +impl Row { + pub fn new(cols: Vec<(String, Value)>) -> Row { + Row { cols } + } + + pub fn get(&self, name: &str) -> Option<&Value> { + self.cols.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + + pub fn get_i64(&self, name: &str) -> Option { + self.get(name).and_then(Value::as_i64) + } + + pub fn get_f64(&self, name: &str) -> Option { + self.get(name).and_then(Value::as_f64) + } + + pub fn get_text(&self, name: &str) -> Option<&str> { + self.get(name).and_then(Value::as_text) + } +} + +/// A parametrized SQL statement: the unit both backends execute and +/// the unit the parity fixtures record. +#[derive(Debug, Clone, PartialEq)] +pub struct Stmt { + pub sql: String, + pub args: Vec, +} + +impl Stmt { + pub fn new(sql: impl Into, args: Vec) -> Stmt { + Stmt { + sql: sql.into(), + args, + } + } +} + +/// One branch hit in rank order. `dist` is the cosine distance for +/// vector hits (`None` for FTS hits; the Python carries `None` raw +/// values for the FTS branch and a possibly-missing distance for +/// index-branch survivors). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BranchHit { + pub chunk_id: i64, + pub dist: Option, +} + +/// The fused pools one search runs over. +#[derive(Debug, Clone, Default)] +pub struct BranchPools { + pub fts: Vec, + pub vector: Vec, +} + +/// The branch inputs, mirroring `run_search`'s per-mode state. +#[derive(Debug, Clone)] +pub struct BranchQuery { + pub match_expr: Option, + /// Normalized (and possibly truncated) query vector. + pub query_vector: Option>, + pub pool: usize, + pub vector_backend: crate::VectorBackend, +} + +/// A chunk's detail row (the Python's `fetch_details` output), with +/// effective sensitivity resolved: chunk sensitivity, falling back to +/// the session label's (Python: `chunk_sensitivity or l_sensitivity`). +#[derive(Debug, Clone)] +pub struct ChunkDetail { + pub chunk_id: i64, + pub text: String, + pub chunk_idx: i64, + pub message_id: String, + pub m_role: Option, + pub session_id: String, + pub s_title: Option, + pub s_client: Option, + pub s_created_at: Option, + pub l_kind: Option, + pub l_topics: Option, + pub l_projects: Option, + pub eff_sensitivity: Option, +} + +#[derive(Debug, Clone)] +pub struct NeighborRow { + pub chunk_id: i64, + pub chunk_idx: i64, + pub text: String, +} + +#[derive(Debug, Clone)] +pub struct MessageRow { + pub id: String, + pub role: Option, + pub text: String, +} + +/// The Python's `parse_json_list`: non-list / unparsable / empty +/// inputs all read as an empty list. +pub fn parse_json_list(v: Option<&str>) -> Vec { + let Some(s) = v else { return Vec::new() }; + if s.is_empty() { + return Vec::new(); + } + match serde_json::from_str::(s) { + Ok(Json::Array(items)) => items, + _ => Vec::new(), + } +} + +/// Python's `round(x, 6)`: round the exact binary value to six +/// decimal places (ties to even, as CPython's float round does via +/// correct decimal rounding), then take the nearest f64 — whose +/// shortest repr is the decimal the Python prints. +pub fn round6(x: f64) -> f64 { + if !x.is_finite() { + return x; + } + format!("{x:.6}").parse::().unwrap_or(x) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round6_matches_python() { + assert_eq!(round6(0.17424242424242425), 0.174242); + assert_eq!(round6(1.0 / 11.0), 0.090909); + assert_eq!(round6(0.0), 0.0); + assert_eq!(round6(2.0), 2.0); + assert_eq!(round6(0.0018811234), 0.001881); + } + + #[test] + fn parse_json_list_shapes() { + assert_eq!(parse_json_list(None), Vec::::new()); + assert_eq!(parse_json_list(Some("")), Vec::::new()); + assert_eq!(parse_json_list(Some("not json")), Vec::::new()); + assert_eq!(parse_json_list(Some("{\"a\":1}")), Vec::::new()); + assert_eq!( + parse_json_list(Some("[\"nixos\", \"backup\"]")), + vec![Json::from("nixos"), Json::from("backup")] + ); + } +} + +/// Convert one `details_sql` row into a [`ChunkDetail`], resolving +/// effective sensitivity the Python's way (`chunk or label`). +/// Only the chunk id is structurally required; other columns fall +/// back to empty/None the way the Python's dict reads tolerate. +pub fn detail_from_row(r: &Row) -> Option { + let chunk_sens = r.get_text("chunk_sensitivity").filter(|s| !s.is_empty()); + let eff = chunk_sens + .or_else(|| r.get_text("l_sensitivity")) + .map(str::to_string); + Some(ChunkDetail { + chunk_id: r.get_i64("chunk_id")?, + text: r.get_text("text").unwrap_or("").to_string(), + chunk_idx: r.get_i64("chunk_idx").unwrap_or(0), + message_id: r.get_text("message_id").unwrap_or("").to_string(), + m_role: r.get_text("m_role").map(str::to_string), + session_id: r.get_text("session_id").unwrap_or("").to_string(), + s_title: r.get_text("s_title").map(str::to_string), + s_client: r.get_text("s_client").map(str::to_string), + s_created_at: r.get_text("s_created_at").map(str::to_string), + l_kind: r.get_text("l_kind").map(str::to_string), + l_topics: r.get_text("l_topics").map(str::to_string), + l_projects: r.get_text("l_projects").map(str::to_string), + eff_sensitivity: eff, + }) +} + +impl Row { + /// The first column's value (for single-column queries). + pub fn first_value(&self) -> Option<&Value> { + self.cols.first().map(|(_, v)| v) + } +} + +/// The production vector table (the CLI's `VEC_TABLE`). +pub const DEFAULT_VEC_TABLE: &str = "vec_snowflake_m_v2_768_f32"; + +/// The production embedder identity (the CLI's `MODEL`). +pub const DEFAULT_MODEL: &str = "Snowflake/snowflake-arctic-embed-m-v2.0"; + +/// How the vector branch gathers its pool. The default stays +/// `Scan` (the current production path) until the #5356 +/// golden-parity cutover promotes a winner from the A/B. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum VectorBackend { + #[default] + Scan, + IndexFixed, + IndexFill, +} + +impl VectorBackend { + pub fn as_str(&self) -> &'static str { + match self { + VectorBackend::Scan => "scan", + VectorBackend::IndexFixed => "index-fixed", + VectorBackend::IndexFill => "index-fill", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "scan" => Some(VectorBackend::Scan), + "index-fixed" => Some(VectorBackend::IndexFixed), + "index-fill" => Some(VectorBackend::IndexFill), + _ => None, + } + } +} diff --git a/pkgs/atlas-search/crates/atlas-core/tests/parity.rs b/pkgs/atlas-search/crates/atlas-core/tests/parity.rs new file mode 100644 index 0000000000..17e5eb2c99 --- /dev/null +++ b/pkgs/atlas-search/crates/atlas-core/tests/parity.rs @@ -0,0 +1,428 @@ +//! Parity tests against the production Python `atlas_search.py`. +//! +//! `fixtures/core-expectations.json` was recorded from the real +//! module by `fixtures/gen_core_fixtures.py`: search envelopes +//! over a miniature fixture corpus (LocalBackend, fixture query +//! vector), the Turso branch SQL byte-for-byte, and the +//! `turso_allowed_ids` / `turso_index_branch` call sequences +//! against a recording fake. atlas-core must reproduce all of it. +//! +//! The canary property of the fixture corpus: chunk 5 +//! (secret-bearing) holds the query's exact vector and FTS terms, +//! chunk 6 (local-only) is nearly as close — both must be absent +//! at the default ceiling (filter-before-rank), and chunk 5 must +//! surface at vector rank 1 under a secret-bearing ceiling. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use atlas_core::filters::{Filters, TURSO_SHAPE, branch_queries}; +use atlas_core::turso::{PipelineTransport, TursoBackend}; +use atlas_core::types::{Row, Stmt, Value}; +use atlas_core::{ + DEFAULT_VEC_TABLE, FixedEmbedder, LocalBackend, SearchMode, SearchOptions, VectorBackend, + run_get_chunk, run_search, +}; +use serde_json::Value as Json; + +fn fixtures_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") +} + +fn expectations() -> Json { + let p = fixtures_dir().join("core-expectations.json"); + serde_json::from_str(&std::fs::read_to_string(p).expect("read expectations")) + .expect("parse expectations") +} + +fn fixture_spec() -> Json { + let p = fixtures_dir().join("fixture_spec.json"); + serde_json::from_str(&std::fs::read_to_string(p).expect("read spec")).expect("parse spec") +} + +/// Build the fixture corpus DB in a unique temp dir (the DB file +/// itself is never committed; the generator's SQL + spec are). +fn build_fixture_db(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("atlas-core-parity-{}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir).expect("temp dir"); + let db = dir.join("fixture.db"); + let _ = std::fs::remove_file(&db); + let sql = std::fs::read_to_string(fixtures_dir().join("fixture_corpus.sql")) + .expect("read corpus sql"); + let spec = fixture_spec(); + let con = rusqlite::Connection::open(&db).expect("open fixture db"); + con.execute_batch(&sql).expect("load corpus sql"); + let vectors = spec["vectors"].as_object().expect("spec vectors"); + for (cid, vec) in vectors { + let mut blob = Vec::new(); + for x in vec.as_array().expect("vec array") { + blob.extend_from_slice(&(x.as_f64().expect("f64") as f32).to_le_bytes()); + } + con.execute( + "INSERT INTO vec_snowflake_m_v2_768_f32 (chunk_id, vec) VALUES (?, ?)", + rusqlite::params![cid.parse::().expect("cid"), blob], + ) + .expect("insert vec"); + } + drop(con); + db +} + +fn filters( + kinds: &[&str], + topics: &[&str], + projects: &[&str], + clients: &[&str], + ceiling: &str, + since: Option<&str>, + until: Option<&str>, +) -> Filters { + Filters::new( + kinds.iter().map(|s| s.to_string()).collect(), + topics.iter().map(|s| s.to_string()).collect(), + projects.iter().map(|s| s.to_string()).collect(), + clients.iter().map(|s| s.to_string()).collect(), + ceiling, + since.map(str::to_string), + until.map(str::to_string), + ) + .expect("filters") +} + +fn default_filters() -> Filters { + filters(&[], &[], &[], &[], "personal", None, None) +} + +fn case_request(name: &str) -> (SearchOptions, Filters) { + let mut o = SearchOptions::new("how do we back up the database"); + let f = match name { + "hybrid_default" => default_filters(), + "hybrid_secret_ceiling" => filters(&[], &[], &[], &[], "secret-bearing", None, None), + "hybrid_shareable_ceiling" => filters(&[], &[], &[], &[], "shareable", None, None), + "fts_default" => { + o.mode = SearchMode::Fts; + default_filters() + } + "vector_default" => { + o.mode = SearchMode::Vector; + default_filters() + } + "hybrid_kind_code" => filters(&["code"], &[], &[], &[], "personal", None, None), + "hybrid_topic_nixos" => filters(&[], &["nixos"], &[], &[], "personal", None, None), + "hybrid_client_codex_dates" => filters( + &[], + &[], + &[], + &["codex"], + "personal", + Some("2026-10-01"), + Some("2026-10-31"), + ), + "hybrid_until_before_sB" => filters( + &[], + &[], + &[], + &["codex"], + "personal", + None, + Some("2026-10-19"), + ), + "hybrid_grouped" => { + o.group_by_session = true; + o.k = 2; + default_filters() + } + "hybrid_expand_message" => { + o.expand = 1; + o.with_message = true; + o.k = 3; + default_filters() + } + "hybrid_pool2_k2" => { + o.pool = 2; + o.k = 2; + default_filters() + } + other => panic!("unknown case {other}"), + }; + (o, f) +} + +#[test] +fn local_search_envelopes_match_python() { + let db = build_fixture_db("search"); + let be = + LocalBackend::new(db.to_str().unwrap(), None, DEFAULT_VEC_TABLE, 0).expect("local backend"); + let exp = expectations(); + let qvec_raw: Vec = exp["qvec_raw"] + .as_array() + .unwrap() + .iter() + .map(|x| x.as_f64().unwrap() as f32) + .collect(); + let embedder = FixedEmbedder { raw: qvec_raw }; + for case in exp["search_cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let (opts, f) = case_request(name); + let got = + run_search(&be, &embedder, &f, &opts).unwrap_or_else(|e| panic!("case {name}: {e}")); + assert_eq!( + got, + case["envelope"], + "case {name} envelope mismatch\nrust: {}\npython: {}", + serde_json::to_string_pretty(&got).unwrap(), + serde_json::to_string_pretty(&case["envelope"]).unwrap(), + ); + } +} + +#[test] +fn local_get_chunk_matches_python() { + let db = build_fixture_db("getchunk"); + let be = + LocalBackend::new(db.to_str().unwrap(), None, DEFAULT_VEC_TABLE, 0).expect("local backend"); + let exp = expectations(); + for case in exp["get_chunk_cases"].as_array().unwrap() { + let (cid, neighbors) = match case["name"].as_str().unwrap() { + "get_chunk_secret" => (5, 0), + "get_chunk_neighbors" => (2, 1), + other => panic!("unknown case {other}"), + }; + let got = run_get_chunk(&be, cid, neighbors).expect("get chunk"); + assert_eq!(got, case["envelope"], "case {}", case["name"]); + } +} + +fn json_params_to_values(params: &Json) -> Vec { + params + .as_array() + .unwrap() + .iter() + .map(|p| match p { + Json::String(s) => Value::text(s.clone()), + Json::Number(n) => n + .as_i64() + .map(Value::Integer) + .unwrap_or_else(|| Value::Float(n.as_f64().unwrap())), + Json::Null => Value::Null, + other => panic!("unhandled fixture param {other}"), + }) + .collect() +} + +fn assert_stmts_eq(got: &[Stmt], recorded: &Json, ctx: &str) { + let recorded = recorded.as_array().unwrap(); + assert_eq!(got.len(), recorded.len(), "{ctx}: statement count"); + for (i, (g, r)) in got.iter().zip(recorded.iter()).enumerate() { + assert_eq!(g.sql, r["sql"].as_str().unwrap(), "{ctx}: stmt {i} sql"); + assert_eq!( + g.args, + json_params_to_values(&r["params"]), + "{ctx}: stmt {i} params" + ); + } +} + +#[test] +fn turso_branch_queries_match_python() { + let exp = expectations(); + let me = Some("\"back\" OR \"database\""); + let qj = Some("[0.5, 0.25]"); + for case in exp["turso"]["branch_queries"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let (f, me_arg, qj_arg) = match name { + "defaults" => (default_filters(), me, qj), + "all_filters_secret" => ( + filters( + &["code"], + &["rust"], + &[], + &["codex"], + "secret-bearing", + Some("2026-10-01"), + Some("2026-10-31"), + ), + me, + qj, + ), + "fts_only" => (default_filters(), me, None), + "vector_only" => (default_filters(), None, qj), + other => panic!("unknown case {other}"), + }; + let got = branch_queries(TURSO_SHAPE, DEFAULT_VEC_TABLE, &f, me_arg, qj_arg, 100); + assert_stmts_eq(&got, &case["stmts"], name); + } +} + +/// The recording fake from the generator, speaking the +/// PipelineTransport contract (one call may carry several +/// statements; the Python's fake execute saw them one by one, so +/// calls are recorded flattened, in order). +struct FakeTransport { + calls: Mutex>, +} + +impl FakeTransport { + fn new() -> FakeTransport { + FakeTransport { + calls: Mutex::new(Vec::new()), + } + } + + fn respond(&self, stmt: &Stmt) -> Vec { + let sql = &stmt.sql; + let row = |pairs: Vec<(&str, Value)>| { + Row::new(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) + }; + if sql.contains("vector_top_k") { + let depth = match stmt.args.get(2) { + Some(Value::Integer(i)) => *i, + other => panic!("top_k depth arg: {other:?}"), + }; + let script: &[i64] = match depth { + 3 => &[5, 1, 6], + 6 => &[5, 1, 6, 2, 8, 3], + other => panic!("unscripted depth {other}"), + }; + return script + .iter() + .map(|i| row(vec![("id", Value::Integer(*i))])) + .collect(); + } + if sql.contains("vector_distance_cos") && sql.contains("chunk_id IN") { + let dists: HashMap = [(1, 0.01), (2, 0.3), (8, 0.07)].into_iter().collect(); + return stmt.args[1..] + .iter() + .map(|a| match a { + Value::Integer(cid) => row(vec![ + ("cid", Value::Integer(*cid)), + ("dist", Value::Float(dists[cid])), + ]), + other => panic!("dist arg: {other:?}"), + }) + .collect(); + } + if sql.contains("c.sensitivity") { + return [1, 2, 3, 4, 7, 8] + .iter() + .map(|i| row(vec![("cid", Value::Integer(*i))])) + .collect(); + } + if sql.contains("c2.id") { + return [4, 7] + .iter() + .map(|i| row(vec![("cid", Value::Integer(*i))])) + .collect(); + } + panic!("unexpected SQL: {sql}"); + } + + fn recorded(&self) -> Json { + let calls = self.calls.lock().unwrap(); + Json::Array( + calls + .iter() + .map(|s| { + serde_json::json!({ + "sql": s.sql, + "params": s.args.iter().map(|a| match a { + Value::Text(t) => Json::String(t.clone()), + Value::Integer(i) => Json::from(*i), + Value::Float(f) => Json::from(*f), + Value::Null => Json::Null, + Value::Blob(_) => panic!("blob param in turso fixture"), + }).collect::>(), + }) + }) + .collect(), + ) + } +} + +impl PipelineTransport for FakeTransport { + fn pipeline(&self, stmts: &[Stmt]) -> atlas_core::Result>> { + let mut out = Vec::new(); + for s in stmts { + self.calls.lock().unwrap().push(s.clone()); + out.push(self.respond(s)); + } + Ok(out) + } +} + +#[test] +fn turso_allowed_ids_and_index_branches_match_python() { + let exp = expectations(); + let turso = &exp["turso"]; + + // allowed-ids, no session filters: one statement. + let fake = FakeTransport::new(); + let be = TursoBackend::with_transport(fake, DEFAULT_VEC_TABLE); + let mut got: Vec = be + .allowed_ids(&default_filters()) + .expect("allowed ids") + .into_iter() + .collect(); + got.sort_unstable(); + assert_eq!(Json::from(got), turso["allowed_ids_plain"]["result"]); + assert_eq!( + be.transport().recorded(), + turso["allowed_ids_plain"]["calls"] + ); + + // allowed-ids with a kind filter: sensitivity set ∩ session set. + let fake = FakeTransport::new(); + let be = TursoBackend::with_transport(fake, DEFAULT_VEC_TABLE); + let f = filters(&["code"], &[], &[], &[], "personal", None, None); + let mut got: Vec = be + .allowed_ids(&f) + .expect("allowed ids") + .into_iter() + .collect(); + got.sort_unstable(); + assert_eq!(Json::from(got), turso["allowed_ids_kind"]["result"]); + assert_eq!( + be.transport().recorded(), + turso["allowed_ids_kind"]["calls"] + ); + + // index fetch-to-fill at pool 3: depths 3 then 6, survivors + // [1, 2, 8] in index order, exact distances fetched after. + let fake = FakeTransport::new(); + let be = TursoBackend::with_transport(fake, DEFAULT_VEC_TABLE); + let got = be + .index_branch( + &default_filters(), + "[0.5, 0.25]", + 3, + VectorBackend::IndexFill, + ) + .expect("index fill"); + let got_json = Json::Array( + got.iter() + .map(|h| serde_json::json!([h.chunk_id, h.dist])) + .collect(), + ); + assert_eq!(got_json, turso["index_fill"]["result"]); + assert_eq!(be.transport().recorded(), turso["index_fill"]["calls"]); + + // index fixed-fetch: one depth-3 fetch, survivors [1]. + let fake = FakeTransport::new(); + let be = TursoBackend::with_transport(fake, DEFAULT_VEC_TABLE); + let got = be + .index_branch( + &default_filters(), + "[0.5, 0.25]", + 3, + VectorBackend::IndexFixed, + ) + .expect("index fixed"); + let got_json = Json::Array( + got.iter() + .map(|h| serde_json::json!([h.chunk_id, h.dist])) + .collect(), + ); + assert_eq!(got_json, turso["index_fixed"]["result"]); + assert_eq!(be.transport().recorded(), turso["index_fixed"]["calls"]); +} diff --git a/pkgs/atlas-search/fixtures/core-expectations.json b/pkgs/atlas-search/fixtures/core-expectations.json new file mode 100644 index 0000000000..809a27aaca --- /dev/null +++ b/pkgs/atlas-search/fixtures/core-expectations.json @@ -0,0 +1,1573 @@ +{ + "comment": "Recorded from the production Python atlas_search.py by gen_core_fixtures.py. atlas-core's parity tests must reproduce every envelope and SQL string here.", + "qvec_raw": [ + 0.9, + 0.3, + 0.1, + 0.0, + 0.2, + 0.0, + 0.1, + 0.0 + ], + "search_cases": [ + { + "name": "hybrid_default", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal" + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.181818, + "rank_sources": { + "fts": 1, + "vector": 1 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.001881 + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.166667, + "rank_sources": { + "fts": 2, + "vector": 2 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.056255 + }, + { + "chunk_id": 2, + "session_id": "sA", + "score": 0.076923, + "rank_sources": { + "vector": 3 + }, + "text": "restic snapshots go to the turso bucket nightly", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.227317 + }, + { + "chunk_id": 4, + "session_id": "sB", + "score": 0.071429, + "rank_sources": { + "vector": 4 + }, + "text": "refactoring the rust parser for speed", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.377201 + }, + { + "chunk_id": 3, + "session_id": "sA", + "score": 0.066667, + "rank_sources": { + "vector": 5 + }, + "text": "the backup script uses restic and rclone", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.673401 + }, + { + "chunk_id": 7, + "session_id": "sB", + "score": 0.0625, + "rank_sources": { + "vector": 6 + }, + "text": "cargo test failures in the queue worker", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.941876 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_secret_ceiling", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "secret-bearing" + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.174242, + "rank_sources": { + "fts": 1, + "vector": 2 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.001881 + }, + { + "chunk_id": 5, + "session_id": "sC", + "score": 0.167832, + "rank_sources": { + "fts": 3, + "vector": 1 + }, + "text": "secret backup database master plan", + "session": { + "title": "Secret plans", + "client": "claude-code", + "created_at": "2026-11-02T03:04:05Z", + "kind": "chat", + "topics": [ + "plans" + ], + "projects": [], + "sensitivity": "secret-bearing" + }, + "vector_distance": 0.0 + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.154762, + "rank_sources": { + "fts": 2, + "vector": 4 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.056255 + }, + { + "chunk_id": 6, + "session_id": "sD", + "score": 0.148352, + "rank_sources": { + "fts": 4, + "vector": 3 + }, + "text": "local notes about database backup", + "session": { + "title": "Local scratch", + "client": "opencode", + "created_at": "2026-09-15T22:40:10Z", + "kind": "chat", + "topics": [ + "nixos" + ], + "projects": [], + "sensitivity": "local-only" + }, + "vector_distance": 0.010672 + }, + { + "chunk_id": 2, + "session_id": "sA", + "score": 0.066667, + "rank_sources": { + "vector": 5 + }, + "text": "restic snapshots go to the turso bucket nightly", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.227317 + }, + { + "chunk_id": 4, + "session_id": "sB", + "score": 0.0625, + "rank_sources": { + "vector": 6 + }, + "text": "refactoring the rust parser for speed", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.377201 + }, + { + "chunk_id": 3, + "session_id": "sA", + "score": 0.058824, + "rank_sources": { + "vector": 7 + }, + "text": "the backup script uses restic and rclone", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.673401 + }, + { + "chunk_id": 7, + "session_id": "sB", + "score": 0.055556, + "rank_sources": { + "vector": 8 + }, + "text": "cargo test failures in the queue worker", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.941876 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_shareable_ceiling", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "shareable" + }, + "results": [ + { + "chunk_id": 4, + "session_id": "sB", + "score": 0.090909, + "rank_sources": { + "vector": 1 + }, + "text": "refactoring the rust parser for speed", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.377201 + }, + { + "chunk_id": 7, + "session_id": "sB", + "score": 0.083333, + "rank_sources": { + "vector": 2 + }, + "text": "cargo test failures in the queue worker", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.941876 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "fts_default", + "envelope": { + "query": "how do we back up the database", + "mode": "fts", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal" + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.090909, + "rank_sources": { + "fts": 1 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + } + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.083333, + "rank_sources": { + "fts": 2 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + } + } + ] + } + }, + { + "name": "vector_default", + "envelope": { + "query": "how do we back up the database", + "mode": "vector", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal" + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.090909, + "rank_sources": { + "vector": 1 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.001881 + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.083333, + "rank_sources": { + "vector": 2 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.056255 + }, + { + "chunk_id": 2, + "session_id": "sA", + "score": 0.076923, + "rank_sources": { + "vector": 3 + }, + "text": "restic snapshots go to the turso bucket nightly", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.227317 + }, + { + "chunk_id": 4, + "session_id": "sB", + "score": 0.071429, + "rank_sources": { + "vector": 4 + }, + "text": "refactoring the rust parser for speed", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.377201 + }, + { + "chunk_id": 3, + "session_id": "sA", + "score": 0.066667, + "rank_sources": { + "vector": 5 + }, + "text": "the backup script uses restic and rclone", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.673401 + }, + { + "chunk_id": 7, + "session_id": "sB", + "score": 0.0625, + "rank_sources": { + "vector": 6 + }, + "text": "cargo test failures in the queue worker", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.941876 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_kind_code", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal", + "kind": [ + "code" + ] + }, + "results": [ + { + "chunk_id": 4, + "session_id": "sB", + "score": 0.090909, + "rank_sources": { + "vector": 1 + }, + "text": "refactoring the rust parser for speed", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.377201 + }, + { + "chunk_id": 7, + "session_id": "sB", + "score": 0.083333, + "rank_sources": { + "vector": 2 + }, + "text": "cargo test failures in the queue worker", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.941876 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_topic_nixos", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal", + "topic": [ + "nixos" + ] + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.181818, + "rank_sources": { + "fts": 1, + "vector": 1 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.001881 + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.166667, + "rank_sources": { + "fts": 2, + "vector": 2 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.056255 + }, + { + "chunk_id": 2, + "session_id": "sA", + "score": 0.076923, + "rank_sources": { + "vector": 3 + }, + "text": "restic snapshots go to the turso bucket nightly", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.227317 + }, + { + "chunk_id": 3, + "session_id": "sA", + "score": 0.071429, + "rank_sources": { + "vector": 4 + }, + "text": "the backup script uses restic and rclone", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.673401 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_client_codex_dates", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal", + "client": [ + "codex" + ], + "since": "2026-10-01", + "until": "2026-10-31" + }, + "results": [ + { + "chunk_id": 4, + "session_id": "sB", + "score": 0.090909, + "rank_sources": { + "vector": 1 + }, + "text": "refactoring the rust parser for speed", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.377201 + }, + { + "chunk_id": 7, + "session_id": "sB", + "score": 0.083333, + "rank_sources": { + "vector": 2 + }, + "text": "cargo test failures in the queue worker", + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "vector_distance": 0.941876 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_until_before_sB", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal", + "client": [ + "codex" + ], + "until": "2026-10-19" + }, + "results": [], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_grouped", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal" + }, + "results": [ + { + "session_id": "sA", + "score": 0.181818, + "hit_count": 4, + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "chunks": [ + { + "chunk_id": 1, + "score": 0.181818, + "rank_sources": { + "fts": 1, + "vector": 1 + }, + "text": "how do we back up the database with restic", + "vector_distance": 0.001881 + }, + { + "chunk_id": 8, + "score": 0.166667, + "rank_sources": { + "fts": 2, + "vector": 2 + }, + "text": "database backup verification steps", + "vector_distance": 0.056255 + }, + { + "chunk_id": 2, + "score": 0.076923, + "rank_sources": { + "vector": 3 + }, + "text": "restic snapshots go to the turso bucket nightly", + "vector_distance": 0.227317 + }, + { + "chunk_id": 3, + "score": 0.066667, + "rank_sources": { + "vector": 5 + }, + "text": "the backup script uses restic and rclone", + "vector_distance": 0.673401 + } + ] + }, + { + "session_id": "sB", + "score": 0.071429, + "hit_count": 2, + "session": { + "title": "Rust refactor session", + "client": "codex", + "created_at": "2026-10-20T09:12:00Z", + "kind": "code", + "topics": [ + "rust" + ], + "projects": [ + "atlas" + ], + "sensitivity": "shareable" + }, + "chunks": [ + { + "chunk_id": 4, + "score": 0.071429, + "rank_sources": { + "vector": 4 + }, + "text": "refactoring the rust parser for speed", + "vector_distance": 0.377201 + }, + { + "chunk_id": 7, + "score": 0.0625, + "rank_sources": { + "vector": 6 + }, + "text": "cargo test failures in the queue worker", + "vector_distance": 0.941876 + } + ] + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_expand_message", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal" + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.181818, + "rank_sources": { + "fts": 1, + "vector": 1 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.001881, + "context": { + "before": [], + "after": [ + { + "chunk_id": 2, + "text": "restic snapshots go to the turso bucket nightly" + } + ] + }, + "message": { + "id": "mA1", + "role": "user", + "text": "how do we back up the database with restic and check the secret backup database master plan", + "truncated": false + } + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.166667, + "rank_sources": { + "fts": 2, + "vector": 2 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.056255, + "context": { + "before": [ + { + "chunk_id": 3, + "text": "the backup script uses restic and rclone" + } + ], + "after": [] + }, + "message": { + "id": "mA2", + "role": "assistant", + "text": "the backup script uses restic and rclone; database backup verification steps follow", + "truncated": false + } + }, + { + "chunk_id": 2, + "session_id": "sA", + "score": 0.076923, + "rank_sources": { + "vector": 3 + }, + "text": "restic snapshots go to the turso bucket nightly", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.227317, + "context": { + "before": [ + { + "chunk_id": 1, + "text": "how do we back up the database with restic" + } + ], + "after": [] + }, + "message": { + "id": "mA1", + "role": "user", + "text": "how do we back up the database with restic and check the secret backup database master plan", + "truncated": false + } + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 100, + "vector_backend": "scan" + } + } + }, + { + "name": "hybrid_pool2_k2", + "envelope": { + "query": "how do we back up the database", + "mode": "hybrid", + "backend": "local", + "filters_applied": { + "max_sensitivity": "personal" + }, + "results": [ + { + "chunk_id": 1, + "session_id": "sA", + "score": 0.181818, + "rank_sources": { + "fts": 1, + "vector": 1 + }, + "text": "how do we back up the database with restic", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.001881 + }, + { + "chunk_id": 8, + "session_id": "sA", + "score": 0.166667, + "rank_sources": { + "fts": 2, + "vector": 2 + }, + "text": "database backup verification steps", + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "vector_distance": 0.056255 + } + ], + "vector": { + "model": "Snowflake/snowflake-arctic-embed-m-v2.0", + "table": "vec_snowflake_m_v2_768_f32", + "embedder": "auto", + "trunc": null, + "pool": 2, + "vector_backend": "scan" + } + } + } + ], + "get_chunk_cases": [ + { + "name": "get_chunk_secret", + "envelope": { + "chunk_id": 5, + "text": "secret backup database master plan", + "chunk_idx": 0, + "message": { + "id": "mC1", + "role": "user", + "session_id": "sC" + }, + "session": { + "title": "Secret plans", + "client": "claude-code", + "created_at": "2026-11-02T03:04:05Z", + "kind": "chat", + "topics": [ + "plans" + ], + "projects": [], + "sensitivity": "secret-bearing" + }, + "session_id": "sC" + } + }, + { + "name": "get_chunk_neighbors", + "envelope": { + "chunk_id": 2, + "text": "restic snapshots go to the turso bucket nightly", + "chunk_idx": 1, + "message": { + "id": "mA1", + "role": "user", + "session_id": "sA" + }, + "session": { + "title": "NixOS backup chat", + "client": "claude-code", + "created_at": "2026-10-05T14:23:00Z", + "kind": "chat", + "topics": [ + "nixos", + "backup" + ], + "projects": [ + "atlas" + ], + "sensitivity": "personal" + }, + "session_id": "sA", + "context": { + "before": [ + { + "chunk_id": 1, + "text": "how do we back up the database with restic" + } + ], + "after": [] + } + } + } + ], + "turso": { + "branch_queries": [ + { + "name": "defaults", + "stmts": [ + { + "sql": "SELECT c.id AS cid FROM chunks c JOIN chunks_fts f ON f.rowid = c.id JOIN messages m ON m.id = c.message_id JOIN sessions s ON s.id = m.session_id LEFT JOIN session_labels l ON l.session_id = s.id WHERE chunks_fts MATCH ? AND c.sensitivity IN (?,?) ORDER BY bm25(chunks_fts) LIMIT ?", + "params": [ + "\"back\" OR \"database\"", + "shareable", + "personal", + 100 + ] + }, + { + "sql": "SELECT v.chunk_id AS cid, vector_distance_cos(v.vec, vector32(?)) AS dist FROM vec_snowflake_m_v2_768_f32 v JOIN chunks c ON c.id = v.chunk_id WHERE c.sensitivity IN (?,?) ORDER BY dist ASC LIMIT ?", + "params": [ + "[0.5, 0.25]", + "shareable", + "personal", + 100 + ] + } + ] + }, + { + "name": "all_filters_secret", + "stmts": [ + { + "sql": "SELECT c.id AS cid FROM chunks c JOIN chunks_fts f ON f.rowid = c.id JOIN messages m ON m.id = c.message_id JOIN sessions s ON s.id = m.session_id LEFT JOIN session_labels l ON l.session_id = s.id WHERE chunks_fts MATCH ? AND c.sensitivity IN (?,?,?,?) AND l.kind IN (?) AND s.client IN (?) AND l.topics LIKE ? AND s.created_at >= ? AND s.created_at < ? ORDER BY bm25(chunks_fts) LIMIT ?", + "params": [ + "\"back\" OR \"database\"", + "shareable", + "personal", + "local-only", + "secret-bearing", + "code", + "codex", + "%\"rust\"%", + "2026-10-01", + "2026-11-01", + 100 + ] + }, + { + "sql": "SELECT v.chunk_id AS cid, vector_distance_cos(v.vec, vector32(?)) AS dist FROM vec_snowflake_m_v2_768_f32 v JOIN chunks c ON c.id = v.chunk_id WHERE c.sensitivity IN (?,?,?,?) AND v.chunk_id IN (SELECT c2.id FROM chunks c2 JOIN messages m2 ON m2.id = c2.message_id JOIN sessions s2 ON s2.id = m2.session_id LEFT JOIN session_labels l2 ON l2.session_id = s2.id WHERE l2.kind IN (?) AND s2.client IN (?) AND l2.topics LIKE ? AND s2.created_at >= ? AND s2.created_at < ?) ORDER BY dist ASC LIMIT ?", + "params": [ + "[0.5, 0.25]", + "shareable", + "personal", + "local-only", + "secret-bearing", + "code", + "codex", + "%\"rust\"%", + "2026-10-01", + "2026-11-01", + 100 + ] + } + ] + }, + { + "name": "fts_only", + "stmts": [ + { + "sql": "SELECT c.id AS cid FROM chunks c JOIN chunks_fts f ON f.rowid = c.id JOIN messages m ON m.id = c.message_id JOIN sessions s ON s.id = m.session_id LEFT JOIN session_labels l ON l.session_id = s.id WHERE chunks_fts MATCH ? AND c.sensitivity IN (?,?) ORDER BY bm25(chunks_fts) LIMIT ?", + "params": [ + "\"back\" OR \"database\"", + "shareable", + "personal", + 100 + ] + } + ] + }, + { + "name": "vector_only", + "stmts": [ + { + "sql": "SELECT v.chunk_id AS cid, vector_distance_cos(v.vec, vector32(?)) AS dist FROM vec_snowflake_m_v2_768_f32 v JOIN chunks c ON c.id = v.chunk_id WHERE c.sensitivity IN (?,?) ORDER BY dist ASC LIMIT ?", + "params": [ + "[0.5, 0.25]", + "shareable", + "personal", + 100 + ] + } + ] + } + ], + "allowed_ids_plain": { + "calls": [ + { + "sql": "SELECT c.id AS cid FROM chunks c WHERE c.sensitivity IN (?,?)", + "params": [ + "shareable", + "personal" + ] + } + ], + "result": [ + 1, + 2, + 3, + 4, + 7, + 8 + ] + }, + "allowed_ids_kind": { + "calls": [ + { + "sql": "SELECT c.id AS cid FROM chunks c WHERE c.sensitivity IN (?,?)", + "params": [ + "shareable", + "personal" + ] + }, + { + "sql": "SELECT c2.id AS cid FROM chunks c2 JOIN messages m2 ON m2.id = c2.message_id JOIN sessions s2 ON s2.id = m2.session_id LEFT JOIN session_labels l2 ON l2.session_id = s2.id WHERE l2.kind IN (?)", + "params": [ + "code" + ] + } + ], + "result": [ + 4, + 7 + ] + }, + "index_fill": { + "calls": [ + { + "sql": "SELECT c.id AS cid FROM chunks c WHERE c.sensitivity IN (?,?)", + "params": [ + "shareable", + "personal" + ] + }, + { + "sql": "SELECT id FROM vector_top_k(?, vector32(?), ?)", + "params": [ + "vec_snowflake_m_v2_768_f32_idx", + "[0.5, 0.25]", + 3 + ] + }, + { + "sql": "SELECT id FROM vector_top_k(?, vector32(?), ?)", + "params": [ + "vec_snowflake_m_v2_768_f32_idx", + "[0.5, 0.25]", + 6 + ] + }, + { + "sql": "SELECT chunk_id AS cid, vector_distance_cos(vec, vector32(?)) AS dist FROM vec_snowflake_m_v2_768_f32 WHERE chunk_id IN (?,?,?)", + "params": [ + "[0.5, 0.25]", + 1, + 2, + 8 + ] + } + ], + "result": [ + [ + 1, + 0.01 + ], + [ + 2, + 0.3 + ], + [ + 8, + 0.07 + ] + ] + }, + "index_fixed": { + "calls": [ + { + "sql": "SELECT c.id AS cid FROM chunks c WHERE c.sensitivity IN (?,?)", + "params": [ + "shareable", + "personal" + ] + }, + { + "sql": "SELECT id FROM vector_top_k(?, vector32(?), ?)", + "params": [ + "vec_snowflake_m_v2_768_f32_idx", + "[0.5, 0.25]", + 3 + ] + }, + { + "sql": "SELECT chunk_id AS cid, vector_distance_cos(vec, vector32(?)) AS dist FROM vec_snowflake_m_v2_768_f32 WHERE chunk_id IN (?)", + "params": [ + "[0.5, 0.25]", + 1 + ] + } + ], + "result": [ + [ + 1, + 0.01 + ] + ] + } + } +} \ No newline at end of file diff --git a/pkgs/atlas-search/fixtures/fixture_corpus.sql b/pkgs/atlas-search/fixtures/fixture_corpus.sql new file mode 100644 index 0000000000..d5c4ab9527 --- /dev/null +++ b/pkgs/atlas-search/fixtures/fixture_corpus.sql @@ -0,0 +1,90 @@ +-- Fixture corpus for atlas-core parity tests (developing-today/code#5352). +-- +-- A miniature publish-shaped Atlas DB: sessions -> messages -> chunks, +-- session_labels, a chunks_fts FTS5 table, and sensitivity denormalized +-- onto chunks (the publish schema). All content is synthetic. +-- +-- Sensitivity layout is the point of the fixture: +-- chunk 5 (secret-bearing) carries the query's exact vector (sim 1.0) +-- and FTS terms -- it must be ABSENT at the default ceiling, not +-- down-ranked, and PRESENT (top) when the ceiling is spelled out. +-- chunk 6 (local-only) is nearly as close and likewise excluded by +-- the default `personal` ceiling. +-- Vectors live in fixture_spec.json (this file cannot hold blobs); +-- both the Python fixture generator and the Rust tests insert them +-- into vec_snowflake_m_v2_768_f32 from that one source. + +CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + title TEXT, + client TEXT, + created_at TEXT +); +CREATE TABLE messages ( + id TEXT PRIMARY KEY, + session_id TEXT, + role TEXT, + text TEXT +); +CREATE TABLE chunks ( + id INTEGER PRIMARY KEY, + message_id TEXT NOT NULL, + chunk_idx INTEGER, + text TEXT NOT NULL, + content_hash TEXT UNIQUE NOT NULL, + sensitivity TEXT +); +CREATE TABLE session_labels ( + session_id TEXT PRIMARY KEY, + client TEXT, + kind TEXT, + topics TEXT, + projects TEXT, + sensitivity TEXT, + confidence TEXT, + scheme TEXT +); +CREATE TABLE vec_snowflake_m_v2_768_f32 ( + chunk_id INTEGER PRIMARY KEY, + vec BLOB NOT NULL +); +CREATE VIRTUAL TABLE chunks_fts USING fts5(text); + +INSERT INTO sessions (id, title, client, created_at) VALUES + ('sA', 'NixOS backup chat', 'claude-code', '2026-10-05T14:23:00Z'), + ('sB', 'Rust refactor session', 'codex', '2026-10-20T09:12:00Z'), + ('sC', 'Secret plans', 'claude-code', '2026-11-02T03:04:05Z'), + ('sD', 'Local scratch', 'opencode', '2026-09-15T22:40:10Z'); + +INSERT INTO session_labels (session_id, client, kind, topics, projects, sensitivity, confidence, scheme) VALUES + ('sA', 'claude-code', 'chat', '["nixos", "backup"]', '["atlas"]', 'personal', 'high', '1.0'), + ('sB', 'codex', 'code', '["rust"]', '["atlas"]', 'shareable', 'high', '1.0'), + ('sC', 'claude-code', 'chat', '["plans"]', '[]', 'secret-bearing', 'high', '1.0'), + ('sD', 'opencode', 'chat', '["nixos"]', '[]', 'local-only', 'high', '1.0'); + +INSERT INTO messages (id, session_id, role, text) VALUES + ('mA1', 'sA', 'user', 'how do we back up the database with restic and check the secret backup database master plan'), + ('mA2', 'sA', 'assistant', 'the backup script uses restic and rclone; database backup verification steps follow'), + ('mB1', 'sB', 'user', 'refactoring the rust parser for speed; cargo test failures in the queue worker'), + ('mC1', 'sC', 'user', 'secret backup database master plan'), + ('mD1', 'sD', 'assistant', 'local notes about database backup'); + +INSERT INTO chunks (id, message_id, chunk_idx, text, content_hash, sensitivity) VALUES + (1, 'mA1', 0, 'how do we back up the database with restic', 'fxh1', 'personal'), + (2, 'mA1', 1, 'restic snapshots go to the turso bucket nightly', 'fxh2', 'personal'), + (3, 'mA2', 0, 'the backup script uses restic and rclone', 'fxh3', 'personal'), + (4, 'mB1', 0, 'refactoring the rust parser for speed', 'fxh4', 'shareable'), + (5, 'mC1', 0, 'secret backup database master plan', 'fxh5', 'secret-bearing'), + (6, 'mD1', 0, 'local notes about database backup', 'fxh6', 'local-only'), + (7, 'mB1', 1, 'cargo test failures in the queue worker', 'fxh7', 'shareable'), + (8, 'mA2', 1, 'database backup verification steps', 'fxh8', 'personal'); + +INSERT INTO chunks_fts (rowid, text) VALUES + (1, 'how do we back up the database with restic'), + (2, 'restic snapshots go to the turso bucket nightly'), + (3, 'the backup script uses restic and rclone'), + (4, 'refactoring the rust parser for speed'), + (5, 'secret backup database master plan'), + (6, 'local notes about database backup'), + (7, 'cargo test failures in the queue worker'), + (8, 'database backup verification steps'); diff --git a/pkgs/atlas-search/fixtures/fixture_spec.json b/pkgs/atlas-search/fixtures/fixture_spec.json new file mode 100644 index 0000000000..9f555c06b1 --- /dev/null +++ b/pkgs/atlas-search/fixtures/fixture_spec.json @@ -0,0 +1 @@ +{"comment":"Toy 8-dimension vectors for the atlas-core fixture corpus (fixture_corpus.sql). The Python fixture generator monkeypatches embed_query to return qvec_raw normalized exactly as embed_query does; the Rust tests inject the same qvec_raw through a fixed embedder. Chunk 5's vector equals qvec_raw (cosine 1.0 after normalization): it is the ceiling canary. Document vectors are stored unnormalized; both implementations normalize rows at load, as production does.","qvec_raw":[0.9,0.3,0.1,0.0,0.2,0.0,0.1,0.0],"vectors":{"1":[0.85,0.3,0.1,0.05,0.2,0.0,0.1,0.02],"2":[0.5,0.6,0.3,0.1,0.0,0.2,0.0,0.1],"3":[0.2,0.1,0.9,0.3,0.1,0.0,0.0,0.2],"4":[0.6,0.2,0.2,0.8,0.1,0.1,0.0,0.0],"5":[0.9,0.3,0.1,0.0,0.2,0.0,0.1,0.0],"6":[0.8,0.35,0.15,0.0,0.25,0.05,0.05,0.0],"7":[0.0,0.1,0.0,0.2,0.0,0.9,0.3,0.4],"8":[0.75,0.25,0.3,0.1,0.3,0.0,0.2,0.1]}} \ No newline at end of file diff --git a/pkgs/atlas-search/fixtures/gen_core_fixtures.py b/pkgs/atlas-search/fixtures/gen_core_fixtures.py new file mode 100644 index 0000000000..700b421e2b --- /dev/null +++ b/pkgs/atlas-search/fixtures/gen_core_fixtures.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Generate the atlas-core parity fixtures (developing-today/code#5352). + +Builds the fixture corpus (fixture_corpus.sql + fixture_spec.json) into +a throwaway SQLite DB, runs the PRODUCTION Python atlas_search.py +against it (LocalBackend, embed_query monkeypatched to the fixture +query vector), and records the exact output envelopes. It also records +the Turso branch SQL (branch_queries) for representative filter sets +and the full call sequences of turso_allowed_ids / turso_index_branch +against a recording fake backend -- the server-side contract atlas-core +must reproduce byte-for-byte. + +Run on the laptop (amd-6), never the sandbox: + + LD_LIBRARY_PATH=: \ + ~/atlas/v3-venv/bin/python gen_core_fixtures.py + +Output: fixtures/core-expectations.json (committed; the .db is not). +""" +import argparse +import importlib.util +import json +import os +import sqlite3 +import struct +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +PY_CLI = os.path.expanduser("~/atlas/turso-atlas/scripts/atlas_search.py") + +spec = importlib.util.spec_from_file_location("atlas_search", PY_CLI) +A = importlib.util.module_from_spec(spec) +spec.loader.exec_module(A) + +import numpy as np # noqa: E402 + +with open(os.path.join(HERE, "fixture_spec.json")) as f: + FSPEC = json.load(f) +QVEC_RAW = FSPEC["qvec_raw"] + + +def build_db(path): + with open(os.path.join(HERE, "fixture_corpus.sql")) as f: + sql = f.read() + con = sqlite3.connect(path) + con.executescript(sql) + for cid, vec in FSPEC["vectors"].items(): + con.execute( + "INSERT INTO vec_snowflake_m_v2_768_f32 (chunk_id, vec) VALUES (?, ?)", + (int(cid), struct.pack(f"<{len(vec)}f", *vec)), + ) + con.commit() + con.close() + + +def fixture_embed_query(text, model=None, embedder=None, trunc=0): + """embed_query stand-in: the fixture qvec, normalized exactly as + the real embed_query normalizes (float32, divide by float norm).""" + v = np.array(QVEC_RAW, dtype=np.float32) + if trunc: + v = v[:trunc] + n = float(np.linalg.norm(v)) + return v / n + + +A.embed_query = fixture_embed_query + + +def mkargs(**over): + base = dict( + query="how do we back up the database", + mode="hybrid", k=10, pool=100, + kind=None, topic=None, project=None, client=None, + since=None, until=None, max_sensitivity="personal", + group_by_session=False, expand=0, with_message=False, + model=A.MODEL, embedder="auto", trunc=0, vector_backend="scan", + ) + base.update(over) + return argparse.Namespace(**base) + + +def search_cases(be): + cases = [] + def add(name, **over): + out = A.run_search(be, mkargs(**over)) + cases.append({"name": name, "envelope": out}) + add("hybrid_default") + add("hybrid_secret_ceiling", max_sensitivity="secret-bearing") + add("hybrid_shareable_ceiling", max_sensitivity="shareable") + add("fts_default", mode="fts") + add("vector_default", mode="vector") + add("hybrid_kind_code", kind="code") + add("hybrid_topic_nixos", topic="nixos") + add("hybrid_client_codex_dates", client="codex", + since="2026-10-01", until="2026-10-31") + add("hybrid_until_before_sB", client="codex", until="2026-10-19") + add("hybrid_grouped", group_by_session=True, k=2) + add("hybrid_expand_message", expand=1, with_message=True, k=3) + add("hybrid_pool2_k2", pool=2, k=2) + return cases + + +def get_chunk_cases(be): + cases = [] + for name, cid, neighbors in (("get_chunk_secret", 5, 0), + ("get_chunk_neighbors", 2, 1)): + ns = argparse.Namespace(chunk_id=cid, neighbors=neighbors) + cases.append({"name": name, "envelope": A.run_get_chunk(be, ns)}) + return cases + + +def turso_fixtures(): + stub = object.__new__(A.TursoBackend) + stub.vec_table = A.VEC_TABLE + out = {} + + def filters_for(**over): + return A.Filters(mkargs(**over)) + + bq = [] + for name, fover, me, qj, pool in ( + ("defaults", {}, '"back" OR "database"', "[0.5, 0.25]", 100), + ("all_filters_secret", dict(kind="code", topic="rust", client="codex", + since="2026-10-01", until="2026-10-31", + max_sensitivity="secret-bearing"), + '"back" OR "database"', "[0.5, 0.25]", 100), + ("fts_only", {}, '"back" OR "database"', None, 100), + ("vector_only", {}, None, "[0.5, 0.25]", 100), + ): + stmts = A.branch_queries(stub, filters_for(**fover), me, qj, pool) + bq.append({"name": name, + "stmts": [{"sql": s, "params": p} for s, p in stmts]}) + out["branch_queries"] = bq + + class FakeBe: + vec_table = A.VEC_TABLE + def __init__(self): + self.calls = [] + def execute(self, sql, args=()): + self.calls.append({"sql": sql, "params": list(args)}) + if "vector_top_k" in sql: + script = {3: [5, 1, 6], 6: [5, 1, 6, 2, 8, 3]} + return [{"id": i} for i in script[args[2]]] + if "vector_distance_cos" in sql and "chunk_id IN" in sql: + dists = {1: 0.01, 2: 0.3, 8: 0.07} + return [{"cid": c, "dist": dists[c]} for c in args[1:]] + if "c.sensitivity" in sql: + return [{"cid": i} for i in (1, 2, 3, 4, 7, 8)] + if "c2.id" in sql: + return [{"cid": i} for i in (4, 7)] + raise AssertionError(f"unexpected SQL: {sql}") + + fb = FakeBe() + allowed = A.turso_allowed_ids(fb, filters_for()) + out["allowed_ids_plain"] = {"calls": fb.calls, "result": sorted(allowed)} + + fb = FakeBe() + allowed = A.turso_allowed_ids(fb, filters_for(kind="code")) + out["allowed_ids_kind"] = {"calls": fb.calls, "result": sorted(allowed)} + + fb = FakeBe() + ranked = A.turso_index_branch(fb, filters_for(), "[0.5, 0.25]", 3, "index-fill") + out["index_fill"] = {"calls": fb.calls, + "result": [[c, d] for c, d in ranked]} + + fb = FakeBe() + # index-fixed at pool 3 would call depth 3; reuse the scripted depth-3 + # response: survivors = [1] after filtering. + ranked = A.turso_index_branch(fb, filters_for(), "[0.5, 0.25]", 3, "index-fixed") + out["index_fixed"] = {"calls": fb.calls, + "result": [[c, d] for c, d in ranked]} + return out + + +def main(): + tmp = tempfile.mkdtemp(prefix="atlas-core-fixture-") + db = os.path.join(tmp, "fixture.db") + build_db(db) + be = A.LocalBackend(db) + doc = { + "comment": ("Recorded from the production Python atlas_search.py " + "by gen_core_fixtures.py. atlas-core's parity tests " + "must reproduce every envelope and SQL string here."), + "qvec_raw": QVEC_RAW, + "search_cases": search_cases(be), + "get_chunk_cases": get_chunk_cases(be), + "turso": turso_fixtures(), + } + out_path = os.path.join(HERE, "core-expectations.json") + with open(out_path, "w") as f: + json.dump(doc, f, indent=1, ensure_ascii=False) + print(f"wrote {out_path}") + + +if __name__ == "__main__": + main()