Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkgs/atlas-search/crates/atlas-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
10 changes: 9 additions & 1 deletion pkgs/atlas-search/crates/atlas-core/src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ pub fn run_search_with_executor(
opts: &SearchOptions,
executor: &dyn BranchPoolExecutor,
) -> Result<Json> {
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"
Expand Down Expand Up @@ -399,7 +405,9 @@ fn entry_chunk_extras(

/// The Python's `neighbor_map`.
fn neighbor_map(backend: &dyn SearchBackend, d: &ChunkDetail, n: usize) -> Result<Json> {
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 {
Expand Down
29 changes: 22 additions & 7 deletions pkgs/atlas-search/crates/atlas-search/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>) -> Result<usize, CliError> {
if v >= min && max.is_none_or(|m| v <= m) {
return Ok(usize::try_from(v).expect("range-checked count converts"));
Expand All @@ -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<String> = None;
// The shard fan-out is standalone-only: the service does not
Expand Down Expand Up @@ -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()
Comment on lines +795 to +802

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept deliberately: Ok(100) and the literal error string pin the bounds ACTUAL value, not just its consistency with the constant. The acceptance criteria for #5593 require the bound justified against the get-chunk 100 cap; if MAX_EXPAND_NEIGHBORS ever changes, this test failing is the intended tripwire that forces re-justification. — repo-worker-code-r

)
);
// 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(),
Expand Down
27 changes: 27 additions & 0 deletions pkgs/atlas-search/crates/atlas-search/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
Expand Down Expand Up @@ -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"),
Comment on lines +2501 to +2502

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept deliberately, same rationale as the CLI test: asserting the literal 100 pins the bound value itself (the #5593 acceptance ties it to the get-chunk cap), so a silent constant change fails here instead of drifting. — repo-worker-code-r

"got: {:?}",
err.body
);
}

#[test]
fn paging_reuses_stored_ranking_and_matches_one_shot() {
let (handle, calls) = start(RuntimeLimits::default(), None);
Expand Down
21 changes: 21 additions & 0 deletions pkgs/atlas-search/crates/atlas-search/tests/cli_parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Comment on lines +160 to +162

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept: the missing.db check is a secondary negative assert only — the primary pins are exit code 2 and the exact --expand message, which cannot be produced by any backend path. The backend-open error including the db path is established behavior relied on by the other parity tests in this file. — repo-worker-code-r

);
}

#[test]
fn cli_get_chunk_matches_python() {
let db = build_fixture_db("getchunk");
Expand Down
Loading