Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(engine,api): TTL-sweep + cap scroll and async-search contexts (RC4 blocker 11)

xerj-org7f70c75f5943
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index b738724f4..5020e1fc3 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -4534,6 +4534,16 @@ pub async fn search(
let is_scroll_request = params.scroll.is_some();
let scroll_page_size = body.size;
if is_scroll_request {
+ // RC4 blocker 11: enforce the open-scroll cap BEFORE running the
+ // search — each context pins a fully-hydrated Vec<Hit>, so an
+ // uncapped open loop is an unauthenticated memory DoS. Expired
+ // contexts are swept opportunistically first so the cap counts
+ // only live contexts.
+ state.engine.sweep_expired_scrolls();
+ let scroll_cap = state.config.search_context.max_open_scrolls;
+ if state.engine.scrolls.len() >= scroll_cap {
+ return too_many_scroll_contexts(scroll_cap);
+ }
// Cap scroll snapshot at 10k hits — matches the default max_result_window.
body.size = 10_000;
body.from = 0;
@@ -9682,12 +9692,27 @@ pub async fn search(
.map(|s| s.to_string())
.unwrap_or_default();
let scroll_id = Uuid::new_v4().to_string();
+ // TTL (RC4 blocker 11): every context expires. `?scroll=1m` is the
+ // keep-alive; unparsable/absent falls back to the configured
+ // default, and everything is capped at the configured max so a
+ // client cannot pin the snapshot for 30 days.
+ let sc_cfg = &state.config.search_context;
+ let keep_alive_secs = params
+ .scroll
+ .as_deref()
+ .and_then(parse_keep_alive_to_secs)
+ .unwrap_or(sc_cfg.scroll_default_keep_alive_secs)
+ .min(sc_cfg.scroll_max_keep_alive_secs);
+ let keep_alive = std::time::Duration::from_secs(keep_alive_secs);
+ let now = Instant::now();
let ctx = xerj_engine::engine::ScrollContext {
index: scroll_index,
hits: snapshot,
position: scroll_page_size,
page_size: scroll_page_size,
- created: Instant::now(),
+ created: now,
+ keep_alive,
+ expires_at: now + keep_alive,
};
state.engine.scrolls.insert(scroll_id.clone(), ctx);
response_body["_scroll_id"] = Value::String(scroll_id);
@@ -12481,7 +12506,11 @@ pub async fn index_stats(
"current": 0,
},
"search": {
- "open_contexts": 0,
+ // Live open-context counts (RC4 blocker 11): scrolls are
+ // engine-global (a context spans indices), reported here so
+ // the TTL sweeper and 429 cap are observable. Previously
+ // hardcoded 0.
+ "open_contexts": state.engine.scrolls.len(),
"query_total": 0,
"query_time_in_millis": 0,
"query_current": 0,
@@ -12490,7 +12519,7 @@ pub async fn index_stats(
"fetch_current": 0,
"scroll_total": 0,
"scroll_time_in_millis": 0,
- "scroll_current": 0,
+ "scroll_current": state.engine.scrolls.len(),
"suggest_total": 0,
"suggest_time_in_millis": 0,
"suggest_current": 0,
@@ -12845,6 +12874,17 @@ pub async fn search_with_scroll(
let started = Instant::now();
let body = body.into_or_default();
+ // RC4 blocker 11: same open-scroll cap as the `?scroll=` path on
+ // `_search` — checked up front so the full-corpus snapshot below is
+ // never even computed for a request that cannot get a context.
+ if params.scroll.is_some() {
+ state.engine.sweep_expired_scrolls();
+ let scroll_cap = state.config.search_context.max_open_scrolls;
+ if state.engine.scrolls.len() >= scroll_cap {
+ return too_many_scroll_contexts(scroll_cap);
+ }
+ }
+
// Resolve aliases and expand comma-separated indices.
let index_names: Vec<String> = index
.split(',')
@@ -12969,12 +13009,24 @@ pub async fn search_with_scroll(
})
.collect();
+ // TTL (RC4 blocker 11) — mirrors the `_search?scroll=` site.
+ let sc_cfg = &state.config.search_context;
+ let keep_alive_secs = params
+ .scroll
+ .as_deref()
+ .and_then(parse_keep_alive_to_secs)
+ .unwrap_or(sc_cfg.scroll_default_keep_alive_secs)
+ .min(sc_cfg.scroll_max_keep_alive_secs);
+ let keep_alive = std::time::Duration::from_secs(keep_alive_secs);
+ let now = Instant::now();
let ctx = xerj_engine::engine::ScrollContext {
index: index.clone(),
hits: hits_only,
position: page_size,
page_size,
- created: Instant::now(),
+ created: now,
+ keep_alive,
+ expires_at: now + keep_alive,
};
state.engine.scrolls.insert(scroll_id.clone(), ctx);
@@ -13094,6 +13146,34 @@ pub async fn next_scroll(
match state.engine.scrolls.get_mut(&scroll_id) {
Some(mut ctx) => {
+ // Keep-alive enforcement (RC4 blocker 11): an expired context
+ // is gone even if the background sweeper hasn't collected it
+ // yet — same 404 as an unknown id, matching ES.
+ let now = Instant::now();
+ if ctx.expires_at <= now {
+ drop(ctx); // release the DashMap shard guard before remove
+ state.engine.scrolls.remove(&scroll_id);
+ let e = xerj_common::XerjError::index_not_found(format!(
+ "No search context found for id [{scroll_id}]"
+ ));
+ return ApiError::new(e).into_response();
+ }
+ // Re-arm the deadline: an explicit `scroll` on the continuation
+ // (body wins over query param, like scroll_id) sets a new
+ // keep-alive (capped); absent → the previous keep-alive window
+ // restarts from now, matching ES.
+ if let Some(ka_secs) = body
+ .scroll
+ .as_deref()
+ .or(params.scroll.as_deref())
+ .and_then(parse_keep_alive_to_secs)
+ {
+ let capped =
+ ka_secs.min(state.config.search_context.scroll_max_keep_alive_secs);
+ ctx.keep_alive = std::time::Duration::from_secs(capped);
+ }
+ ctx.expires_at = now + ctx.keep_alive;
+
let page_size = ctx.page_size.max(1);
let position = ctx.position;
let total = ctx.hits.len() as u64;
@@ -22449,9 +22529,24 @@ pub(crate) fn build_inner_hits(
// DELETE /_async_search/{id} — delete stored result
// ─────────────────────────────────────────────────────────────────────────────
+/// Query params for `_async_search` submit/get. Only `keep_alive` changes
+/// behavior (result TTL); `wait_for_completion_timeout` and
+/// `keep_on_completion` are accepted for wire compatibility — searches run
+/// synchronously here, so every response is already complete.
+#[derive(Debug, Default, Deserialize)]
+pub struct AsyncSearchParams {
+ #[serde(default)]
+ pub keep_alive: Option<String>,
+ #[serde(default)]
+ pub wait_for_completion_timeout: Option<String>,
+ #[serde(default)]
+ pub keep_on_completion: Option<String>,
+}
+
pub async fn async_search_submit(
State(state): State<AppState>,
Path(index): Path<String>,
+ Query(params): Query<AsyncSearchParams>,
body: OptionalJson<EsSearchBody>,
) -> impl IntoResponse {
let mut body = body.into_or_default();
@@ -22461,6 +22556,15 @@ pub async fn async_search_submit(
body.track_total_hits = Some(json!(10_000));
}
+ // RC4 blocker 11: stored async results are TTL'd AND capped. Sweep
+ // expired entries first so the cap counts only live results, then
+ // refuse (429) rather than pinning yet another response JSON forever.
+ state.engine.sweep_expired_async_searches();
+ let async_cap = state.config.search_context.max_open_async_searches;
+ if state.engine.async_searches.len() >= async_cap {
+ return too_many_async_searches(async_cap);
+ }
+
let idx = match state.engine.get_or_create_index(&index) {
Ok(i) => i,
Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),
@@ -22479,8 +22583,19 @@ pub async fn async_search_submit(
};
let took_ms = started.elapsed().as_millis() as u64;
+ // TTL (RC4 blocker 11): honor the request's `keep_alive` (pre-rc.4 it
+ // was parsed nowhere and every result silently got 5 minutes), fall
+ // back to the configured default, cap at the configured max. The
+ // expiry is enforced on GET and by the background sweeper.
+ let sc_cfg = &state.config.search_context;
+ let keep_alive_secs = params
+ .keep_alive
+ .as_deref()
+ .and_then(parse_keep_alive_to_secs)
+ .unwrap_or(sc_cfg.async_default_keep_alive_secs)
+ .min(sc_cfg.async_max_keep_alive_secs);
let now_ms = chrono::Utc::now().timestamp_millis();
- let exp_ms = now_ms + 5 * 60 * 1000; // 5 minute expiry
+ let exp_ms = now_ms + (keep_alive_secs as i64) * 1000;
// Build a normal search response body to embed.
let max_score = result.hits.first().map(|h| h.score as f64);
@@ -22538,9 +22653,36 @@ pub async fn async_search_submit(
pub async fn async_search_get(
State(state): State<AppState>,
Path(id): Path<String>,
+ Query(params): Query<AsyncSearchParams>,
) -> impl IntoResponse {
- match state.engine.async_searches.get(&id) {
- Some(result) => Json(result.clone()).into_response(),
+ let now_ms = chrono::Utc::now().timestamp_millis();
+ match state.engine.async_searches.get_mut(&id) {
+ Some(mut entry) => {
+ // Expiry enforcement on read (RC4 blocker 11): a result past
+ // its keep-alive is gone even before the sweeper collects it.
+ let expired = entry
+ .get("expiration_time_in_millis")
+ .and_then(Value::as_i64)
+ .map(|exp| exp <= now_ms)
+ .unwrap_or(true);
+ if expired {
+ drop(entry); // release the DashMap shard guard before remove
+ state.engine.async_searches.remove(&id);
+ return async_search_not_found(&id);
+ }
+ // `GET …?keep_alive=…` extends the stored result's TTL (ES
+ // semantics), capped like submit.
+ if let Some(ka_secs) = params
+ .keep_alive
+ .as_deref()
+ .and_then(parse_keep_alive_to_secs)
+ {
+ let capped =
+ ka_secs.min(state.config.search_context.async_max_keep_alive_secs);
+ entry["expiration_time_in_millis"] = json!(now_ms + (capped as i64) * 1000);
+ }
+ Json(entry.clone()).into_response()
+ }
// Unknown id → ES returns 404 resource_not_found, not a 500.
None => async_search_not_found(&id),
}
@@ -22556,6 +22698,49 @@ pub async fn async_search_delete(
}
}
+/// ES-shaped 429 for exceeding the open-scroll-contexts cap (RC4
+/// blocker 11). Mirrors ES's `search.max_open_scroll_context` rejection
+/// text, naming xerj's own setting key.
+fn too_many_scroll_contexts(cap: usize) -> axum::response::Response {
+ let reason = format!(
+ "Trying to create too many scroll contexts. Must be less than or equal to: [{cap}]. \
+ This limit can be set by changing the [search_context.max_open_scrolls] setting."
+ );
+ (
+ StatusCode::TOO_MANY_REQUESTS,
+ Json(json!({
+ "error": {
+ "root_cause": [{ "type": "exception", "reason": reason }],
+ "type": "exception",
+ "reason": reason,
+ },
+ "status": 429,
+ })),
+ )
+ .into_response()
+}
+
+/// ES-shaped 429 for exceeding the stored-async-search cap (RC4 blocker 11).
+fn too_many_async_searches(cap: usize) -> axum::response::Response {
+ let reason = format!(
+ "Trying to store too many async searches. Must be less than or equal to: [{cap}]. \
+ This limit can be set by changing the [search_context.max_open_async_searches] \
+ setting, or free slots with DELETE /_async_search/<id>."
+ );
+ (
+ StatusCode::TOO_MANY_REQUESTS,
+ Json(json!({
+ "error": {
+ "root_cause": [{ "type": "exception", "reason": reason }],
+ "type": "exception",
+ "reason": reason,
+ },
+ "status": 429,
+ })),
+ )
+ .into_response()
+}
+
/// ES-shaped 404 for an unknown async-search id.
fn async_search_not_found(id: &str) -> axum::response::Response {
let reason = format!("no async search found for id [{id}]");
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index c7111ef20..e955126ed 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -76,6 +76,8 @@ pub struct Config {
pub cluster: ClusterConfig,
/// Point-in-time TTL + sweep cadence — 3 settings.
pub pit: PitConfig,
+ /// Scroll + async-search context TTLs and open-context caps — 7 settings.
+ pub search_context: SearchContextConfig,
}
// Total: 5+2+3+10+5+3+1+6+2+4+3+4+3 = 51 fields
@@ -925,6 +927,60 @@ impl Default for PitConfig {
}
}
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Scroll + async-search context lifecycle settings (RC4 blocker 11).
+///
+/// **7 settings.**
+///
+/// Every open scroll context pins a fully-hydrated `Vec<Hit>` snapshot and
+/// every stored async-search result pins its response JSON. Before v1.0.0-rc.4
+/// neither was ever expired or capped — an unauthenticated client that opened
+/// scrolls in a loop (or simply never called DELETE /_search/scroll) grew the
+/// process RSS without bound. These settings mirror the PIT lifecycle: a TTL
+/// on every context (refreshed by the `scroll`/`keep_alive` parameters), a
+/// background sweeper, and a hard cap on concurrently-open contexts (requests
+/// beyond the cap get 429, like ES's `search.max_open_scroll_context`).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct SearchContextConfig {
+ /// Default scroll TTL when `?scroll=…` carries no parsable duration
+ /// (default: 60 seconds). ES requires the duration; we degrade to this
+ /// default rather than 400.
+ pub scroll_default_keep_alive_secs: u64,
+ /// Hard cap on any scroll keep-alive (default: 86 400 = 24 h — mirrors
+ /// ES `search.max_keep_alive`). Larger requests are capped silently.
+ pub scroll_max_keep_alive_secs: u64,
+ /// Maximum concurrently-open scroll contexts (default: 500 — mirrors
+ /// ES `search.max_open_scroll_context`). Opening more returns 429.
+ pub max_open_scrolls: usize,
+ /// Default async-search result TTL when the submit request carries no
+ /// `keep_alive` (default: 300 seconds, the pre-rc.4 hardcoded expiry).
+ pub async_default_keep_alive_secs: u64,
+ /// Hard cap on any async-search `keep_alive` (default: 86 400 = 24 h).
+ pub async_max_keep_alive_secs: u64,
+ /// Maximum concurrently-stored async-search results (default: 500).
+ /// Submitting more returns 429.
+ pub max_open_async_searches: usize,
+ /// How often the background sweeper drops expired scroll and
+ /// async-search contexts (default: 30 seconds).
+ pub sweep_interval_secs: u64,
+}
+
+impl Default for SearchContextConfig {
+ fn default() -> Self {
+ Self {
+ scroll_default_keep_alive_secs: 60,
+ scroll_max_keep_alive_secs: 86_400,
+ max_open_scrolls: 500,
+ async_default_keep_alive_secs: 300,
+ async_max_keep_alive_secs: 86_400,
+ max_open_async_searches: 500,
+ sweep_interval_secs: 30,
+ }
+ }
+}
+
// ═════════════════════════════════════════════════════════════════════════════
// Tests
// ═════════════════════════════════════════════════════════════════════════════
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 46a285761..6dd36b0b6 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -94,12 +94,29 @@ pub struct IndexTemplate {
}
/// Active scroll context holding all matching hits.
+///
+/// Each context pins a fully-hydrated `Vec<Hit>` snapshot, so its lifetime
+/// must be bounded: pre-rc.4 contexts lived until an explicit
+/// `DELETE /_search/scroll` and accumulated forever otherwise (RC4
+/// blocker 11). Every context now carries an `expires_at` deadline
+/// (from the request's `scroll=…` keep-alive, capped by
+/// `Config.search_context.scroll_max_keep_alive_secs`), refreshed on each
+/// continuation, enforced on access, and swept in the background.
pub struct ScrollContext {
pub index: String,
pub hits: Vec<xerj_query::executor::Hit>,
pub position: usize,
pub page_size: usize,
pub created: Instant,
+ /// The keep-alive window last requested for this context. A
+ /// continuation without an explicit `scroll` parameter re-arms the
+ /// deadline with this same duration (ES keeps the context alive for
+ /// the previous keep-alive in that case).
+ pub keep_alive: std::time::Duration,
+ /// Wall-clock deadline after which the context is dead: continuations
+ /// return the same 404 as an unknown id, and the background sweeper
+ /// (or an opportunistic sweep on open) frees the pinned hits.
+ pub expires_at: Instant,
}
/// Point-in-time search context — snapshots the set of indices and the
@@ -384,6 +401,14 @@ impl Engine {
// Instant compare) and bounded by the live PIT count.
engine.spawn_pit_sweeper();
+ // Spawn the scroll + async-search context sweeper (RC4 blocker
+ // 11) — the scroll/async twin of the PIT sweeper above. Each
+ // scroll pins a full Vec<Hit> and each async search pins its
+ // response JSON; without a sweeper both maps grow until an
+ // explicit client DELETE, i.e. forever under normal client
+ // behavior.
+ engine.spawn_search_context_sweeper();
+
Ok(engine)
}
@@ -491,6 +516,112 @@ impl Engine {
});
}
+ /// Drop scroll contexts whose `expires_at` is in the past. Mirrors
+ /// [`Engine::sweep_expired_pits`]: cheap O(N) walk, run by the
+ /// background sweeper and opportunistically before opening a new
+ /// scroll so a tight open-without-clear loop self-bounds.
+ pub fn sweep_expired_scrolls(&self) -> usize {
+ let now = Instant::now();
+ let expired: Vec<String> = self
+ .scrolls
+ .iter()
+ .filter(|e| e.value().expires_at <= now)
+ .map(|e| e.key().clone())
+ .collect();
+ for id in &expired {
+ self.scrolls.remove(id);
+ }
+ expired.len()
+ }
+
+ /// Drop stored async-search results whose `expiration_time_in_millis`
+ /// is in the past. The expiry lives inside the stored response JSON
+ /// (it is part of the ES wire format), so the sweep reads it from
+ /// there; a malformed/missing field counts as expired — every writer
+ /// sets it, so that arm only fires on corruption.
+ pub fn sweep_expired_async_searches(&self) -> usize {
+ let now_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or(i64::MAX);
+ let expired: Vec<String> = self
+ .async_searches
+ .iter()
+ .filter(|e| {
+ e.value()
+ .get("expiration_time_in_millis")
+ .and_then(Value::as_i64)
+ .map(|exp| exp <= now_ms)
+ .unwrap_or(true)
+ })
+ .map(|e| e.key().clone())
+ .collect();
+ for id in &expired {
+ self.async_searches.remove(id);
+ }
+ expired.len()
+ }
+
+ /// Background sweeper for scroll + async-search contexts (RC4
+ /// blocker 11) — the twin of [`Engine::spawn_pit_sweeper`].
+ ///
+ /// Deliberately captures ONLY the two context maps (never a full
+ /// `Engine` clone): the engine holds the data-dir `node.lock`, and a
+ /// long-lived task owning an `Engine` clone would keep that lock
+ /// alive after the last user-visible engine is dropped.
+ fn spawn_search_context_sweeper(&self) {
+ let scrolls = Arc::clone(&self.scrolls);
+ let async_searches = Arc::clone(&self.async_searches);
+ let interval = std::time::Duration::from_secs(
+ self.config.search_context.sweep_interval_secs.max(1),
+ );
+ tokio::spawn(async move {
+ let mut tick = tokio::time::interval(interval);
+ // Skip the immediate first tick — Engine::new just ran, so
+ // both maps are empty.
+ tick.tick().await;
+ loop {
+ tick.tick().await;
+ let now = Instant::now();
+ let expired_scrolls: Vec<String> = scrolls
+ .iter()
+ .filter(|e| e.value().expires_at <= now)
+ .map(|e| e.key().clone())
+ .collect();
+ for id in &expired_scrolls {
+ scrolls.remove(id);
+ }
+ let now_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or(i64::MAX);
+ let expired_async: Vec<String> = async_searches
+ .iter()
+ .filter(|e| {
+ e.value()
+ .get("expiration_time_in_millis")
+ .and_then(Value::as_i64)
+ .map(|exp| exp <= now_ms)
+ .unwrap_or(true)
+ })
+ .map(|e| e.key().clone())
+ .collect();
+ for id in &expired_async {
+ async_searches.remove(id);
+ }
+ if !expired_scrolls.is_empty() || !expired_async.is_empty() {
+ tracing::debug!(
+ swept_scrolls = expired_scrolls.len(),
+ swept_async = expired_async.len(),
+ remaining_scrolls = scrolls.len(),
+ remaining_async = async_searches.len(),
+ "search-context sweep dropped expired contexts",
+ );
+ }
+ }
+ });
+ }
+
/// Create a new index, applying any matching index template.
pub fn create_index(&self, name: &str, schema: Schema) -> Result<()> {
let index_name = IndexName::new(name).map_err(EngineError::Common)?;
diff --git a/engine/crates/xerj-engine/tests/search_context_ttl.rs b/engine/crates/xerj-engine/tests/search_context_ttl.rs
new file mode 100644
index 000000000..d9cbefad2
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/search_context_ttl.rs
@@ -0,0 +1,89 @@
+//! RC4 blocker 11 regression: scroll + async-search contexts are TTL-swept.
+//!
+//! Before the fix, `Engine.scrolls` (each entry pinning a fully-hydrated
+//! `Vec<Hit>`) and `Engine.async_searches` (each entry pinning a stored
+//! response JSON) were only ever removed by an explicit client DELETE —
+//! normal client behavior (open scrolls, never clear) grew both maps, and
+//! therefore process RSS, without bound. The engine now mirrors the PIT
+//! lifecycle: TTLs on every context, sweep helpers (run opportunistically
+//! on open + by a background task), expiry enforced on access, and a hard
+//! open-context cap at the API layer.
+
+use std::time::{Duration, Instant};
+
+use serde_json::json;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_engine::engine::ScrollContext;
+use xerj_engine::Engine;
+
+fn make_engine(dir: &TempDir) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ Engine::new(config).expect("engine::new")
+}
+
+fn scroll_ctx(expires_in: i64) -> ScrollContext {
+ let now = Instant::now();
+ let keep_alive = Duration::from_secs(60);
+ let expires_at = if expires_in >= 0 {
+ now + Duration::from_secs(expires_in as u64)
+ } else {
+ now - Duration::from_secs((-expires_in) as u64)
+ };
+ ScrollContext {
+ index: "idx".to_string(),
+ hits: Vec::new(),
+ position: 0,
+ page_size: 10,
+ created: now,
+ keep_alive,
+ expires_at,
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn expired_scroll_contexts_are_swept() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ engine.scrolls.insert("dead".into(), scroll_ctx(-5));
+ engine.scrolls.insert("live".into(), scroll_ctx(3600));
+
+ let swept = engine.sweep_expired_scrolls();
+ assert_eq!(swept, 1, "exactly the expired context is swept");
+ assert!(engine.scrolls.get("dead").is_none(), "expired ctx freed");
+ assert!(engine.scrolls.get("live").is_some(), "live ctx kept");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn expired_async_search_results_are_swept() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+
+ let now_ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as i64;
+
+ engine.async_searches.insert(
+ "dead".into(),
+ json!({ "id": "dead", "expiration_time_in_millis": now_ms - 1000 }),
+ );
+ engine.async_searches.insert(
+ "live".into(),
+ json!({ "id": "live", "expiration_time_in_millis": now_ms + 3_600_000 }),
+ );
+ // Defensive arm: an entry with no expiry field counts as expired —
+ // every writer sets the field, so this only fires on corruption, and
+ // "reclaim" beats "pin forever" there.
+ engine
+ .async_searches
+ .insert("malformed".into(), json!({ "id": "malformed" }));
+
+ let swept = engine.sweep_expired_async_searches();
+ assert_eq!(swept, 2, "expired + malformed swept, live kept");
+ assert!(engine.async_searches.get("dead").is_none());
+ assert!(engine.async_searches.get("malformed").is_none());
+ assert!(engine.async_searches.get("live").is_some());
+}