From ab0ac127e961c082c17fc8086ef8955ecfbd0c8a Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:20:40 -0600 Subject: [PATCH] fix(atlas-search): cap search neighbor expansion --- .../atlas-search/crates/atlas-core/src/lib.rs | 4 +++ .../crates/atlas-core/src/search.rs | 10 ++++++- .../crates/atlas-search/src/main.rs | 29 ++++++++++++++----- .../crates/atlas-search/src/server.rs | 27 +++++++++++++++++ .../crates/atlas-search/tests/cli_parity.rs | 21 ++++++++++++++ 5 files changed, 83 insertions(+), 8 deletions(-) diff --git a/pkgs/atlas-search/crates/atlas-core/src/lib.rs b/pkgs/atlas-search/crates/atlas-core/src/lib.rs index 89ffc1deff..b11710b6af 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/lib.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/lib.rs @@ -38,6 +38,10 @@ pub mod shards; pub mod turso; pub mod types; +/// Maximum neighbor chunks search expansion may attach to each result. +/// Keep this aligned with the service's get-chunk neighbors ceiling. +pub const MAX_EXPAND_NEIGHBORS: usize = 100; + pub use backend::SearchBackend; pub use embed::{AtlasEmbedder, FixedEmbedder, QUERY_PROMPT, QueryEmbedder}; pub use error::{Error, Result}; diff --git a/pkgs/atlas-search/crates/atlas-core/src/search.rs b/pkgs/atlas-search/crates/atlas-core/src/search.rs index de50672cb9..9222c880fd 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/search.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/search.rs @@ -162,6 +162,12 @@ pub fn run_search_with_executor( opts: &SearchOptions, executor: &dyn BranchPoolExecutor, ) -> Result { + if opts.expand > crate::MAX_EXPAND_NEIGHBORS { + return Err(Error::fatal(format!( + "expand must be at most {}", + crate::MAX_EXPAND_NEIGHBORS + ))); + } if opts.mode.uses_vector() && opts.vector_backend != VectorBackend::Scan && backend.name() != "turso" @@ -399,7 +405,9 @@ fn entry_chunk_extras( /// The Python's `neighbor_map`. fn neighbor_map(backend: &dyn SearchBackend, d: &ChunkDetail, n: usize) -> Result { - let rows = backend.neighbors(&d.message_id, d.chunk_idx, n as i64)?; + let n = i64::try_from(n) + .map_err(|_| Error::fatal("neighbor count does not fit in the backend's signed range"))?; + let rows = backend.neighbors(&d.message_id, d.chunk_idx, n)?; let mut before = Vec::new(); let mut after = Vec::new(); for r in &rows { diff --git a/pkgs/atlas-search/crates/atlas-search/src/main.rs b/pkgs/atlas-search/crates/atlas-search/src/main.rs index ee6951c633..0ef4a6b664 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/main.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/main.rs @@ -583,11 +583,11 @@ fn u(v: i64) -> usize { /// Validate one CLI count flag against the service's request /// contract (design section 2; `validate_request` in server.rs): -/// `--k` at least 1, `--pool` between 1 and 400, and the -/// zero-is-valid counts (`--expand`, `--trunc`, `--neighbors`) are -/// non-negative; `--neighbors` is also capped at the service's limit. -/// Out-of-range values are fatal (exit 2), never silently clamped to 0 -/// (#5407). +/// `--k` at least 1, `--pool` between 1 and 400, `--expand` between +/// 0 and `MAX_EXPAND_NEIGHBORS`, `--neighbors` also capped at the +/// service's limit, and the other zero-is-valid counts (`--trunc`) +/// non-negative. Out-of-range values are fatal (exit 2), never a +/// silent clamp to 0 (#5407). fn count(flag: &str, v: i64, min: i64, max: Option) -> Result { if v >= min && max.is_none_or(|m| v <= m) { return Ok(usize::try_from(v).expect("range-checked count converts")); @@ -611,7 +611,12 @@ fn cmd_search(args: SearchArgs) -> Result<(), CliError> { // count fails identically whether or not a service is running. let k = count("--k", args.k, 1, None)?; let pool = count("--pool", args.pool, 1, Some(400))?; - let expand = count("--expand", args.expand, 0, None)?; + let expand = count( + "--expand", + args.expand, + 0, + Some(i64::try_from(atlas_core::MAX_EXPAND_NEIGHBORS).expect("neighbor cap fits in i64")), + )?; let trunc = count("--trunc", args.vector.trunc, 0, None)?; let mut note: Option = None; // The shard fan-out is standalone-only: the service does not @@ -787,8 +792,18 @@ mod tests { ); assert!(count("--pool", 0, 1, Some(400)).is_err()); assert!(count("--pool", -5, 1, Some(400)).is_err()); + // --expand shares the service's 100-neighbor ceiling. + let max_expand = atlas_core::MAX_EXPAND_NEIGHBORS as i64; + assert_eq!(count("--expand", max_expand, 0, Some(max_expand)), Ok(100)); + assert_eq!( + count("--expand", max_expand + 1, 0, Some(max_expand)).unwrap_err(), + ( + 2, + "--expand must be between 0 and 100 (design section 2)".to_string() + ) + ); // zero-is-valid counts: 0 stays valid, negatives do not - for flag in ["--expand", "--trunc"] { + for flag in ["--trunc"] { assert_eq!(count(flag, 0, 0, None), Ok(0), "{flag}"); assert_eq!( count(flag, -1, 0, None).unwrap_err(), diff --git a/pkgs/atlas-search/crates/atlas-search/src/server.rs b/pkgs/atlas-search/crates/atlas-search/src/server.rs index 4f517541ac..57730731e5 100644 --- a/pkgs/atlas-search/crates/atlas-search/src/server.rs +++ b/pkgs/atlas-search/crates/atlas-search/src/server.rs @@ -523,6 +523,15 @@ fn validate_request(req: &SearchRequest) -> Result<(), ServerError> { "pool must be between 1 and 400 (design section 2)", )); } + if req.expand > atlas_core::MAX_EXPAND_NEIGHBORS { + return Err(ServerError::bad_request(format!( + "expand must be at most {}", + atlas_core::MAX_EXPAND_NEIGHBORS + ))); + } + // Deliberately leave k unbounded: it truncates the candidates produced by + // the bounded pool, and grouped search caps its consideration window to + // the available candidates in atlas-core. if req.k == 0 { return Err(ServerError::bad_request("k must be at least 1")); } @@ -2478,6 +2487,24 @@ mod tests { // ----- tests -------------------------------------------------------- + #[test] + fn expand_validation_matches_the_core_neighbor_limit() { + let mut req = SearchRequest { + expand: atlas_core::MAX_EXPAND_NEIGHBORS, + ..SearchRequest::default() + }; + assert!(validate_request(&req).is_ok()); + + req.expand = atlas_core::MAX_EXPAND_NEIGHBORS + 1; + let err = validate_request(&req).unwrap_err(); + assert_eq!(err.status, 400); + assert!( + err.body.error.message.contains("100"), + "got: {:?}", + err.body + ); + } + #[test] fn paging_reuses_stored_ranking_and_matches_one_shot() { let (handle, calls) = start(RuntimeLimits::default(), None); diff --git a/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs b/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs index ee161267c4..4fd6b3621b 100644 --- a/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs +++ b/pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs @@ -142,6 +142,27 @@ fn cli_search_envelopes_match_python() { } } +#[test] +fn cli_rejects_expand_above_limit_before_backend_work() { + let db = std::env::temp_dir() + .join(format!("atlas-cli-parity-{}-missing", std::process::id())) + .join("missing.db"); + let out = run_bin( + &db, + &["search", "query", "--backend", "local", "--expand", "101"], + ); + assert_eq!(out.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("--expand must be between 0 and 100"), + "{stderr}" + ); + assert!( + !stderr.contains("missing.db"), + "backend was reached: {stderr}" + ); +} + #[test] fn cli_get_chunk_matches_python() { let db = build_fixture_db("getchunk");