diff --git a/AGENTS.develop.md b/AGENTS.develop.md index 9585af42..0f49475b 100644 --- a/AGENTS.develop.md +++ b/AGENTS.develop.md @@ -242,6 +242,8 @@ Never `unwrap_or_default()` a store error on a search path — "no results" and ## Changelog highlights (recent) +- **Pending** — upstream #384 stage 2: separate loopback-only `codesearch-server` HTTP binary owns PostgreSQL pgvector/pg_search persistence, server-side embeddings, database cache and transactional revision-CAS file publication. Local CLI storage and behavior remain unchanged; authentication/federation/publication scheduling are deferred. + - **Pending** — dependabot automation repaired: `gh pr merge --auto` failed for every dependabot PR under the develop ruleset (`enablePullRequestAutoMerge` denied for GITHUB_TOKEN, and the ruleset has no required status checks so `--auto` would have merged red CI — observed live on #407); the workflow now approves minor/patch bumps and merges only after `gh pr checks --watch` reports every check green, major bumps still wait for a human; changelog-check reads the `no-changelog` label live via the API instead of the stale `labeled`-webhook payload that kept dependency PRs visibly red. - **Pending** — recreated-path requeues gated + parent .gitignore rules loaded: `requeue_recreated_removals` re-ran no watchable gate, so delete+recreate churn over build output re-entered the text batch ungated (811 UTF-8 read warns/day on one worktree's bin/Debug, 141 in one flush; 2100 from a registered subdir's `.tmp/` scratch whose repo-root rules the watcher never saw); a recreated path is a create — same `is_watchable` gate, the removal stands when rejected — and `build_gitignore` now collects parent `.gitignore` files up to the git root, mirroring the walker's `parents(true)`. diff --git a/CHANGELOG.md b/CHANGELOG.md index b8babc97..6e907114 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,17 @@ more PRs land; when the release is actually tagged, the same section is finalized in place with a date — no renaming/migration step needed. --> +## [1.8.25] + +### Fixed + +- Server publication rejects malformed notebooks without replacing prior index state, orders unique shared cache insertions to avoid reversed-key deadlocks, and provides bounded repository keyset pagination. Split chunks now retain inclusive physical source-line ranges, including fragments of long lines; notebook coordinates remain explicitly synthetic. +- Server documents now preserve extracted documentation for BM25 and embeddings, with cache keys derived from final prepared input (including long-function split headers). The v2 document fingerprint refuses earlier databases until intentional reindex into a fresh database; no automatic reset/migration. Loopback HTTP now rejects hostile/malformed Host and browser Origin values before all routes, without adding authentication. + +### Added + +- Separate `codesearch-server` foundation for upstream #384 stage 2: loopback HTTP publication/search with PostgreSQL pgvector and pg_search 0.27.1, server-side embeddings and database embedding cache, persistent repository/file sync state, transactional replacement/deletion and stale-writer revision checks. The local CLI remains unchanged. This stage has no authentication and must not be exposed to untrusted callers; see `server/README.md`. + ## [1.8.12] ### Added diff --git a/Cargo.lock b/Cargo.lock index cdad9528..b11866bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -115,7 +115,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -126,7 +126,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -218,6 +218,15 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + [[package]] name = "atomic" version = "0.6.1" @@ -833,6 +842,23 @@ dependencies = [ [[package]] name = "codesearch-server" version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "clap", + "codesearch-core", + "pgvector", + "reqwest 0.13.5", + "serde", + "serde_json", + "sha2 0.11.1", + "sqlx", + "thiserror 2.0.21", + "tokio", + "tracing", + "tracing-subscriber", + "url", +] [[package]] name = "color_quant" @@ -852,7 +878,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -986,6 +1012,21 @@ dependencies = [ "libc", ] +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + [[package]] name = "crc32fast" version = "1.5.3" @@ -1352,6 +1393,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -1392,7 +1434,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1427,6 +1469,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + [[package]] name = "downcast-rs" version = "2.0.2" @@ -1459,6 +1507,9 @@ name = "either" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] [[package]] name = "encode_unicode" @@ -1544,7 +1595,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1553,6 +1604,17 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + [[package]] name = "euclid" version = "0.22.14" @@ -1562,6 +1624,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + [[package]] name = "exr" version = "1.74.2" @@ -1688,6 +1760,12 @@ 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" @@ -1792,6 +1870,17 @@ dependencies = [ "futures-util", ] +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + [[package]] name = "futures-io" version = "0.3.34" @@ -1946,6 +2035,17 @@ version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -1954,7 +2054,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", "serde", "serde_core", ] @@ -1967,7 +2067,16 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.2.0", +] + +[[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]] @@ -2047,12 +2156,39 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "hmac-sha256" version = "1.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ad320b3b96fb2a455a0726d16efe0a5afdbd34b71dea5bc53b05ea057714d4e" +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "htmlescape" version = "0.3.1" @@ -2668,7 +2804,10 @@ version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ + "bitflags 2.13.2", "libc", + "plain", + "redox_syscall 0.9.5", ] [[package]] @@ -2833,6 +2972,16 @@ dependencies = [ "rayon", ] +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + [[package]] name = "measure_time" version = "0.9.0" @@ -3136,7 +3285,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3481,6 +3630,12 @@ dependencies = [ "libm", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -3499,7 +3654,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", "smallvec", "windows-link", ] @@ -3581,6 +3736,15 @@ dependencies = [ "pest", ] +[[package]] +name = "pgvector" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3673cba5b9a124916096a423b806a9f29620972c6c97b08db5f2053e9428b481" +dependencies = [ + "sqlx", +] + [[package]] name = "phf" version = "0.11.3" @@ -3645,6 +3809,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + [[package]] name = "plotters" version = "0.3.7" @@ -3890,7 +4060,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3920,6 +4090,8 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ + "libc", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] @@ -3929,7 +4101,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -3944,6 +4116,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" @@ -3959,6 +4141,9 @@ name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] [[package]] name = "rand_core" @@ -4113,7 +4298,7 @@ dependencies = [ "paste", "profiling", "rand 0.9.5", - "rand_chacha", + "rand_chacha 0.9.0", "simd_helpers", "thiserror 2.0.21", "v_frame", @@ -4196,6 +4381,15 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "redox_users" version = "0.5.3" @@ -4439,7 +4633,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4498,7 +4692,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4688,7 +4882,7 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ - "foldhash", + "foldhash 0.2.0", "indexmap", "itoa", "memchr", @@ -4870,6 +5064,9 @@ name = "smallvec" version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +dependencies = [ + "serde", +] [[package]] name = "socket2" @@ -4878,7 +5075,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4893,6 +5090,126 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-postgres", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64 0.22.1", + "bytes", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "thiserror 2.0.21", + "tokio", + "tokio-stream", + "tracing", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2 0.10.9", + "sqlx-core", + "sqlx-postgres", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64 0.22.1", + "bitflags 2.13.2", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand 0.8.8", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror 2.0.21", + "tracing", + "whoami", +] + [[package]] name = "sse-stream" version = "0.2.6" @@ -4922,7 +5239,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4937,6 +5254,17 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.11.1" @@ -5238,10 +5566,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5254,7 +5582,7 @@ dependencies = [ "parking_lot", "rustix", "signal-hook", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5919,12 +6247,27 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-normalization-alignments" version = "0.1.12" @@ -5934,6 +6277,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + [[package]] name = "unicode-segmentation" version = "1.13.3" @@ -6007,7 +6356,7 @@ dependencies = [ "ureq-proto", "utf8-zero", "webpki-root-certs", - "webpki-roots", + "webpki-roots 1.0.10", ] [[package]] @@ -6149,6 +6498,12 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -6260,6 +6615,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.10", +] + [[package]] name = "webpki-roots" version = "1.0.10" @@ -6347,6 +6711,16 @@ dependencies = [ "wezterm-dynamic", ] +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + [[package]] name = "winapi" version = "0.3.9" @@ -6369,7 +6743,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -6490,6 +6864,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -6526,6 +6909,21 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -6568,6 +6966,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -6580,6 +6984,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -6592,6 +7002,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -6616,6 +7032,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -6628,6 +7050,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -6640,6 +7068,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -6652,6 +7086,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" diff --git a/core/src/chunker/jupyter.rs b/core/src/chunker/jupyter.rs index 5310b374..4043920e 100644 --- a/core/src/chunker/jupyter.rs +++ b/core/src/chunker/jupyter.rs @@ -205,8 +205,8 @@ fn build_chunk(group: &CellGroup, file_name: &str, file_breadcrumb: &str) -> Chu // distinguish code from markdown content. let prefixed = format!("# [{}]\n{}", group.cell_type, group.content); - // Group lines are 0-based offsets into the notebook; chunks surface - // 1-based editor lines. + // Group offsets count extracted cell-content lines; expose 1-based synthetic + // bounds, not editor coordinates inside the raw notebook JSON. let mut chunk = Chunk::new( prefixed, group.start_line + 1, diff --git a/core/src/chunker/semantic.rs b/core/src/chunker/semantic.rs index b7568ee7..71727f88 100644 --- a/core/src/chunker/semantic.rs +++ b/core/src/chunker/semantic.rs @@ -9,6 +9,10 @@ use anyhow::Result; use std::path::Path; use tree_sitter::Node; +#[cfg(test)] +#[path = "semantic_range_tests.rs"] +mod range_tests; + /// Smart semantic chunker using tree-sitter and language-specific extractors pub struct SemanticChunker { parser: CodeParser, @@ -497,21 +501,21 @@ impl SemanticChunker { // 1. Expand into "units": one per line, but any line over the char budget is // fragmented on char boundaries so no single unit exceeds max_chunk_chars. - let mut units: Vec = Vec::new(); - for line in chunk.content.lines() { + let mut units: Vec<(String, usize)> = Vec::new(); + for (line_index, line) in chunk.content.lines().enumerate() { if line.len() <= self.max_chunk_chars { - units.push(line.to_string()); + units.push((line.to_string(), line_index)); continue; } let mut frag = String::new(); for ch in line.chars() { if !frag.is_empty() && frag.len() + ch.len_utf8() > self.max_chunk_chars { - units.push(std::mem::take(&mut frag)); + units.push((std::mem::take(&mut frag), line_index)); } frag.push(ch); } if !frag.is_empty() { - units.push(frag); + units.push((frag, line_index)); } } @@ -530,18 +534,24 @@ impl SemanticChunker { let mut char_count = 0usize; while j < units.len() && (j - i) < self.max_chunk_lines - && (j == i || char_count + units[j].len() < self.max_chunk_chars) + && (j == i || char_count + units[j].0.len() < self.max_chunk_chars) { - char_count += units[j].len() + 1; + char_count += units[j].0.len() + 1; j += 1; } let end = if j > i { j } else { i + 1 }; - let content = units[i..end].join("\n"); + let mut content = units[i].0.clone(); + for index in (i + 1)..end { + if units[index].1 != units[index - 1].1 { + content.push('\n'); + } + content.push_str(&units[index].0); + } let mut piece = Chunk::new( content, - chunk.start_line + i, - chunk.start_line + end, + chunk.start_line + units[i].1, + chunk.start_line + units[end - 1].1, chunk.kind, chunk.path.clone(), ); @@ -591,7 +601,7 @@ impl SemanticChunker { let mut split_chunk = Chunk::new( content, chunk.start_line + i, - chunk.start_line + end, + chunk.start_line + end - 1, chunk.kind, chunk.path.clone(), ); diff --git a/core/src/chunker/semantic_range_tests.rs b/core/src/chunker/semantic_range_tests.rs new file mode 100644 index 00000000..c06b0d12 --- /dev/null +++ b/core/src/chunker/semantic_range_tests.rs @@ -0,0 +1,44 @@ +use super::*; + +#[test] +fn structured_split_bounds_are_inclusive() { + let source = format!("fn example() {{\n{}}}", " do_work();\n".repeat(180)); + let chunks = SemanticChunker::new(80, 6000, 10) + .chunk_semantic(Language::Rust, Path::new("example.rs"), &source) + .unwrap(); + assert_eq!( + chunks + .iter() + .map(|chunk| (chunk.start_line, chunk.end_line)) + .collect::>(), + [(1, 80), (71, 150), (141, 182)] + ); +} + +#[test] +fn fragmented_utf8_lines_keep_physical_positions() { + for (language, path) in [ + (Language::Markdown, "example.md"), + (Language::Unknown, "example.data"), + ] { + let source = format!("short\n{}\nlast", "界".repeat(5000)); + let chunks = SemanticChunker::new(80, 6000, 10) + .chunk_semantic(language, Path::new(path), &source) + .unwrap(); + assert!(chunks.len() >= 3); + let mut ranges = Vec::new(); + for chunk in chunks { + assert!((1..=3).contains(&chunk.start_line)); + assert!((chunk.start_line..=3).contains(&chunk.end_line)); + assert!(chunk.content.len() <= 6000); + if chunk.content.contains("short") { + assert_eq!(chunk.start_line, 1); + } + if chunk.content.contains("last") { + assert_eq!(chunk.end_line, 3); + } + ranges.push((chunk.start_line, chunk.end_line)); + } + assert_eq!(ranges, [(1, 1), (2, 2), (2, 2), (2, 3)]); + } +} diff --git a/core/src/embed/batch.rs b/core/src/embed/batch.rs index 6a0ca9e8..07059d05 100644 --- a/core/src/embed/batch.rs +++ b/core/src/embed/batch.rs @@ -145,7 +145,7 @@ impl BatchEmbedder { /// - Signature (if available) /// - Docstring (if available) /// - Content - fn prepare_text(chunk: &Chunk, model_type: ModelType) -> String { + pub fn prepare_text(chunk: &Chunk, model_type: ModelType) -> String { let mut parts = Vec::new(); // Add context breadcrumbs (e.g., "File: main.rs > Class: Server") diff --git a/core/src/embed/mod.rs b/core/src/embed/mod.rs index 223031ed..87789315 100644 --- a/core/src/embed/mod.rs +++ b/core/src/embed/mod.rs @@ -10,6 +10,17 @@ pub use config::{active_config, configure, save_defaults, EmbedConfig}; pub use identity::EmbeddingModel; pub use provider::Embedder; +/// Construct a provider without opening a local index or embedding cache. +/// Model artifacts for local inference remain managed by FastEmbedder. +pub fn create_embedder(config: EmbedConfig, local_model: ModelType) -> Result> { + config.validate()?; + if config.remote() { + Ok(Box::new(openai::OpenAiEmbedder::new(config)?)) + } else { + Ok(Box::new(FastEmbedder::with_model(local_model)?)) + } +} + use anyhow::Result; #[allow(unused_imports)] // group_embedded_chunks_by_path unused in the bin target (lib facade consumes it) diff --git a/server/Cargo.toml b/server/Cargo.toml index d90d3d1a..245bfa87 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -9,3 +9,27 @@ description = "HTTP serve binary for codesearch (built on codesearch-core)" [lib] name = "codesearch_server" path = "src/lib.rs" + +[features] +default = ["download-binaries"] +download-binaries = ["codesearch-core/download-binaries"] +load-dynamic = ["codesearch-core/load-dynamic"] + +[dependencies] +codesearch-core = { path = "../core", default-features = false } +anyhow = { workspace = true } +axum = { workspace = true } +clap = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +tokio = { workspace = true, features = ["full"] } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +thiserror = "2.0" +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres", "derive"] } +pgvector = { version = "0.4", features = ["sqlx"] } +url = "2" + +[dev-dependencies] +reqwest = { workspace = true } diff --git a/server/README.md b/server/README.md new file mode 100644 index 00000000..5616ed7b --- /dev/null +++ b/server/README.md @@ -0,0 +1,220 @@ +# codesearch-server + +An HTTP server for code search with PostgreSQL-backed storage and server-side +embedding. This is a separate binary, not a storage mode for the local CLI. +`codesearch` and `codesearch-core` do not depend on SQLx or pgvector. The server +reuses core chunking and embedding providers, **not** local LMDB/Tantivy indices, +local embedding caches, the CLI registry, or client-side SQL integration. + +## Security and supported capabilities + +**No authentication or authorization. Loopback only.** The binary refuses a +non-loopback `--listen` address; default `127.0.0.1:39726`. Before all routes, +the router requires a loopback IP or exact `localhost` HTTP authority (optional +valid nonzero port) and rejects non-loopback/malformed browser Origins with HTTP +403. Native clients may omit Origin. This blocks hostile Host/DNS-rebinding +requests; it is not authentication, and forwarded headers are not trusted. +Any local process can +read and modify all registered repositories. Do not proxy, port-forward or +expose this service to untrusted callers. There is no shared-key compatibility. +Auth, federation, publisher/scheduler integration, filesystem watching, symbol +navigation, working-copy namespaces and repository-wide snapshot publication +are not implemented. Publication is explicit, per-file HTTP input; the server +never reads a caller-supplied filesystem path. `/health` is process liveness, +not a database-readiness claim. + +## Database prerequisites + +Use a dedicated database. Provision **pg_search 0.27.1** and **pgvector >=0.8**; +other pg_search versions are rejected rather than silently using a legacy API. +The qualified image is +`paradedb/paradedb:0.27.1-pg17@sha256:8e5483653e2af1b904428dd025e4ac9564c01a4e10d3af196e73537f8cb94c3f` +(PostgreSQL 17.12, pg_search 0.27.1, vector 0.8.6). Self-managed pg_search needs +`shared_preload_libraries='pg_search'` and a PostgreSQL restart. A DBA must run: + +```sql +CREATE EXTENSION vector; +CREATE EXTENSION pg_search CASCADE; +SELECT extname, extversion FROM pg_extension; +``` + +The application role needs connection and schema/table/index creation and CRUD +privileges. Startup creates `cs_server_*` tables and a source-code-tokenized +ParadeDB BM25 index transactionally; concurrent startup is serialized. All +repositories and the PostgreSQL embedding cache share one recorded embedding +fingerprint/dimension. A mismatch or unknown schema version fails startup. +Changing model, dimensions, retrieval prefixes or server document representation +requires a **separate database and reindex**, never an automatic destructive reset. +The database fingerprint includes the server document representation; incompatible +representations are rejected without migration or automatic deletion. As in core, endpoint changes +are allowed for the same model identity; operators must ensure the replacement +endpoint really serves the same embedding space (an opaque model name cannot +prove that). Endpoint URLs are not persisted as embedding identity. + +Set `CODESEARCH_DATABASE_URL` through your process environment/secret manager. +TLS defaults to `verify-full` (configure a trusted CA and hostname); only an +explicit URL `sslmode` parameter overrides it. `sslmode=disable` is for isolated +loopback test databases, not remote deployments. URLs/parser/connection errors +are redacted, SQL logging is disabled and HTTP storage/provider errors expose +only categories, not credentials, source text or response bodies. + +## Run + +```sh +# Normal build uses the same ONNX feature as the CLI. +cargo build -p codesearch-server +export CODESEARCH_DATABASE_URL='postgres://ROLE@HOST/DEDICATED_DB' +# Optional remote OpenAI-compatible provider; no saved local defaults are read. +export CODESEARCH_EMBED_PROVIDER=openai +export CODESEARCH_EMBED_BASE_URL=https://your-embedding-endpoint.example/v1 +export CODESEARCH_EMBED_API_KEY='...' +export CODESEARCH_EMBED_DIMENSIONS=768 +cargo run -p codesearch-server -- --model YOUR_REMOTE_MODEL +``` + +For local inference omit the remote settings, select e.g. `--model minilm-l6-q`. +Local model artifacts may be downloaded by core; no local index/cache is opened. +For machines needing dynamic ONNX use +`--no-default-features --features load-dynamic` and supply `ORT_DYLIB_PATH` for +local inference. Remote-only execution does not load ONNX. Remote provider +query/document transformations and validation come from core `EmbedConfig`; +queries use `embed_queries`, documents use `embed_documents`. + +## HTTP contract + +JSON, no MCP/federation compatibility surface: + +| Method | Path | Purpose | +|---|---|---| +| GET | `/health` | Process liveness | +| POST | `/repositories` | Register `{name,description}` (identical replay allowed; differing metadata conflicts) | +| GET | `/repositories?after=NAME&limit=100` | Ordered metadata/revision list; keyset pagination, max 1000 | +| GET | `/repositories/NAME/files?after=PATH&limit=100` | Ordered file sync state including tombstones; keyset pagination, max 1000 | +| GET | `/repositories/NAME/file?path=src%2Fmain.rs` | Exact file state, JSON null if never indexed | +| PUT | `/repositories/NAME/files` | Atomic replacement or deletion | +| POST | `/search` | Explicit scoped keyword/vector/hybrid search | + +```sh +curl -fsS http://127.0.0.1:39726/repositories -H 'Content-Type: application/json' \ + -d '{"name":"example","description":"Example source"}' +curl -fsS -X PUT http://127.0.0.1:39726/repositories/example/files \ + -H 'Content-Type: application/json' \ + -d '{"path":"src/main.rs","expected_revision":0,"source_revision":"commit-abc","content":"fn main() { println!(\"hello\"); }"}' +curl -fsS http://127.0.0.1:39726/search -H 'Content-Type: application/json' \ + -d '{"repositories":["example"],"query":"hello","mode":"hybrid","limit":10,"path_prefix":"src/"}' +``` + +Files accept canonical relative slash-separated paths only (no aliases, +backslashes, drive prefixes, empty/dot/parent components). Maximum source size +1 MiB, 2048 chunks per file, request body 2 MiB. Search requires 1–32 explicit +repository names, 1–100 results and a nonempty query of at most 4096 bytes. +Unknown repositories are errors, never silently omitted. `path_prefix` is a +**literal** prefix applied before ranking/limit; `%` and `_` are not wildcards. +Unknown input fields are rejected. + +Repository and file lists default to 100 rows, with `limit` from 1 to 1000. +Start without `after`, then pass the last returned `name` (repositories) or +`path` (files), URL-encoded, as `after` until an empty page. The cursor is +exclusive; pages are ordered by that key. Traversal is not a multi-request +snapshot when registrations/publications occur concurrently. + +Notebook publication requires valid JSON with a `cells` array and well-formed +cell type/source fields (string source or array of strings). Malformed input +returns HTTP 400 before inference or replacement; `{"cells":[]}` is an +intentional valid empty publication. Notebook outputs/metadata are not indexed. + +`expected_revision=0` means never indexed. Each successful file update increments +its revision, even deletion (`content:null`) or empty-file publication +(`content:""`). The `content` field is required; omitting it returns HTTP 422, +never a deletion. Deleted file tombstones are retained so stale writers cannot +recreate with revision zero (ABA). Read state and retry deliberately after HTTP +409; blindly replaying a request whose response was lost returns 409 if its +commit succeeded. `source_revision` is a bounded caller-supplied source label, +not a verified Git commit or whole-repository consistency claim. File state +includes SHA-256 of submitted content, chunk count, deletion flag and source +revision; repository revision increments with every committed file change. + +A server document is prepared from final chunk content plus core context, +signature/name and cleaned extracted documentation, using core embedding +preparation semantics. Documentation already inside source content is not added +a second time. This same document is persisted for BM25 and supplied to the +embedding provider; its SHA-256 is the cache key, not the chunker's pre-header +hash. Provider query/document prefixes remain provider transformations guarded +by the database fingerprint. Returned `content` and inclusive physical editor +line bounds describe the code chunk, not synthetic headers/metadata or preceding +documentation; fragments of one long source line retain the same line number. +A documentation-only hit may therefore return code without the matching comment. +**Notebook exception:** `.ipynb` line bounds are synthetic positions over extracted +cell-content lines, not raw JSON editor coordinates; they are for display/order, +not jump-to-source or source re-extraction. Republication replaces persisted +content and bounds with those computed from the submitted source. + +Chunking, validation and all embedding/cache lookups finish before deletion. +A repository row lock then rechecks file CAS in the transaction. Cache entries, +chunks, BM25 mutations, file sync state and repository revision commit together. +Global cache insertions use sorted unique document hashes independently of source +chunk order, so cross-repository publications acquire shared keys consistently. +Provider and pre-commit SQL failures preserve the previous published file state. +Transaction atomicity guarantees complete old or complete new state, never a +partial replacement. A transport failure during COMMIT can leave the outcome +unknown (the database may have committed); read file state before deciding +whether to retry. Concurrent writes to different files in one repository serialize +only their final transactions; same-file stale writers conflict. Deleting a +missing file still requires expected revision zero and creates a tombstone. + +Keyword mode uses pg_search `|||` **any-token**, plain bound text, source-code +tokenization and BM25. The search transaction uses `SET LOCAL +plan_cache_mode=force_custom_plan` so repeated prepared queries keep the required +ParadeDB scoring scan. Corpus statistics are database-wide. Vector mode uses +exact pgvector cosine ranking within explicit scope (not approximate ANN, so no +filtered ANN underfill). Hybrid uses reciprocal-rank fusion, constant 60, up to +4×limit bounded candidates per branch, one repeatable-read snapshot. Scores +are mode-specific; there is no universal relevance threshold. Search returns +indexed content, line bounds, repository/path and file/source revisions. +Storage/provider failures remain HTTP 503/502 rather than empty hits. No local +cache or silent keyword fallback on vector failure. PostgreSQL statement/idle +transaction timeouts are 30 seconds; pool maximum is eight connections. Exact +vector scans and serialized provider access prioritize scoped retrieval correctness +over large-corpus throughput. Cache retention/garbage collection and per-user +resource quotas are deferred; this service is not safe for public exposure. + +## Isolated behavioral qualification + +Never point this at a production/shared database. The ignored integration test +creates and drops a unique database; the role must have `CREATEDB` and extension +privileges. Failures deliberately leave the named disposable database available +for inspection. Use the pinned image above with a private disposable volume and +loopback-only random host port, then: + +```sh +export CODESEARCH_TEST_DATABASE_URL='postgres://TEST_ROLE:TEST_PASSWORD@127.0.0.1:TEST_PORT/TEST_DB?sslmode=disable' +cargo test -p codesearch-server --lib -- --include-ignored --nocapture +# Or remote-only dynamic linkage: +cargo test -p codesearch-server --no-default-features --features load-dynamic --lib -- --include-ignored --nocapture +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --lib --bins +# Local dependency isolation: neither command should find sqlx/pgvector. +cargo tree -p codesearch-core --edges normal +cargo tree -p codesearch --edges normal +``` + +The test runs real HTTP server interfaces and real pg_search/pgvector, with an +explicitly **simulated deterministic OpenAI-compatible HTTP embedding boundary**. +It is not end-to-end inference or semantic-quality evidence. Cases include all +search modes, explicit single/multi-repository and path scopes, document/query +prefix semantics, failed inference preserving old publication, SQL failure after +delete, old complete visibility from another connection during blocked insert, +terminated writer connection rollback, competing CAS, server/provider restart +and DB cache reuse, fingerprint/dimension/prefix mismatch, deletion/empty files, +tombstone ABA, validation and unavailable storage returning an error. Regressions +also cover long-function renames/shared slices, same-document cache reuse, +doc-only keyword/vector input, persisted documentation retrieval after restart, +prior-representation refusal without mutation, and Host/Origin HTTP rejection +before all routes. Additional cases cover invalid-notebook preservation, valid +empty notebooks, physical split ranges, 1001-repository pagination, and a real +PostgreSQL trigger enforcing sorted unique cache inserts during concurrent +reversed-source publication (not a timing-based deadlock reproduction). A physical +PostgreSQL/container crash/restart is an additional external qualification step; +the test simulates interruption by terminating the publishing backend, not by +claiming an in-process restart is a database crash. diff --git a/server/src/document.rs b/server/src/document.rs new file mode 100644 index 00000000..3bf7071c --- /dev/null +++ b/server/src/document.rs @@ -0,0 +1,32 @@ +use codesearch_core::{ + chunker::Chunk, + embed::{BatchEmbedder, ModelType}, +}; + +/// One representation for provider input, BM25 and cache identity. Source content +/// and editor line bounds remain separate; metadata is not a source excerpt. +pub(crate) struct Document { + pub text: String, + pub hash: String, +} +impl Document { + pub fn new(chunk: &Chunk, model: ModelType) -> Self { + let mut chunk = chunk.clone(); + // Some grammars (e.g. Python) include the docstring inside the AST node. + // Preserve it there instead of adding a second Documentation section. + if chunk + .docstring + .as_ref() + .is_some_and(|doc| chunk.content.contains(doc)) + { + chunk.docstring = None; + } + let text = BatchEmbedder::prepare_text(&chunk, model); + let hash = Chunk::compute_hash(&text); + Self { text, hash } + } +} + +#[cfg(test)] +#[path = "document_tests.rs"] +mod tests; diff --git a/server/src/document_integration_tests.rs b/server/src/document_integration_tests.rs new file mode 100644 index 00000000..10bdd40d --- /dev/null +++ b/server/src/document_integration_tests.rs @@ -0,0 +1,323 @@ +use super::*; + +pub(super) struct TestDatabase { + admin: sqlx::PgPool, + pub(super) pool: sqlx::PgPool, + name: String, + url: String, +} +impl TestDatabase { + pub(super) async fn new() -> Self { + let options: sqlx::postgres::PgConnectOptions = + std::env::var("CODESEARCH_TEST_DATABASE_URL") + .expect("set disposable CODESEARCH_TEST_DATABASE_URL") + .parse() + .unwrap(); + let admin = sqlx::PgPool::connect_with(options.clone()).await.unwrap(); + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + static SEQUENCE: AtomicUsize = AtomicUsize::new(0); + let sequence = SEQUENCE.fetch_add(1, Ordering::SeqCst); + let name = format!("cs_stage2_{}_{}_{}", std::process::id(), nonce, sequence); + // Only this freshly generated database is ever modified/dropped. + eprintln!("isolated regression database: {name}"); + admin + .execute(format!("CREATE DATABASE {name}").as_str()) + .await + .unwrap(); + let options = options.database(&name); + let pool = sqlx::PgPool::connect_with(options.clone()).await.unwrap(); + pool.execute("CREATE EXTENSION IF NOT EXISTS vector; CREATE EXTENSION IF NOT EXISTS pg_search CASCADE").await.unwrap(); + Self { + admin, + pool, + name, + url: options.to_url_lossy().to_string(), + } + } + pub(super) async fn store(&self, config: &EmbedConfig) -> Store { + Store::connect( + &self.url, + Embedding::new(config.clone(), ModelType::default()).unwrap(), + ) + .await + .unwrap() + } + pub(super) async fn cleanup(self) { + self.pool.close().await; + self.admin + .execute(format!("DROP DATABASE {} WITH (FORCE)", self.name).as_str()) + .await + .unwrap(); + self.admin.close().await; + } +} +pub(super) async fn boundary(state: &Simulated) -> Service { + serve( + axum::Router::new() + .route("/v1/embeddings", post(embeddings)) + .with_state(state.clone()), + ) + .await +} +async fn register(client: &reqwest::Client, service: &Service, name: &str) { + request( + client, + service, + reqwest::Method::POST, + "/repositories", + json!({"name":name,"description":"regression"}), + 200, + ) + .await; +} +async fn publish( + client: &reqwest::Client, + service: &Service, + repo: &str, + revision: i64, + source: &str, +) -> Value { + let mut body = update(revision, Some(source)); + body["path"] = json!("src/example.rs"); + request( + client, + service, + reqwest::Method::PUT, + &format!("/repositories/{repo}/files"), + body, + 200, + ) + .await +} + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search 0.27.1 + vector and CREATEDB"] +async fn long_function_rename_embeds_final_slices_and_reuses_identical_text() { + let db = TestDatabase::new().await; + let state = Simulated::default(); + let boundary = boundary(&state).await; + let config = config(&boundary.url); + let service = serve(router(db.store(&config).await)).await; + let client = reqwest::Client::new(); + register(&client, &service, "first").await; + register(&client, &service, "second").await; + let body = (0..180) + .map(|i| format!(" let value_{i} = {i};\n")) + .collect::(); + let original = format!("fn originallong() {{\n{body}}}"); + let renamed = original.replace("originallong", "renamedlong"); + let first = publish(&client, &service, "first", 0, &original).await; + let count = first["chunk_count"].as_u64().unwrap() as usize; + assert!(count >= 3, "must exercise shared middle/tail slices"); + state.inputs.lock().unwrap().clear(); + publish(&client, &service, "first", 1, &renamed).await; + let inputs = state.inputs.lock().unwrap().clone(); + assert_eq!( + inputs.len(), + count, + "each changed final signature-bearing slice needs fresh inference; inputs: {inputs:?}" + ); + assert!(inputs.iter().all(|text| text.contains("renamedlong"))); + for input in &inputs { + let text = input.strip_prefix("document:").unwrap(); + let cached: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM cs_server_embedding_cache WHERE content_hash=$1)", + ) + .bind(codesearch_core::chunker::Chunk::compute_hash(text)) + .fetch_one(&db.pool) + .await + .unwrap(); + assert!( + cached, + "cache identity hashes exactly the representation supplied to provider" + ); + } + let hits = search(&client, &service, &["first"], "renamedlong", "vector", None).await; + assert_eq!(hits.len(), count); + assert!( + hits.iter() + .all(|hit| hit["score"].as_f64().unwrap() > 0.999), + "persisted vectors must match renamed inputs: {hits:?}" + ); + let before = state.documents.load(Ordering::SeqCst); + state.fail.store(true, Ordering::SeqCst); + publish(&client, &service, "second", 0, &renamed).await; + assert_eq!( + state.documents.load(Ordering::SeqCst), + before, + "identical representations reuse cache across repositories" + ); + drop(service); + drop(boundary); + db.cleanup().await; +} + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search 0.27.1 + vector and CREATEDB"] +async fn extracted_documentation_is_searchable_embedded_and_persisted() { + let db = TestDatabase::new().await; + let state = Simulated::default(); + let boundary = boundary(&state).await; + let config = config(&boundary.url); + let service = serve(router(db.store(&config).await)).await; + let client = reqwest::Client::new(); + register(&client, &service, "docs").await; + publish( + &client, + &service, + "docs", + 0, + "/// quasarneedle describes the hidden behavior\nfn example() {}\n", + ) + .await; + let hits = search( + &client, + &service, + &["docs"], + "quasarneedle", + "keyword", + None, + ) + .await; + assert_eq!( + hits.len(), + 1, + "term appears only in extracted preceding documentation" + ); + assert_eq!(hits[0]["content"], "fn example() {}"); + assert_eq!( + hits[0]["start_line"], 2, + "source bounds must still describe the AST code, not synthetic documentation" + ); + assert_eq!(hits[0]["end_line"], 2); + let inputs = state.inputs.lock().unwrap().clone(); + assert_eq!(inputs.len(), 1); + assert_eq!(inputs[0].matches("quasarneedle").count(), 1); + let document: String = sqlx::query_scalar("SELECT document FROM cs_server_chunks") + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!( + inputs[0].strip_prefix("document:").unwrap(), + document, + "BM25 persistence and provider input share one representation" + ); + drop(service); + let service = serve(router(db.store(&config).await)).await; + state.fail.store(true, Ordering::SeqCst); + let persisted = search( + &client, + &service, + &["docs"], + "quasarneedle", + "keyword", + None, + ) + .await; + assert_eq!( + persisted.len(), + 1, + "documentation survives a new Store/provider/router" + ); + publish( + &client, + &service, + "docs", + 1, + "/// quasarneedle describes the hidden behavior\nfn example() {}\n", + ) + .await; + state.fail.store(false, Ordering::SeqCst); + let vectors = search(&client, &service, &["docs"], "quasarneedle", "vector", None).await; + assert!( + vectors[0]["score"].as_f64().unwrap() > 0.999, + "documentation reached the provider and persisted vector" + ); + // Documentation-only edits must invalidate the representation, without changing source code. + let before = state.documents.load(Ordering::SeqCst); + publish( + &client, + &service, + "docs", + 2, + "/// changedneedle describes new behavior\nfn example() {}\n", + ) + .await; + assert_eq!(state.documents.load(Ordering::SeqCst), before + 1); + assert!(search( + &client, + &service, + &["docs"], + "quasarneedle", + "keyword", + None + ) + .await + .is_empty()); + assert_eq!( + search( + &client, + &service, + &["docs"], + "changedneedle", + "keyword", + None + ) + .await + .len(), + 1 + ); + drop(service); + drop(boundary); + db.cleanup().await; +} + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search 0.27.1 + vector and CREATEDB"] +async fn prior_document_representation_is_refused_without_mutation() { + let db = TestDatabase::new().await; + let state = Simulated::default(); + let boundary = boundary(&state).await; + let mut config = config(&boundary.url); + config.embed_dimensions = Some(3); + let legacy = config.fingerprint(); + db.pool.execute("CREATE TABLE cs_server_index (singleton boolean PRIMARY KEY CHECK(singleton), schema_version integer NOT NULL, fingerprint text NOT NULL, dimensions integer NOT NULL); CREATE TABLE retained_marker (value text); INSERT INTO retained_marker VALUES ('do not destroy')").await.unwrap(); + sqlx::query("INSERT INTO cs_server_index VALUES (true,1,$1,3)") + .bind(&legacy) + .execute(&db.pool) + .await + .unwrap(); + let error = Store::connect( + &db.url, + Embedding::new(config, ModelType::default()).unwrap(), + ) + .await + .err() + .expect("old representation must require fresh database/reindex"); + assert!(error.to_string().contains("mismatch")); + let recorded: String = sqlx::query_scalar("SELECT fingerprint FROM cs_server_index") + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(recorded, legacy); + let marker: String = sqlx::query_scalar("SELECT value FROM retained_marker") + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(marker, "do not destroy"); + let tables: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'cs_server_%'", + ) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!( + tables, 1, + "failed startup does not migrate/create index tables" + ); + drop(boundary); + db.cleanup().await; +} diff --git a/server/src/document_tests.rs b/server/src/document_tests.rs new file mode 100644 index 00000000..51fbcf65 --- /dev/null +++ b/server/src/document_tests.rs @@ -0,0 +1,42 @@ +use super::*; +use codesearch_core::chunker::{ChunkKind, SemanticChunker}; +use codesearch_core::file::Language; +use std::path::Path; + +#[test] +fn document_uses_final_content_and_core_metadata_preparation() { + let mut chunk = Chunk::new( + "fn example() {}".into(), + 2, + 2, + ChunkKind::Function, + "example.rs".into(), + ); + chunk.context = vec!["File: example.rs".into()]; + chunk.signature = Some("fn example()".into()); + chunk.docstring = Some("/// quasarneedle".into()); + let document = Document::new(&chunk, ModelType::default()); + assert!(document.text.contains("Context: File: example.rs")); + assert!(document.text.contains("Signature: fn example()")); + assert!(document.text.contains("Name: example")); + assert!(document.text.contains("Documentation: quasarneedle")); + assert_eq!(document.hash, Chunk::compute_hash(&document.text)); + chunk.content.insert_str(0, "// [Part 1/2] fn renamed()\n"); + let changed = Document::new(&chunk, ModelType::default()); + assert_ne!(changed.hash, document.hash, "ignore stale core chunk.hash"); +} + +#[test] +fn python_inline_documentation_is_not_duplicated() { + let source = + "def example():\n \"\"\"quasarneedle describes this function.\"\"\"\n return 42\n"; + let chunks = SemanticChunker::new(80, 6000, 10) + .chunk_semantic(Language::Python, Path::new("example.py"), source) + .unwrap(); + let chunk = chunks + .iter() + .find(|chunk| chunk.docstring.is_some()) + .expect("production extractor must exercise inline docstring"); + let document = Document::new(chunk, ModelType::default()); + assert_eq!(document.text.matches("quasarneedle").count(), 1); +} diff --git a/server/src/embedding.rs b/server/src/embedding.rs new file mode 100644 index 00000000..86ad68b0 --- /dev/null +++ b/server/src/embedding.rs @@ -0,0 +1,60 @@ +use crate::{validate_vector, Error, Result}; +use codesearch_core::embed::{create_embedder, EmbedConfig, Embedder, ModelType}; +use std::sync::{Arc, Mutex}; + +/// No local index/cache: only provider model artifacts may live on disk. +#[derive(Clone)] +pub struct Embedding { + provider: Arc>>, + pub(crate) fingerprint: String, + pub(crate) dimensions: usize, + pub(crate) document_model: ModelType, +} +impl Embedding { + pub fn new(mut config: EmbedConfig, model: ModelType) -> anyhow::Result { + let provider = create_embedder(config.clone(), model)?; + let dimensions = provider.dimensions(); + let document_model = provider.local_model().unwrap_or_default(); + anyhow::ensure!( + (1..=2000).contains(&dimensions), + "embedding dimensions must be 1 to 2000" + ); + let fingerprint = if config.remote() { + // Match core identity semantics, but normalize probed dimensions. + config.embed_dimensions = Some(dimensions); + config.fingerprint() + } else { + format!("local:{}:{dimensions}", model.short_name()) + }; + Ok(Self { + provider: Arc::new(Mutex::new(provider)), + fingerprint: format!("{fingerprint}:server-documents-v2"), + dimensions, + document_model, + }) + } + pub(crate) async fn embed(&self, texts: Vec, query: bool) -> Result>> { + let provider = self.provider.clone(); + let dimensions = self.dimensions; + tokio::task::spawn_blocking(move || { + let count = texts.len(); + let mut provider = provider.lock().map_err(|_| Error::Embedding)?; + // Provider errors may contain untrusted response text; never forward it. + let vectors = if query { + provider.embed_queries(texts) + } else { + provider.embed_documents(texts) + } + .map_err(|_| Error::Embedding)?; + if vectors.len() != count { + return Err(Error::Embedding); + } + for vector in &vectors { + validate_vector(vector, dimensions)?; + } + Ok(vectors) + }) + .await + .map_err(|_| Error::Embedding)? + } +} diff --git a/server/src/http.rs b/server/src/http.rs new file mode 100644 index 00000000..08589a5d --- /dev/null +++ b/server/src/http.rs @@ -0,0 +1,159 @@ +use crate::{ + Error, FileState, FileUpdate, Repository, RepositoryInput, SearchHit, SearchRequest, Store, + MAX_FILE_BYTES, +}; +use axum::{ + extract::{DefaultBodyLimit, Path, Query, Request, State}, + http::{header, uri::Authority, StatusCode}, + middleware::{self, Next}, + response::{IntoResponse, Response}, + routing::{get, post}, + Json, Router, +}; +use serde::Deserialize; + +pub fn router(store: Store) -> Router { + Router::new() + .route( + "/health", + get(|| async { + Json(serde_json::json!({"status":"up", "authentication":"none", "stage":2})) + }), + ) + .route("/repositories", get(repositories).post(register)) + .route("/repositories/{name}/files", get(files).put(update_file)) + .route("/repositories/{name}/file", get(file)) + .route("/search", post(search)) + .layer(DefaultBodyLimit::max(MAX_FILE_BYTES * 2)) + .layer(middleware::from_fn(loopback_boundary)) + .with_state(store) +} +// Parse an HTTP authority without URL normalization, DNS resolution, userinfo, +// empty ports or ambiguous unbracketed IPv6. Never trust forwarded headers. +fn loopback_authority(value: &str) -> bool { + let Ok(authority) = value.parse::() else { + return false; + }; + let host = authority.host(); + let Some(suffix) = value.strip_prefix(host) else { + return false; + }; + if !suffix.is_empty() { + let Some(port) = suffix.strip_prefix(':') else { + return false; + }; + if port.is_empty() + || !port.bytes().all(|byte| byte.is_ascii_digit()) + || !port.parse::().is_ok_and(|port| port > 0) + { + return false; + } + } + let ip = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(host); + host.eq_ignore_ascii_case("localhost") + || ip + .parse::() + .is_ok_and(|ip| ip.is_loopback()) +} +async fn loopback_boundary(request: Request, next: Next) -> Response { + let mut hosts = request.headers().get_all(header::HOST).iter(); + let host = hosts.next(); + let valid_host = match host { + Some(host) => host.to_str().is_ok_and(loopback_authority) && hosts.next().is_none(), + None => request.uri().authority().is_some(), // HTTP/2 :authority + }; + let valid_authority = request + .uri() + .authority() + .is_none_or(|value| loopback_authority(value.as_str())); + let mut origins = request.headers().get_all(header::ORIGIN).iter(); + let valid_origin = match origins.next() { + None => true, // Native clients need not supply Origin. + Some(origin) => { + origin.to_str().is_ok_and(|origin| { + origin + .strip_prefix("http://") + .or_else(|| origin.strip_prefix("https://")) + .is_some_and(loopback_authority) + }) && origins.next().is_none() + } + }; + if !valid_host || !valid_authority || !valid_origin { + return ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({"error":"loopback Host and Origin required"})), + ) + .into_response(); + } + next.run(request).await +} +impl IntoResponse for Error { + fn into_response(self) -> Response { + let status = match &self { + Self::Invalid(_) => StatusCode::BAD_REQUEST, + Self::Conflict => StatusCode::CONFLICT, + Self::NotFound => StatusCode::NOT_FOUND, + Self::Embedding => StatusCode::BAD_GATEWAY, + Self::Storage(_) => StatusCode::SERVICE_UNAVAILABLE, + }; + // Database messages can echo bound source and infrastructure details. + // Preserve the error category, never leak the underlying diagnostic. + (status, Json(serde_json::json!({"error":self.to_string()}))).into_response() + } +} +async fn register( + State(store): State, + Json(input): Json, +) -> Result, Error> { + store.register(input).await.map(Json) +} +async fn repositories( + State(store): State, + Query(page): Query, +) -> Result>, Error> { + store.repositories(&page.after, page.limit).await.map(Json) +} +#[derive(Deserialize)] +struct Page { + #[serde(default)] + after: String, + #[serde(default = "page_limit")] + limit: i64, +} +fn page_limit() -> i64 { + 100 +} +async fn files( + State(store): State, + Path(name): Path, + Query(page): Query, +) -> Result>, Error> { + store.files(&name, &page.after, page.limit).await.map(Json) +} +#[derive(Deserialize)] +struct FileQuery { + path: String, +} +async fn file( + State(store): State, + Path(name): Path, + Query(query): Query, +) -> Result>, Error> { + store.file(&name, &query.path).await.map(Json) +} +async fn update_file( + State(store): State, + Path(name): Path, + Json(input): Json, +) -> Result, Error> { + store.update_file(&name, input).await.map(Json) +} +async fn search( + State(store): State, + Json(input): Json, +) -> Result>, Error> { + store.search(input).await.map(Json) +} diff --git a/server/src/http_tests.rs b/server/src/http_tests.rs new file mode 100644 index 00000000..b3b8206e --- /dev/null +++ b/server/src/http_tests.rs @@ -0,0 +1,143 @@ +use super::*; + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search 0.27.1 + vector and CREATEDB"] +async fn loopback_authority_and_origin_are_checked_before_all_routes() { + let db = document_tests::TestDatabase::new().await; + let state = Simulated::default(); + let boundary = document_tests::boundary(&state).await; + let service = serve(router(db.store(&config(&boundary.url)).await)).await; + let client = reqwest::Client::new(); + for host in [ + "127.0.0.1", + "127.0.0.1:39726", + "localhost", + "LOCALHOST:80", + "[::1]", + "[::1]:65535", + ] { + let response = client + .get(format!("{}/health", service.url)) + .header("host", host) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "native host {host}"); + } + for origin in [ + "http://127.0.0.1", + "http://localhost:39726", + "https://localhost:443", + "http://[::1]:80", + ] { + let response = client + .get(format!("{}/health", service.url)) + .header("origin", origin) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "local origin {origin}"); + } + for host in [ + "untrusted.example:39726", + "localhost.untrusted.example", + "untrusted-localhost", + "127.0.0.1.untrusted.example", + "localhost@untrusted.example", + "untrusted.example@localhost", + "localhost:", + "localhost:bogus", + "localhost:65536", + "localhost:0", + "::1", + "[::1", + "localhost/path", + "localhost,127.0.0.1", + "", + ] { + let response = client + .get(format!("{}/health", service.url)) + .header("host", host) + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "reject host {host:?}" + ); + } + for origin in [ + "http://untrusted.example", + "http://localhost.untrusted.example", + "null", + "file://localhost", + "http://localhost/extra", + "http://localhost?query", + "http://localhost#fragment", + "http://attacker@localhost", + "http://localhost:", + "http://localhost:65536", + "http://localhost http://untrusted.example", + "", + ] { + let response = client + .get(format!("{}/health", service.url)) + .header("origin", origin) + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "reject origin {origin:?}" + ); + } + // Boundary rejection precedes handlers, JSON decoding and fallback routing. + for path in [ + "/health", + "/repositories", + "/repositories/missing/files", + "/repositories/missing/file", + "/search", + "/unknown", + ] { + let response = client + .post(format!("{}{path}", service.url)) + .header("host", "untrusted.example") + .body("not json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FORBIDDEN, "route {path}"); + let response = client + .put(format!("{}{path}", service.url)) + .header("origin", "http://untrusted.example") + .body("not json") + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "origin route {path}" + ); + } + // Duplicate header values must not let a trusted first value mask a hostile second. + for (name, good, bad) in [ + ("host", "localhost", "untrusted.example"), + ("origin", "http://localhost", "http://untrusted.example"), + ] { + let response = client + .get(format!("{}/health", service.url)) + .header(name, good) + .header(name, bad) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FORBIDDEN, "duplicate {name}"); + } + drop(service); + drop(boundary); + db.cleanup().await; +} diff --git a/server/src/integration_tests.rs b/server/src/integration_tests.rs new file mode 100644 index 00000000..54dad0c5 --- /dev/null +++ b/server/src/integration_tests.rs @@ -0,0 +1,635 @@ +//! Real pg_search/pgvector + HTTP server qualification. Embeddings below are +//! deliberately simulated at the OpenAI HTTP boundary, not inference quality. +use super::*; +use axum::{extract::State, http::StatusCode, routing::post, Json}; +use codesearch_core::embed::{EmbedConfig, ModelType}; +use serde_json::{json, Value}; +use sqlx::{ConnectOptions, Connection, Executor}; +use std::sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Mutex, +}; + +#[path = "document_integration_tests.rs"] +mod document_tests; +#[path = "http_tests.rs"] +mod http_tests; +#[path = "publication_tests.rs"] +mod publication_tests; + +#[derive(Clone, Default)] +struct Simulated { + fail: Arc, + documents: Arc, + queries: Arc, + inputs: Arc>>, +} +async fn embeddings( + State(state): State, + Json(body): Json, +) -> (StatusCode, Json) { + if state.fail.load(Ordering::SeqCst) { + return ( + StatusCode::BAD_REQUEST, + Json(json!({"error":"simulated failure"})), + ); + } + let data: Vec<_> = body["input"] + .as_array() + .unwrap() + .iter() + .enumerate() + .map(|(index, text)| { + let text = text.as_str().unwrap(); + if text.starts_with("query:") { + state.queries.fetch_add(1, Ordering::SeqCst); + } else { + assert!(text.starts_with("document:")); + state.documents.fetch_add(1, Ordering::SeqCst); + } + state.inputs.lock().unwrap().push(text.to_string()); + let vector = if text.contains("orchard") + || text.contains("renamedlong") + || text.contains("quasarneedle") + { + vec![1.0, 0.1, 0.1] + } else { + vec![0.1, 1.0, 0.1] + }; + json!({"index":index,"embedding":vector}) + }) + .collect(); + (StatusCode::OK, Json(json!({"data":data}))) +} +struct Service { + url: String, + task: tokio::task::JoinHandle<()>, +} +impl Drop for Service { + fn drop(&mut self) { + self.task.abort(); + } +} +async fn serve(app: axum::Router) -> Service { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + Service { + url, + task: tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }), + } +} +fn config(url: &str) -> EmbedConfig { + EmbedConfig { + embed_provider: Some("openai".into()), + embed_base_url: Some(format!("{url}/v1")), + model: "simulated-not-inference".into(), + embed_dimensions: Some(3), + embed_query_prefix: "query:".into(), + embed_document_prefix: "document:".into(), + ..Default::default() + } +} +async fn request( + client: &reqwest::Client, + service: &Service, + method: reqwest::Method, + path: &str, + body: Value, + status: u16, +) -> Value { + let response = client + .request(method, format!("{}{path}", service.url)) + .json(&body) + .send() + .await + .unwrap(); + let actual = response.status().as_u16(); + let body = response.text().await.unwrap(); + assert_eq!(actual, status, "{path}: {body}"); + serde_json::from_str(&body).unwrap() +} +fn update(revision: i64, content: Option<&str>) -> Value { + json!({"path":"src/a.txt","expected_revision":revision,"source_revision":format!("commit-{revision}"),"content":content}) +} +async fn search( + client: &reqwest::Client, + service: &Service, + repositories: &[&str], + query: &str, + mode: &str, + prefix: Option<&str>, +) -> Vec { + request(client, service, reqwest::Method::POST, "/search", json!({"repositories":repositories,"query":query,"mode":mode,"limit":10,"path_prefix":prefix}), 200).await.as_array().unwrap().clone() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires CODESEARCH_TEST_DATABASE_URL to a disposable pg_search 0.27.1 + pgvector instance with CREATEDB"] +async fn server_http_postgres_transaction_cache_and_recovery() { + let admin_url = std::env::var("CODESEARCH_TEST_DATABASE_URL") + .expect("set disposable CODESEARCH_TEST_DATABASE_URL"); + let admin_options: sqlx::postgres::PgConnectOptions = admin_url.parse().unwrap(); + let admin = sqlx::PgPool::connect_with(admin_options.clone()) + .await + .unwrap(); + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let database = format!("cs_stage2_{}_{}", std::process::id(), nonce); + // Generated ASCII identifier only; never interpolate caller input. + admin + .execute(format!("CREATE DATABASE {database}").as_str()) + .await + .unwrap(); + let options = admin_options.database(&database); + let pool = sqlx::PgPool::connect_with(options.clone()).await.unwrap(); + pool.execute( + "CREATE EXTENSION IF NOT EXISTS vector; CREATE EXTENSION IF NOT EXISTS pg_search CASCADE", + ) + .await + .unwrap(); + // Serialize/encode credentials through URL, never print them. + let database_url = options.to_url_lossy().to_string(); + let simulated = Simulated::default(); + let boundary = serve( + axum::Router::new() + .route("/v1/embeddings", post(embeddings)) + .with_state(simulated.clone()), + ) + .await; + let config = config(&boundary.url); + let embedding = Embedding::new(config.clone(), ModelType::default()).unwrap(); + let store = Store::connect(&database_url, embedding).await.unwrap(); + let service = serve(router(store.clone())).await; + let client = reqwest::Client::new(); + for name in ["first", "second"] { + request( + &client, + &service, + reqwest::Method::POST, + "/repositories", + json!({"name":name,"description":"isolated test corpus"}), + 200, + ) + .await; + } + let put = reqwest::Method::PUT; + let first = request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(0, Some("orchard ancientterm")), + 200, + ) + .await; + assert_eq!(first["revision"], 1); + let mut omitted = update(1, Some("unused")); + omitted.as_object_mut().unwrap().remove("content"); + let response = client + .put(format!("{}/repositories/first/files", service.url)) + .json(&omitted) + .send() + .await + .unwrap(); + assert_eq!( + response.status().as_u16(), + 422, + "omitted content must not delete" + ); + let state = request( + &client, + &service, + reqwest::Method::GET, + "/repositories/first/file?path=src%2Fa.txt", + Value::Null, + 200, + ) + .await; + assert_eq!(state["revision"], 1); + assert_eq!( + search( + &client, + &service, + &["first"], + "ancientterm", + "keyword", + None + ) + .await + .len(), + 1 + ); + assert_eq!( + first["content_hash"].as_str().unwrap(), + codesearch_core::chunker::Chunk::compute_hash("orchard ancientterm") + ); + request( + &client, + &service, + put.clone(), + "/repositories/second/files", + update(0, Some("orchard ancientterm")), + 200, + ) + .await; + assert_eq!( + simulated.documents.load(Ordering::SeqCst), + 1, + "second repository uses PostgreSQL cache" + ); + for mode in ["keyword", "vector", "hybrid"] { + let hits = search(&client, &service, &["first"], "orchard", mode, Some("src/")).await; + assert!(!hits.is_empty(), "{mode}"); + assert!(hits.iter().all(|h| h["repository"] == "first")); + assert!(search( + &client, + &service, + &["first"], + "orchard", + mode, + Some("elsewhere/") + ) + .await + .is_empty()); + assert_eq!( + search( + &client, + &service, + &["first", "second"], + "orchard", + mode, + None + ) + .await + .len(), + 2 + ); + } + // Exceed PostgreSQL's generic prepared-plan threshold across every pool + // connection; pg_search score must stay attached to a ParadeDB scan. + for _ in 0..64 { + assert_eq!( + search( + &client, + &service, + &["first"], + "ancientterm", + "keyword", + None + ) + .await + .len(), + 1 + ); + } + assert!( + simulated.queries.load(Ordering::SeqCst) >= 1, + "query prefix semantics reached real provider boundary" + ); + request( + &client, + &service, + reqwest::Method::POST, + "/search", + json!({"repositories":["missing"],"query":"orchard","mode":"keyword","limit":10}), + 404, + ) + .await; + request( + &client, + &service, + reqwest::Method::POST, + "/search", + json!({"repositories":[],"query":"orchard","mode":"keyword","limit":10}), + 400, + ) + .await; + let mut invalid = update(1, Some("bad")); + invalid["path"] = json!("../a.txt"); + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + invalid, + 400, + ) + .await; + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(0, None), + 409, + ) + .await; + simulated.fail.store(true, Ordering::SeqCst); + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(1, Some("new uncached failed source")), + 502, + ) + .await; + assert_eq!( + search( + &client, + &service, + &["first"], + "ancientterm", + "keyword", + None + ) + .await + .len(), + 1 + ); + request( + &client, + &service, + reqwest::Method::POST, + "/search", + json!({"repositories":["first"],"query":"orchard","mode":"hybrid","limit":10}), + 502, + ) + .await; + simulated.fail.store(false, Ordering::SeqCst); + // Inject failure after DELETE inside the actual application transaction. + pool.execute("CREATE FUNCTION cs_test_fault() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.content LIKE '%faulttoken%' THEN RAISE EXCEPTION 'injected insert failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER cs_test_fault BEFORE INSERT ON cs_server_chunks FOR EACH ROW EXECUTE FUNCTION cs_test_fault()").await.unwrap(); + let cache_before_fault: i64 = + sqlx::query_scalar("SELECT count(*) FROM cs_server_embedding_cache") + .fetch_one(&pool) + .await + .unwrap(); + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(1, Some("faulttoken")), + 503, + ) + .await; + assert_eq!( + search( + &client, + &service, + &["first"], + "ancientterm", + "keyword", + None + ) + .await + .len(), + 1 + ); + let state = request( + &client, + &service, + reqwest::Method::GET, + "/repositories/first/file?path=src%2Fa.txt", + Value::Null, + 200, + ) + .await; + assert_eq!(state["revision"], 1); + let cached: i64 = sqlx::query_scalar("SELECT count(*) FROM cs_server_embedding_cache") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + cached, cache_before_fault, + "failed transaction did not publish cache entries" + ); + // Hold the insertion after DELETE; a separate reader must see complete old + // rows, and killing the writer connection simulates interrupted publication. + pool.execute("CREATE FUNCTION cs_test_block() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.content LIKE '%blockedtoken%' THEN PERFORM pg_advisory_xact_lock(384003); END IF; RETURN NEW; END $$; CREATE TRIGGER cs_test_block BEFORE INSERT ON cs_server_chunks FOR EACH ROW EXECUTE FUNCTION cs_test_block()").await.unwrap(); + let mut lock = sqlx::PgConnection::connect_with(&options).await.unwrap(); + lock.execute("SELECT pg_advisory_lock(384003)") + .await + .unwrap(); + let writer_client = client.clone(); + let writer_url = format!("{}/repositories/first/files", service.url); + let writer = tokio::spawn(async move { + writer_client + .put(writer_url) + .json(&update(1, Some("blockedtoken"))) + .send() + .await + .unwrap() + .status() + }); + let mut blocked = false; + for _ in 0..100 { + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM pg_stat_activity WHERE datname=current_database() AND wait_event='advisory'").fetch_one(&pool).await.unwrap(); + if count > 0 { + blocked = true; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + assert!( + blocked, + "application writer reached post-delete blocking insert" + ); + for mode in ["keyword", "vector", "hybrid"] { + let hits = search(&client, &service, &["first"], "orchard", mode, None).await; + assert_eq!(hits.len(), 1); + assert_eq!(hits[0]["file_revision"], 1); + assert!(hits[0]["content"].as_str().unwrap().contains("ancientterm")); + } + pool.execute("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=current_database() AND wait_event='advisory'").await.unwrap(); + assert_eq!(writer.await.unwrap().as_u16(), 503); + lock.execute("SELECT pg_advisory_unlock(384003)") + .await + .unwrap(); + lock.close().await.unwrap(); + assert_eq!( + search( + &client, + &service, + &["first"], + "ancientterm", + "keyword", + None + ) + .await + .len(), + 1 + ); + // Competing same-revision writers: exactly one commits, one conflicts. + let a = client + .put(format!("{}/repositories/first/files", service.url)) + .json(&update(1, Some("replacementtoken alpha"))) + .send(); + let b = client + .put(format!("{}/repositories/first/files", service.url)) + .json(&update(1, Some("replacementtoken beta"))) + .send(); + let (a, b) = tokio::join!(a, b); + let mut statuses = vec![a.unwrap().status().as_u16(), b.unwrap().status().as_u16()]; + statuses.sort(); + assert_eq!(statuses, vec![200, 409]); + assert!(search( + &client, + &service, + &["first"], + "ancientterm", + "keyword", + None + ) + .await + .is_empty()); + assert_eq!( + search( + &client, + &service, + &["first"], + "replacementtoken", + "keyword", + None + ) + .await + .len(), + 1 + ); + // New service and provider over the same database: no local persisted state. + drop(service); + drop(store); + let restarted = Store::connect( + &database_url, + Embedding::new(config.clone(), ModelType::default()).unwrap(), + ) + .await + .unwrap(); + let service = serve(router(restarted.clone())).await; + let before = simulated.documents.load(Ordering::SeqCst); + simulated.fail.store(true, Ordering::SeqCst); + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(2, Some("orchard ancientterm")), + 200, + ) + .await; + assert_eq!( + simulated.documents.load(Ordering::SeqCst), + before, + "cache survived restart" + ); + simulated.fail.store(false, Ordering::SeqCst); + for changed in [ + EmbedConfig { + model: "other-model".into(), + ..config.clone() + }, + EmbedConfig { + embed_dimensions: Some(4), + ..config.clone() + }, + EmbedConfig { + embed_query_prefix: "other:".into(), + ..config.clone() + }, + ] { + let error = Store::connect( + &database_url, + Embedding::new(changed, ModelType::default()).unwrap(), + ) + .await + .err() + .unwrap(); + assert!(error.to_string().contains("mismatch")); + } + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(3, None), + 200, + ) + .await; + for mode in ["keyword", "vector", "hybrid"] { + assert!(search(&client, &service, &["first"], "orchard", mode, None) + .await + .is_empty()); + } + let deleted = request( + &client, + &service, + reqwest::Method::GET, + "/repositories/first/file?path=src%2Fa.txt", + Value::Null, + 200, + ) + .await; + assert_eq!(deleted["revision"], 4); + assert_eq!(deleted["deleted"], true); + assert_eq!(deleted["content_hash"], Value::Null); + request( + &client, + &service, + put.clone(), + "/repositories/first/files", + update(0, Some("stale recreate")), + 409, + ) + .await; + request( + &client, + &service, + put, + "/repositories/first/files", + update(4, Some("")), + 200, + ) + .await; + let empty = request( + &client, + &service, + reqwest::Method::GET, + "/repositories/first/files?limit=1", + Value::Null, + 200, + ) + .await; + assert_eq!(empty[0]["deleted"], false); + assert_eq!(empty[0]["chunk_count"], 0); + assert_eq!( + search(&client, &service, &["second"], "orchard", "hybrid", None) + .await + .len(), + 1 + ); + // A broken index/store must return an HTTP error, never an empty success. + pool.execute("ALTER TABLE cs_server_chunks RENAME TO cs_test_unavailable") + .await + .unwrap(); + request( + &client, + &service, + reqwest::Method::POST, + "/search", + json!({"repositories":["first"],"query":"orchard","mode":"keyword","limit":10}), + 503, + ) + .await; + drop(service); + drop(restarted); + drop(boundary); + pool.close().await; + admin + .execute(format!("DROP DATABASE {database} WITH (FORCE)").as_str()) + .await + .unwrap(); + admin.close().await; +} diff --git a/server/src/lib.rs b/server/src/lib.rs index fd446d1a..37561782 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -1,3 +1,15 @@ -//! codesearch-server: placeholder for stage 2 of the codesearch-server plan -//! (GH #384). The HTTP serve binary will be extracted from the CLI crate -//! here, on top of codesearch-core. +//! PostgreSQL-backed, unauthenticated loopback HTTP foundation (upstream #384 stage 2). +mod document; +mod embedding; +mod http; +mod store; +mod types; + +pub use embedding::Embedding; +pub use http::router; +pub use store::Store; +pub use types::*; + +#[cfg(test)] +#[path = "integration_tests.rs"] +mod integration_tests; diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 00000000..5e6eda91 --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,50 @@ +use clap::Parser; +use codesearch_core::embed::{EmbedConfig, ModelType}; +use codesearch_server::{router, Embedding, Store}; +use std::net::SocketAddr; + +#[derive(Parser)] +#[command(about = "Unauthenticated loopback PostgreSQL search foundation (#384 stage 2)")] +struct Args { + #[arg(long, default_value = "127.0.0.1:39726")] + listen: SocketAddr, + #[arg(long, default_value = "minilm-l6-q")] + model: String, + #[command(flatten)] + embedding: EmbedConfig, +} +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter("codesearch_server=info") + .init(); + let args = Args::parse(); + anyhow::ensure!( + args.listen.ip().is_loopback(), + "stage 2 has no authentication; only loopback listeners are supported" + ); + let mut config = args.embedding; + config.model = args.model.clone(); + let local = if config.remote() { + ModelType::default() + } else { + ModelType::parse(&args.model).ok_or_else(|| { + anyhow::anyhow!("unknown local model; use a supported core model short name") + })? + }; + let embedding = tokio::task::spawn_blocking(move || Embedding::new(config, local)).await??; + let url = std::env::var("CODESEARCH_DATABASE_URL") + .map_err(|_| anyhow::anyhow!("set CODESEARCH_DATABASE_URL"))?; + let store = Store::connect(&url, embedding).await?; + let listener = tokio::net::TcpListener::bind(args.listen).await?; + eprintln!( + "codesearch-server stage 2: unauthenticated loopback only, listening on {}", + listener.local_addr()? + ); + axum::serve(listener, router(store)) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + Ok(()) +} diff --git a/server/src/publication_tests.rs b/server/src/publication_tests.rs new file mode 100644 index 00000000..6746ed31 --- /dev/null +++ b/server/src/publication_tests.rs @@ -0,0 +1,317 @@ +use super::*; + +async fn setup() -> ( + document_tests::TestDatabase, + Service, + Service, + reqwest::Client, +) { + let db = document_tests::TestDatabase::new().await; + let boundary = document_tests::boundary(&Simulated::default()).await; + let service = serve(router(db.store(&config(&boundary.url)).await)).await; + (db, boundary, service, reqwest::Client::new()) +} +async fn register(client: &reqwest::Client, service: &Service, name: &str) { + request( + client, + service, + reqwest::Method::POST, + "/repositories", + json!({"name":name,"description":"publication regression"}), + 200, + ) + .await; +} +async fn publish( + client: &reqwest::Client, + service: &Service, + repo: &str, + path: &str, + revision: i64, + source: &str, + status: u16, +) -> Value { + let mut body = update(revision, Some(source)); + body["path"] = json!(path); + request( + client, + service, + reqwest::Method::PUT, + &format!("/repositories/{repo}/files"), + body, + status, + ) + .await +} +async fn repositories( + client: &reqwest::Client, + service: &Service, + query: &str, + status: u16, +) -> Value { + request( + client, + service, + reqwest::Method::GET, + &format!("/repositories{query}"), + Value::Null, + status, + ) + .await +} + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search/vector and CREATEDB"] +async fn malformed_notebook_preserves_published_file_and_revisions() { + let (db, boundary, service, client) = setup().await; + register(&client, &service, "notebook").await; + let valid = json!({"cells":[{"cell_type":"code","source":["print('orchard notebookneedle')"]}],"metadata":{},"nbformat":4,"nbformat_minor":5}).to_string(); + let published = publish( + &client, + &service, + "notebook", + "example.ipynb", + 0, + &valid, + 200, + ) + .await; + let before = repositories(&client, &service, "", 200).await; + for invalid in [ + "{", + "{}", + "{\"cells\":null}", + "{\"cells\":{}}", + "{\"cells\":[{}]}", + "{\"cells\":[{\"cell_type\":\"code\",\"source\":[42]}]}", + ] { + publish( + &client, + &service, + "notebook", + "example.ipynb", + 1, + invalid, + 400, + ) + .await; + let current = request( + &client, + &service, + reqwest::Method::GET, + "/repositories/notebook/file?path=example.ipynb", + Value::Null, + 200, + ) + .await; + assert_eq!( + current, published, + "invalid notebook must preserve all file state" + ); + assert_eq!(repositories(&client, &service, "", 200).await, before); + for mode in ["keyword", "vector", "hybrid"] { + let hits = search( + &client, + &service, + &["notebook"], + "notebookneedle", + mode, + None, + ) + .await; + assert_eq!(hits.len(), 1, "preserve {mode} hit after {invalid}"); + assert_eq!(hits[0]["file_revision"], 1); + assert!(hits[0]["content"] + .as_str() + .unwrap() + .contains("notebookneedle")); + } + } + let empty = publish( + &client, + &service, + "notebook", + "example.ipynb", + 1, + "{\"cells\":[]}", + 200, + ) + .await; + assert_eq!(empty["revision"], 2); + assert_eq!(empty["chunk_count"], 0); + assert_eq!(empty["deleted"], false); + assert_eq!( + repositories(&client, &service, "", 200).await[0]["revision"], + 2 + ); + assert!(search( + &client, + &service, + &["notebook"], + "notebookneedle", + "keyword", + None + ) + .await + .is_empty()); + drop(service); + drop(boundary); + db.cleanup().await; +} + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search/vector and CREATEDB"] +async fn split_source_ranges_are_inclusive_physical_lines() { + let (db, boundary, service, client) = setup().await; + register(&client, &service, "ranges").await; + let body: String = (0..180) + .map(|i| format!(" let value_{i} = {i};\n")) + .collect(); + let source = format!("fn rangeneedle() {{\n{body}}}"); + publish(&client, &service, "ranges", "example.rs", 0, &source, 200).await; + let mut hits = search( + &client, + &service, + &["ranges"], + "rangeneedle", + "keyword", + Some("example.rs"), + ) + .await; + hits.sort_by_key(|hit| hit["start_line"].as_u64().unwrap()); + let ranges: Vec<_> = hits + .iter() + .map(|hit| { + ( + hit["start_line"].as_u64().unwrap(), + hit["end_line"].as_u64().unwrap(), + ) + }) + .collect(); + assert_eq!(ranges, [(1, 80), (71, 150), (141, 182)]); + let text = "orchard ".repeat(1800); + publish(&client, &service, "ranges", "one.txt", 0, &text, 200).await; + let hits = search( + &client, + &service, + &["ranges"], + "orchard", + "keyword", + Some("one.txt"), + ) + .await; + assert!(hits.len() >= 3); + for hit in hits { + assert_eq!( + (hit["start_line"].as_u64(), hit["end_line"].as_u64()), + (Some(1), Some(1)), + "fragment must stay on physical line1" + ); + } + drop(service); + drop(boundary); + db.cleanup().await; +} + +#[tokio::test] +#[ignore = "requires disposable PG18 with pg_search/vector and CREATEDB"] +async fn repository_keyset_pagination_discovers_1001_names_once() { + let (db, boundary, service, client) = setup().await; + for i in 0..1001 { + register(&client, &service, &format!("repo{i:04}")).await; + } + publish(&client, &service, "repo1000", "a.txt", 0, "orchard", 200).await; + let mut names = Vec::new(); + let mut after = String::new(); + for _ in 0..12 { + let page = repositories(&client, &service, &format!("?limit=100&after={after}"), 200).await; + let page = page.as_array().unwrap(); + assert!(page.len() <= 100, "bounded page size"); + if page.is_empty() { + break; + } + for repo in page { + let name = repo["name"].as_str().unwrap(); + assert!(name > after.as_str()); + assert_eq!(repo["revision"], if name == "repo1000" { 1 } else { 0 }); + names.push(name.to_string()); + after = name.to_string(); + } + } + assert_eq!( + names, + (0..1001).map(|i| format!("repo{i:04}")).collect::>() + ); + for query in ["?limit=0", "?limit=1001", "?limit=-1"] { + repositories(&client, &service, query, 400).await; + } + drop(service); + drop(boundary); + db.cleanup().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires disposable PG18 with pg_search/vector and CREATEDB"] +async fn global_cache_inserts_sorted_unique_keys_independent_of_chunk_order() { + let (db, boundary, service, client) = setup().await; + register(&client, &service, "first").await; + register(&client, &service, "second").await; + // A transaction-local trigger deterministically rejects descending or repeated + // unique-key lock attempts. This pins lock ordering without a timing lottery. + db.pool.execute("CREATE FUNCTION cs_check_cache_order() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE previous text; BEGIN previous := current_setting('cs_test.previous_hash',true); IF previous IS NOT NULL AND previous <> '' AND NEW.content_hash <= previous THEN RAISE EXCEPTION 'cache keys not strictly ascending'; END IF; PERFORM set_config('cs_test.previous_hash',NEW.content_hash,true); RETURN NEW; END $$; CREATE TRIGGER cs_check_cache_order BEFORE INSERT ON cs_server_embedding_cache FOR EACH ROW EXECUTE FUNCTION cs_check_cache_order()").await.unwrap(); + let a = "fn cache_alpha() {}"; + let b = "fn cache_beta() {}"; + let documents = |source: &str| { + codesearch_core::chunker::SemanticChunker::new(80, 6000, 10) + .chunk_semantic( + codesearch_core::file::Language::Rust, + std::path::Path::new("same.rs"), + source, + ) + .unwrap() + .iter() + .map(|chunk| crate::document::Document::new(chunk, ModelType::default())) + .collect::>() + }; + let pair = documents(&format!("{a}\n{b}")); + assert_eq!(pair.len(), 2); + let (high, low) = if pair[0].hash > pair[1].hash { + (a, b) + } else { + (b, a) + }; + let descending = format!("{high}\n{low}\n{high}"); + let reversed = format!("{low}\n{high}\n{low}"); + let (first, second) = tokio::join!( + publish(&client, &service, "first", "same.rs", 0, &descending, 200), + publish(&client, &service, "second", "same.rs", 0, &reversed, 200) + ); + assert_eq!(first["chunk_count"], 3); + assert_eq!(second["chunk_count"], 3); + for (repo, source) in [("first", descending), ("second", reversed)] { + let actual: Vec = sqlx::query_scalar("SELECT c.document FROM cs_server_chunks c JOIN cs_server_repositories r ON r.id=c.repo_id WHERE r.name=$1 ORDER BY c.ordinal") + .bind(repo).fetch_all(&db.pool).await.unwrap(); + assert_eq!( + actual, + documents(&source) + .into_iter() + .map(|doc| doc.text) + .collect::>(), + "cache sort must not reorder chunk ordinals" + ); + } + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM cs_server_embedding_cache") + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(count, 2); + let repos = repositories(&client, &service, "", 200).await; + assert!(repos + .as_array() + .unwrap() + .iter() + .all(|repo| repo["revision"] == 1)); + drop(service); + drop(boundary); + db.cleanup().await; +} diff --git a/server/src/store.rs b/server/src/store.rs new file mode 100644 index 00000000..9cd8a974 --- /dev/null +++ b/server/src/store.rs @@ -0,0 +1,377 @@ +use crate::types::fuse; +use crate::{ + document::Document, Embedding, Error, FileState, FileUpdate, Repository, RepositoryInput, + Result, SearchHit, SearchMode, SearchRequest, MAX_CHUNKS, +}; +use anyhow::{bail, Context}; +use codesearch_core::chunker::{Chunk, SemanticChunker}; +use codesearch_core::file::Language; +use pgvector::Vector; +use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode}; +use sqlx::{ConnectOptions, PgPool, Row}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::Path, + str::FromStr, + time::Duration, +}; + +// Core's notebook extractor is deliberately best-effort. Publication must not +// interpret an extraction failure as an intentional empty replacement. Validate +// the fields extraction consumes, not unrelated notebook metadata or outputs. +fn validate_notebook(content: &str) -> Result<()> { + let invalid = || Error::Invalid("invalid notebook cells or source"); + let notebook: serde_json::Value = serde_json::from_str(content).map_err(|_| invalid())?; + let cells = notebook + .get("cells") + .and_then(serde_json::Value::as_array) + .ok_or_else(invalid)?; + if !cells.iter().all(|cell| { + cell.get("cell_type") + .and_then(serde_json::Value::as_str) + .is_some_and(|kind| matches!(kind, "code" | "markdown" | "raw")) + && cell.get("source").is_some_and(|source| { + source.is_string() + || source + .as_array() + .is_some_and(|parts| parts.iter().all(serde_json::Value::is_string)) + }) + }) { + return Err(invalid()); + } + Ok(()) +} + +fn connection_options(url: &str) -> anyhow::Result { + let parsed = url::Url::parse(url).map_err(|_| anyhow::anyhow!("invalid database URL"))?; + let explicit_tls = parsed.query_pairs().any(|(key, _)| key == "sslmode"); + let options = + PgConnectOptions::from_str(url).map_err(|_| anyhow::anyhow!("invalid database URL"))?; + Ok(if explicit_tls { + options + } else { + options.ssl_mode(PgSslMode::VerifyFull) + } + .disable_statement_logging()) +} + +#[cfg(test)] +#[path = "store_tests.rs"] +mod tests; + +#[derive(Clone)] +pub struct Store { + pool: PgPool, + embedding: Embedding, +} +impl Store { + pub async fn connect(url: &str, embedding: Embedding) -> anyhow::Result { + // Do not attach the URL, parser error or database connection error: any + // can contain credentials. SQL statement logging is disabled as well. + let options = connection_options(url)?; + let pool = PgPoolOptions::new() + .max_connections(8) + .acquire_timeout(Duration::from_secs(10)) + .after_connect(|connection, _| { + Box::pin(async move { + sqlx::query("SET statement_timeout = '30s'") + .execute(&mut *connection) + .await?; + sqlx::query("SET idle_in_transaction_session_timeout = '30s'") + .execute(connection) + .await?; + Ok(()) + }) + }) + .connect_with(options) + .await + .map_err(|_| { + anyhow::anyhow!("cannot connect to PostgreSQL; check host, TLS and authentication") + })?; + let store = Self { pool, embedding }; + store.migrate().await.map_err(|error| { + // SQL errors may echo source, roles or connection details. + if error.downcast_ref::().is_some() { + anyhow::anyhow!("PostgreSQL schema initialization failed; verify extensions, schema privileges and database availability") + } else { error } + })?; + Ok(store) + } + async fn migrate(&self) -> anyhow::Result<()> { + let mut tx = self.pool.begin().await?; + // Serialize first-start DDL across server instances, not just within one process. + sqlx::query("SELECT pg_advisory_xact_lock(384002)") + .execute(&mut *tx) + .await?; + let search: Option = + sqlx::query_scalar("SELECT extversion FROM pg_extension WHERE extname = 'pg_search'") + .fetch_optional(&mut *tx) + .await?; + let vector: Option = + sqlx::query_scalar("SELECT extversion FROM pg_extension WHERE extname = 'vector'") + .fetch_optional(&mut *tx) + .await?; + if search.as_deref() != Some("0.27.1") { + bail!("codesearch-server requires pg_search 0.27.1 (with shared_preload_libraries configured); ask the DBA to provision extensions"); + } + let vector = vector.context( + "codesearch-server requires pgvector >=0.8; ask the DBA to CREATE EXTENSION vector", + )?; + let parts: Vec<_> = vector + .split('.') + .map(str::parse::) + .collect::>()?; + if parts.len() < 2 || (parts[0], parts[1]) < (0, 8) { + bail!("codesearch-server requires pgvector >=0.8"); + } + sqlx::query("CREATE TABLE IF NOT EXISTS cs_server_index (singleton boolean PRIMARY KEY CHECK(singleton), schema_version integer NOT NULL, fingerprint text NOT NULL, dimensions integer NOT NULL)").execute(&mut *tx).await?; + sqlx::query("INSERT INTO cs_server_index VALUES (true, 1, $1, $2) ON CONFLICT DO NOTHING") + .bind(&self.embedding.fingerprint) + .bind(self.embedding.dimensions as i32) + .execute(&mut *tx) + .await?; + let row = sqlx::query("SELECT schema_version, fingerprint, dimensions FROM cs_server_index WHERE singleton FOR UPDATE").fetch_one(&mut *tx).await?; + if row.try_get::("schema_version")? != 1 { + bail!("unsupported server database schema version"); + } + if row.try_get::("fingerprint")? != self.embedding.fingerprint + || row.try_get::("dimensions")? != self.embedding.dimensions as i32 + { + bail!("database embedding fingerprint/dimension mismatch; use a separate database and reindex for another embedding strategy"); + } + sqlx::query("CREATE TABLE IF NOT EXISTS cs_server_repositories (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text UNIQUE NOT NULL, description text NOT NULL, revision bigint NOT NULL DEFAULT 0 CHECK(revision >= 0))").execute(&mut *tx).await?; + sqlx::query("CREATE TABLE IF NOT EXISTS cs_server_files (repo_id bigint NOT NULL REFERENCES cs_server_repositories(id), path text NOT NULL, revision bigint NOT NULL CHECK(revision > 0), source_revision text NOT NULL, content_hash text, deleted boolean NOT NULL, chunk_count integer NOT NULL CHECK(chunk_count >= 0), PRIMARY KEY(repo_id,path))").execute(&mut *tx).await?; + // Only a range-checked integer is interpolated; all runtime data is bound. + sqlx::query(&format!("CREATE TABLE IF NOT EXISTS cs_server_chunks (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, repo_id bigint NOT NULL, path text NOT NULL, ordinal integer NOT NULL, content text NOT NULL, document text NOT NULL, start_line integer NOT NULL, end_line integer NOT NULL, file_revision bigint NOT NULL, source_revision text NOT NULL, embedding vector({}) NOT NULL, FOREIGN KEY(repo_id,path) REFERENCES cs_server_files(repo_id,path), UNIQUE(repo_id,path,ordinal))", self.embedding.dimensions)).execute(&mut *tx).await?; + sqlx::query("CREATE INDEX IF NOT EXISTS cs_server_chunks_search ON cs_server_chunks USING paradedb (id, repo_id, (document::pdb.source_code))").execute(&mut *tx).await?; + sqlx::query(&format!("CREATE TABLE IF NOT EXISTS cs_server_embedding_cache (content_hash text PRIMARY KEY, embedding vector({}) NOT NULL)", self.embedding.dimensions)).execute(&mut *tx).await?; + tx.commit().await?; + Ok(()) + } + pub async fn register(&self, input: RepositoryInput) -> Result { + input.validate()?; + let row = sqlx::query_as::<_, Repository>("INSERT INTO cs_server_repositories(name,description) VALUES ($1,$2) ON CONFLICT(name) DO UPDATE SET name=EXCLUDED.name WHERE cs_server_repositories.description=EXCLUDED.description RETURNING name,description,revision") + .bind(&input.name).bind(&input.description).fetch_optional(&self.pool).await?; + row.ok_or(Error::Conflict) + } + pub async fn repositories(&self, after: &str, limit: i64) -> Result> { + if !(1..=1000).contains(&limit) { + return Err(Error::Invalid("repository page limit must be 1 to 1000")); + } + Ok(sqlx::query_as( + "SELECT name,description,revision FROM cs_server_repositories WHERE name>$1 ORDER BY name LIMIT $2", + ) + .bind(after) + .bind(limit) + .fetch_all(&self.pool) + .await?) + } + pub async fn files(&self, name: &str, after: &str, limit: i64) -> Result> { + crate::validate_name(name)?; + if !(1..=1000).contains(&limit) { + return Err(Error::Invalid("file page limit must be 1 to 1000")); + } + let repo = self.repo_id(name).await?; + Ok(sqlx::query_as("SELECT path,revision,source_revision,content_hash,deleted,chunk_count FROM cs_server_files WHERE repo_id=$1 AND path>$2 ORDER BY path LIMIT $3").bind(repo).bind(after).bind(limit).fetch_all(&self.pool).await?) + } + pub async fn file(&self, name: &str, path: &str) -> Result> { + crate::validate_name(name)?; + crate::validate_path(path, false)?; + let repo = self.repo_id(name).await?; + Ok(sqlx::query_as("SELECT path,revision,source_revision,content_hash,deleted,chunk_count FROM cs_server_files WHERE repo_id=$1 AND path=$2").bind(repo).bind(path).fetch_optional(&self.pool).await?) + } + async fn repo_id(&self, name: &str) -> Result { + sqlx::query_scalar("SELECT id FROM cs_server_repositories WHERE name=$1") + .bind(name) + .fetch_optional(&self.pool) + .await? + .ok_or(Error::NotFound) + } + pub async fn update_file(&self, name: &str, update: FileUpdate) -> Result { + crate::validate_name(name)?; + update.validate()?; + let repo = self.repo_id(name).await?; + // Reject already-stale requests before inference; the transaction must + // still recheck after inference to close the concurrent-writer race. + let current = self + .file(name, &update.path) + .await? + .map_or(0, |f| f.revision); + if current != update.expected_revision { + return Err(Error::Conflict); + } + let path = update.path.clone(); + let content = update.content.clone(); + let chunks = tokio::task::spawn_blocking(move || -> Result> { + let Some(content) = content else { + return Ok(Vec::new()); + }; + let language = Language::from_path(Path::new(&path)); + if language == Language::Jupyter { + validate_notebook(&content)?; + } + let mut chunker = SemanticChunker::new(80, 6000, 10); + let chunks = chunker + .chunk_semantic(language, Path::new(&path), &content) + .map_err(|_| Error::Invalid("cannot chunk source file"))?; + if chunks.len() > MAX_CHUNKS { + return Err(Error::Invalid("too many chunks in file")); + } + Ok(chunks) + }) + .await + .map_err(|_| Error::Invalid("chunking failed"))??; + let documents: Vec<_> = chunks + .iter() + .map(|chunk| Document::new(chunk, self.embedding.document_model)) + .collect(); + let mut vectors = Vec::with_capacity(chunks.len()); + let mut misses = Vec::new(); + let mut miss_indices = Vec::new(); + for (index, document) in documents.iter().enumerate() { + let cached: Option = sqlx::query_scalar( + "SELECT embedding FROM cs_server_embedding_cache WHERE content_hash=$1", + ) + .bind(&document.hash) + .fetch_optional(&self.pool) + .await?; + match cached { + Some(vector) => { + let vector = vector.to_vec(); + crate::validate_vector(&vector, self.embedding.dimensions)?; + vectors.push(vector); + } + None => { + vectors.push(Vec::new()); + misses.push(document.text.clone()); + miss_indices.push(index); + } + } + } + if !misses.is_empty() { + let embedded = self.embedding.embed(misses, false).await?; + for (index, vector) in miss_indices.into_iter().zip(embedded) { + vectors[index] = vector; + } + } + let mut tx = self.pool.begin().await?; + // Stable repository row serializes file creation, deletion and CAS. The + // retained file tombstone prevents delete/recreate ABA revision reuse. + sqlx::query("SELECT id FROM cs_server_repositories WHERE id=$1 FOR UPDATE") + .bind(repo) + .fetch_one(&mut *tx) + .await?; + let current: Option = + sqlx::query_scalar("SELECT revision FROM cs_server_files WHERE repo_id=$1 AND path=$2") + .bind(repo) + .bind(&update.path) + .fetch_optional(&mut *tx) + .await?; + if current.unwrap_or(0) != update.expected_revision { + return Err(Error::Conflict); + } + let revision = update.expected_revision + 1; + let hash = update.content.as_deref().map(Chunk::compute_hash); + let state = FileState { + path: update.path.clone(), + revision, + source_revision: update.source_revision.clone(), + content_hash: hash, + deleted: update.content.is_none(), + chunk_count: chunks.len() as i32, + }; + sqlx::query("INSERT INTO cs_server_files(repo_id,path,revision,source_revision,content_hash,deleted,chunk_count) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(repo_id,path) DO UPDATE SET revision=EXCLUDED.revision,source_revision=EXCLUDED.source_revision,content_hash=EXCLUDED.content_hash,deleted=EXCLUDED.deleted,chunk_count=EXCLUDED.chunk_count") + .bind(repo).bind(&state.path).bind(revision).bind(&state.source_revision).bind(&state.content_hash).bind(state.deleted).bind(state.chunk_count).execute(&mut *tx).await?; + sqlx::query("DELETE FROM cs_server_chunks WHERE repo_id=$1 AND path=$2") + .bind(repo) + .bind(&state.path) + .execute(&mut *tx) + .await?; + let vectors: Vec<_> = vectors.into_iter().map(Vector::from).collect(); + for (ordinal, ((chunk, document), vector)) in + chunks.iter().zip(&documents).zip(&vectors).enumerate() + { + sqlx::query("INSERT INTO cs_server_chunks(repo_id,path,ordinal,content,document,start_line,end_line,file_revision,source_revision,embedding) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)") + .bind(repo).bind(&state.path).bind(ordinal as i32).bind(&chunk.content).bind(&document.text).bind(chunk.start_line as i32).bind(chunk.end_line as i32).bind(revision).bind(&state.source_revision).bind(vector).execute(&mut *tx).await?; + } + // Global unique-key locks must be acquired in one order across repositories; + // source chunk order is independent and can be reversed or repeat keys. + let cache: BTreeMap<_, _> = documents + .iter() + .map(|document| &document.hash) + .zip(&vectors) + .collect(); + for (hash, vector) in cache { + sqlx::query("INSERT INTO cs_server_embedding_cache(content_hash,embedding) VALUES ($1,$2) ON CONFLICT DO NOTHING").bind(hash).bind(vector).execute(&mut *tx).await?; + } + sqlx::query("UPDATE cs_server_repositories SET revision=revision+1 WHERE id=$1") + .bind(repo) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(state) + } + pub async fn search(&self, request: SearchRequest) -> Result> { + request.validate()?; + let vector = if request.mode != SearchMode::Keyword { + Some(Vector::from( + self.embedding + .embed(vec![request.query.clone()], true) + .await? + .remove(0), + )) + } else { + None + }; + let mut tx = self.pool.begin().await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY") + .execute(&mut *tx) + .await?; + let names: Vec<_> = request + .repositories + .iter() + .cloned() + .collect::>() + .into_iter() + .collect(); + let ids: Vec = + sqlx::query_scalar("SELECT id FROM cs_server_repositories WHERE name=ANY($1)") + .bind(&names) + .fetch_all(&mut *tx) + .await?; + if ids.len() != names.len() { + return Err(Error::NotFound); + } + let candidates = if request.mode == SearchMode::Hybrid { + (request.limit * 4).min(400) + } else { + request.limit + } as i64; + let keyword = if request.mode != SearchMode::Vector { + // pg_search scoring requires a ParadeDB scan; PostgreSQL's generic + // prepared plan can omit it after repeated executions. Keep bound + // queries but plan this transaction using their actual parameters. + sqlx::query("SET LOCAL plan_cache_mode=force_custom_plan") + .execute(&mut *tx) + .await?; + sqlx::query_as::<_, SearchHit>("SELECT c.id,r.name AS repository,c.path,c.content,c.start_line,c.end_line,c.file_revision,c.source_revision,pdb.score(c.id)::double precision AS score FROM cs_server_chunks c JOIN cs_server_repositories r ON r.id=c.repo_id WHERE c.document ||| $1::text AND c.repo_id=ANY($2::bigint[]) AND ($3::text IS NULL OR left(c.path,length($3))=$3) ORDER BY pdb.score(c.id) DESC,c.id LIMIT $4") + .bind(&request.query).bind(&ids).bind(&request.path_prefix).bind(candidates).fetch_all(&mut *tx).await? + } else { + Vec::new() + }; + // Exact cosine ranking intentionally favors correct bounded scope over + // ANN underfill; no filtered approximate-index completeness claim. + let vector = if let Some(vector) = vector { + sqlx::query_as::<_, SearchHit>("SELECT c.id,r.name AS repository,c.path,c.content,c.start_line,c.end_line,c.file_revision,c.source_revision,1-(c.embedding <=> $1) AS score FROM cs_server_chunks c JOIN cs_server_repositories r ON r.id=c.repo_id WHERE c.repo_id=ANY($2::bigint[]) AND ($3::text IS NULL OR left(c.path,length($3))=$3) ORDER BY c.embedding <=> $1,c.id LIMIT $4") + .bind(vector).bind(&ids).bind(&request.path_prefix).bind(candidates).fetch_all(&mut *tx).await? + } else { + Vec::new() + }; + tx.commit().await?; + Ok(match request.mode { + SearchMode::Keyword => keyword, + SearchMode::Vector => vector, + SearchMode::Hybrid => fuse(keyword, vector, request.limit), + }) + } +} diff --git a/server/src/store_tests.rs b/server/src/store_tests.rs new file mode 100644 index 00000000..2d90c16f --- /dev/null +++ b/server/src/store_tests.rs @@ -0,0 +1,52 @@ +use super::*; + +#[test] +fn tls_verifies_by_default_and_only_explicit_parameter_overrides() { + for url in [ + "postgres://user:password@localhost/db", + "postgres://user:sslmode=disable@localhost/db", + ] { + assert!(matches!( + connection_options(url).unwrap().get_ssl_mode(), + PgSslMode::VerifyFull + )); + } + assert!(matches!( + connection_options("postgres://localhost/db?sslmode=disable") + .unwrap() + .get_ssl_mode(), + PgSslMode::Disable + )); + let error = connection_options("not a url secret-password") + .unwrap_err() + .to_string(); + assert!(!error.contains("secret-password")); +} + +#[test] +fn notebook_validation_distinguishes_empty_from_extraction_failure() { + for valid in [ + r#"{"cells":[]}"#, + r#"{"cells":[{"cell_type":"code","source":"print(1)"}]}"#, + r##"{"cells":[{"cell_type":"markdown","source":["# Title","text"]}]}"##, + r#"{"cells":[{"cell_type":"raw","source":[]}]}"#, + ] { + assert!(validate_notebook(valid).is_ok(), "{valid}"); + } + for invalid in [ + "{", + "null", + "[]", + "{}", + r#"{"cells":null}"#, + r#"{"cells":{}}"#, + r#"{"cells":[null]}"#, + r#"{"cells":[{}]}"#, + r#"{"cells":[{"cell_type":1,"source":[] }]}"#, + r#"{"cells":[{"cell_type":"code","source":null}]}"#, + r#"{"cells":[{"cell_type":"typo","source":[]}]}"#, + r#"{"cells":[{"cell_type":"code","source":["valid",2]}]}"#, + ] { + assert!(validate_notebook(invalid).is_err(), "{invalid}"); + } +} diff --git a/server/src/types.rs b/server/src/types.rs new file mode 100644 index 00000000..b2b0315d --- /dev/null +++ b/server/src/types.rs @@ -0,0 +1,204 @@ +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MAX_FILE_BYTES: usize = 1024 * 1024; +pub const MAX_RESULTS: usize = 100; +pub const MAX_CHUNKS: usize = 2048; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("{0}")] + Invalid(&'static str), + #[error("revision conflict; read current state before retrying")] + Conflict, + #[error("repository not found")] + NotFound, + #[error("embedding provider failed")] + Embedding, + #[error("storage operation failed")] + Storage(#[from] sqlx::Error), +} +pub type Result = std::result::Result; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RepositoryInput { + pub name: String, + pub description: String, +} +impl RepositoryInput { + pub fn validate(&self) -> Result<()> { + validate_name(&self.name)?; + validate_text(&self.description, 2048, true) + } +} +#[derive(Clone, Debug, Deserialize, Serialize, sqlx::FromRow)] +pub struct Repository { + pub name: String, + pub description: String, + pub revision: i64, +} +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct FileUpdate { + pub path: String, + /// Zero means never indexed. Deletions retain a revisioned tombstone. + pub expected_revision: i64, + /// Caller-supplied source identifier, not a repository-wide snapshot claim. + pub source_revision: String, + /// Explicit null deletes the file; omission is rejected, not a delete. + #[serde(deserialize_with = "required_content")] + pub content: Option, +} +fn required_content<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + Option::::deserialize(deserializer) +} +impl FileUpdate { + pub fn validate(&self) -> Result<()> { + validate_path(&self.path, false)?; + if !(0..i64::MAX).contains(&self.expected_revision) { + return Err(Error::Invalid("invalid expected revision")); + } + validate_text(&self.source_revision, 256, false)?; + if let Some(content) = &self.content { + validate_text(content, MAX_FILE_BYTES, true)?; + } + Ok(()) + } +} +#[derive(Clone, Debug, Deserialize, Serialize, sqlx::FromRow)] +pub struct FileState { + pub path: String, + pub revision: i64, + pub source_revision: String, + pub content_hash: Option, + pub deleted: bool, + pub chunk_count: i32, +} +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum SearchMode { + Keyword, + Vector, + Hybrid, +} +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SearchRequest { + pub repositories: Vec, + pub query: String, + pub mode: SearchMode, + pub limit: usize, + pub path_prefix: Option, +} +impl SearchRequest { + pub fn validate(&self) -> Result<()> { + if self.repositories.is_empty() || self.repositories.len() > 32 { + return Err(Error::Invalid("provide 1 to 32 explicit repositories")); + } + for name in &self.repositories { + validate_name(name)?; + } + validate_text(&self.query, 4096, false)?; + if !(1..=MAX_RESULTS).contains(&self.limit) { + return Err(Error::Invalid("limit must be 1 to 100")); + } + if let Some(prefix) = &self.path_prefix { + validate_path(prefix, true)?; + } + Ok(()) + } +} +#[derive(Clone, Debug, Deserialize, Serialize, sqlx::FromRow)] +pub struct SearchHit { + pub id: i64, + pub repository: String, + pub path: String, + pub content: String, + pub start_line: i32, + pub end_line: i32, + pub file_revision: i64, + pub source_revision: String, + pub score: f64, +} + +pub fn validate_name(name: &str) -> Result<()> { + if name.is_empty() + || name.len() > 128 + || !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) + { + return Err(Error::Invalid( + "repository name must be 1 to 128 ASCII letters, digits, hyphens, underscores or dots", + )); + } + Ok(()) +} +fn validate_text(value: &str, max: usize, empty: bool) -> Result<()> { + if value.len() > max || value.contains('\0') || (!empty && value.trim().is_empty()) { + return Err(Error::Invalid("text is empty, too large or contains NUL")); + } + Ok(()) +} +/// The API accepts only canonical, relative slash-separated paths. Rejecting +/// aliases rather than rewriting them keeps CAS keys and prefix scopes identical. +pub fn validate_path(path: &str, prefix: bool) -> Result<()> { + if path.len() > 1024 || path.contains(['\\', ':', '\0']) { + return Err(Error::Invalid("invalid relative path")); + } + let components = if prefix { + path.strip_suffix('/').unwrap_or(path) + } else { + path + }; + if prefix && path.is_empty() { + return Ok(()); + } + if components + .split('/') + .any(|part| part.is_empty() || matches!(part, "." | "..")) + { + return Err(Error::Invalid( + "path must use canonical relative slash-separated components", + )); + } + Ok(()) +} +pub fn validate_vector(vector: &[f32], dimensions: usize) -> Result<()> { + if vector.len() != dimensions + || vector.iter().any(|v| !v.is_finite()) + || vector.iter().all(|v| *v == 0.0) + { + return Err(Error::Embedding); + } + Ok(()) +} + +pub(crate) fn fuse( + keyword: Vec, + vector: Vec, + limit: usize, +) -> Vec { + let mut hits: BTreeMap = BTreeMap::new(); + for list in [keyword, vector] { + for (rank, mut hit) in list.into_iter().enumerate() { + let score = 1.0 / (60.0 + rank as f64 + 1.0); + hits.entry(hit.id) + .and_modify(|h| h.score += score) + .or_insert_with(|| { + hit.score = score; + hit + }); + } + } + let mut hits: Vec<_> = hits.into_values().collect(); + hits.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.id.cmp(&b.id))); + hits.truncate(limit); + hits +} +#[cfg(test)] +#[path = "types_tests.rs"] +mod tests; diff --git a/server/src/types_tests.rs b/server/src/types_tests.rs new file mode 100644 index 00000000..868db84f --- /dev/null +++ b/server/src/types_tests.rs @@ -0,0 +1,92 @@ +use super::*; + +#[test] +fn file_validation_is_nondestructive_and_paths_have_one_spelling() { + for path in [ + "/a", "../a", "a/../b", "a//b", "a\\b", "./a", "a/", "C:/a", "a\0b", + ] { + assert!(validate_path(path, false).is_err(), "accepted {path:?}"); + } + assert!(validate_path("src/main.rs", false).is_ok()); + assert!(validate_path("src/", true).is_ok()); + assert!(validate_path("", true).is_ok()); + for revision in [-1, i64::MAX] { + assert!(FileUpdate { + path: "a.rs".into(), + expected_revision: revision, + source_revision: "abc".into(), + content: None + } + .validate() + .is_err()); + } + let mut update = FileUpdate { + path: "a.rs".into(), + expected_revision: 0, + source_revision: "abc".into(), + content: Some("ok".into()), + }; + assert!(update.validate().is_ok()); + update.content = Some("x".repeat(MAX_FILE_BYTES + 1)); + assert!(update.validate().is_err()); +} + +#[test] +fn retrieval_requires_bounded_explicit_scope() { + let mut search = SearchRequest { + repositories: vec!["example".into()], + query: "needle".into(), + mode: SearchMode::Hybrid, + limit: 10, + path_prefix: None, + }; + assert!(search.validate().is_ok()); + for limit in [0, MAX_RESULTS + 1] { + search.limit = limit; + assert!(search.validate().is_err()); + } + search.limit = 10; + search.repositories.clear(); + assert!(search.validate().is_err()); + search.repositories = vec!["example".into()]; + search.query = " ".into(); + assert!(search.validate().is_err()); +} + +#[test] +fn cosine_vectors_reject_corrupt_and_zero_values() { + for vector in [ + vec![], + vec![0.0, 0.0], + vec![f32::NAN, 1.0], + vec![f32::INFINITY, 1.0], + vec![1.0], + ] { + assert!(validate_vector(&vector, 2).is_err()); + } + assert!(validate_vector(&[1.0, -1.0], 2).is_ok()); +} + +#[test] +fn hybrid_uses_ranks_not_incompatible_scores_and_has_stable_ties() { + let hit = |id, score| SearchHit { + id, + repository: "r".into(), + path: "a".into(), + content: "x".into(), + start_line: 1, + end_line: 1, + file_revision: 1, + source_revision: "s".into(), + score, + }; + let fused = fuse( + vec![hit(2, 900.0), hit(1, 1.0)], + vec![hit(1, 0.99), hit(3, 0.5)], + 3, + ); + assert_eq!( + fused.iter().map(|h| h.id).collect::>(), + vec![1, 2, 3] + ); +}