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): cold-segment hydration must not queue on tokio's blocking pool (#751) (#899)

xerj-org8f4de3ee11a6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 73f03f637..d44c25e0f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -291,11 +291,11 @@ jobs:
build-test:
name: Build + Test
runs-on: ubuntu-latest
- # #751's second-order damage is the whole job hanging against GitHub's 6h
+ # #751's second-order damage was the whole job hanging against GitHub's 6h
# default while main's `cancel-in-progress: false` never auto-cancels — main
- # then sits ~4h with no CI verdict. The step-6 `timeout-minutes: 12` below
- # bounds the one documented hang (step 6, default parallelism) precisely and
- # fast. This job-level cap is defense-in-depth: it bounds ANY hang in the job
+ # then sat ~4h with no CI verdict. #751's root cause is fixed (see the step-6
+ # comment below); the step-6 `timeout-minutes: 12` stays as the precise, fast
+ # bound on any recurrence. This job-level cap is defense-in-depth: it bounds ANY hang in the job
# (setup, cache, a future test race the step timeout would not cover) to
# 60 min instead of the 6h default. It is deliberately generous because
# step 5 (build + threads=2 tests) can legitimately take ~36 min on a loaded
@@ -304,8 +304,8 @@ jobs:
# slow-but-healthy runs. #770 measured the legitimate worst case at ~43-46 min
# against the old 50-min cap (setup + ~36-min step 5 + ~2.3-min step 6 +
# cache-save) — too thin a margin on a loaded runner — so this was bumped to
- # 60 min. Neither cap fixes the root race (#751 stays open for the bisect +
- # port/fixture serialisation).
+ # 60 min. Neither cap is what fixed #751 — the engine deadlock was; they
+ # bound the blast radius of the next one.
timeout-minutes: 60
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
@@ -376,14 +376,21 @@ jobs:
#
# Reuses the binaries the step above already built: the added cost is test
# runtime, not another compile.
- # #751: this step intermittently hangs on the 2-4 vCPU hosted runner (a
- # port/fixture race at low thread count — normal ~2.3 min, observed hanging
- # 18-28 min). Because main's `cancel-in-progress: false` never auto-cancels,
- # a hang leaves the whole run stuck for hours with no completed signal, so
- # main commits never get a CI verdict. Bound it: a hang now fails the step
- # in 12 min (5x normal, well under the observed hangs) so the run completes
- # and `gh run rerun --failed` can recover. This does NOT fix the root race —
- # #751 stays open for the bisect + port/fixture serialisation.
+ # #751: this step used to hang intermittently on the 2-4 vCPU hosted runner
+ # (normal ~2.3 min, observed hanging 18-28 min). It was NOT a port or a
+ # shared fixture — it was a tokio blocking-pool self-deadlock in the engine:
+ # `Index::search` parks a blocking-pool thread inside `block_in_place` for
+ # the whole search, and the aggregation-corpus segment hydration then queued
+ # its decode onto that same pool. Root-caused and fixed in the engine
+ # (`Index::stored_values_for_async` now decodes on the engine's own rayon
+ # maintenance pool); pinned by
+ # `xerj-engine/tests/agg_corpus_hydration_deadlock.rs`.
+ #
+ # The 12-minute cap stays as defense in depth: main's
+ # `cancel-in-progress: false` never auto-cancels, so ANY future hang here
+ # would otherwise leave the run stuck for hours with no verdict. A hang
+ # fails the step in 12 min (5x normal) so the run completes and
+ # `gh run rerun --failed` can recover.
- name: Workspace tests (all targets) at default parallelism (contributor's `cargo test`)
timeout-minutes: 12
working-directory: engine
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 367f00a84..55ca0aeb4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,46 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **CI's default-parallelism test step no longer races itself for a port**
+ ([#751](https://github.com/xerj-org/xerj/issues/751), the second half). With
+ the deadlock above fixed, the same step then failed on a real port race that
+ the hang had been masking: `xerj-server`'s cleartext-bind tests allocated a
+ port by binding `127.0.0.1:0`, reading the number, releasing it, and handing
+ it to a child process that binds it later. The kernel is free to hand that
+ same ephemeral port to the next `bind(":0")`, and several tests in that file
+ keep a real server alive for seconds, so at default parallelism they
+ overlapped — `gRPC: bind [::1]:46843 ... Address already in use`. Ports now
+ come from a band below every platform's ephemeral range, strided per process
+ and probe-bound on both `127.0.0.1` and `::1` (a port free on one family can
+ be taken on the other, which is exactly how it failed). Test-only change.
+
+- **A search that aggregates over a cold segment could deadlock forever**
+ ([#751](https://github.com/xerj-org/xerj/issues/751)). On a multi-thread
+ runtime `Index::search` runs its whole body inside
+ `block_in_place(|| Handle::current().block_on(..))`: that hands the worker's
+ core to a tokio *blocking-pool* thread — which then runs the scheduler loop
+ for the life of the runtime — and parks the calling thread, itself a
+ blocking-pool thread, for the entire search. An aggregation with no columnar
+ fast path assembles the full corpus from inside that park, and the cold
+ segment hydration it needs (`stored_values_for_async`) queued its decode with
+ `spawn_blocking` — onto the very pool the waiter was holding a thread of.
+ tokio grows that pool only when it observes zero idle threads at push time,
+ so the core hand-off and the decode submission could both see the same idle
+ thread, both merely notify, and the one thread that woke took the core and
+ never returned. The decode was then queued behind threads that were all
+ permanently running worker cores: the search waited for a task that could
+ never be scheduled. The decode now runs on the engine's own rayon maintenance
+ pool, whose threads are never consumed by tokio, so the wait cannot be
+ circular. This is what made CI's default-parallelism workspace-test step hang
+ on hosted runners and leave `main` with no verdict for hours. Measured on a
+ 4-cpu affinity mask with the reported test binary: 12 hangs in 60 runs before,
+ 0 in 200 after (and 0 in 100 on a 2-cpu mask). One consequence worth knowing:
+ a cold hydration a search is waiting on now runs at the maintenance pool's
+ `nice(10)` instead of a `nice(0)` blocking thread, which is only observable
+ when every core is already saturated.
+
## [1.0.0-rc.72] - 2026-08-31
The idle-cost release. A 2026-08-29 measurement session found XERJ was not
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index a5b554da8..a17dfbf42 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -5447,8 +5447,8 @@ mod semantic_deadline_regression_tests {
"request waited for detached cold load instead of its deadline"
);
- // `spawn_blocking` is deliberately not aborted: the immutable load
- // completes and warms the cache for a later request.
+ // The detached decode is deliberately not cancelled: the immutable
+ // load completes and warms the cache for a later request.
tokio::time::timeout(std::time::Duration::from_secs(1), async {
while idx.stored_value_cache.is_empty() {
tokio::task::yield_now().await;
@@ -25735,11 +25735,17 @@ impl Index {
/// worker. Cache hits stay on the caller because they are only a DashMap
/// lookup and `Arc` clone.
///
- /// `spawn_blocking` tasks cannot be cancelled once started. A timed-out or
- /// dropped request therefore leaves the load running to completion, which
- /// is useful: it warms the immutable segment for the next request. The
- /// segment-current check prevents such a detached completion from
- /// resurrecting a cache entry that a concurrent merge already retired.
+ /// The decode runs on the engine's own rayon maintenance pool, never on
+ /// tokio's blocking pool: a search already parks a blocking-pool thread
+ /// inside `block_in_place` for its whole duration, so queueing this work
+ /// there is a circular wait (issue #751, and the rule stated on
+ /// `await_publication_barrier`).
+ ///
+ /// The submitted decode is never cancelled. A timed-out or dropped request
+ /// therefore leaves the load running to completion, which is useful: it
+ /// warms the immutable segment for the next request. The segment-current
+ /// check prevents such a detached completion from resurrecting a cache
+ /// entry that a concurrent merge already retired.
async fn stored_values_for_async(&self, segment_id: &str) -> Option<Resident<Vec<Value>>> {
if let Some(entry) = self.stored_value_cache.get(segment_id) {
return Some(Arc::clone(entry.value()));
@@ -25776,7 +25782,42 @@ impl Index {
loads.remove(&segment_id);
return;
};
- let blocking = tokio::task::spawn_blocking(move || {
+ // #751 — the decode runs on the engine's own rayon
+ // maintenance pool, NOT on tokio's blocking pool.
+ //
+ // `Index::search` wraps its whole body in
+ // `block_in_place(|| Handle::current().block_on(..))`
+ // on multi-thread runtimes (M5.21). `block_in_place`
+ // hands the worker's core to a tokio BLOCKING-pool
+ // thread — which then runs `worker::run` for the rest
+ // of the runtime's life — and parks the calling thread,
+ // itself a blocking-pool thread, for the whole search.
+ // An aggregation with no columnar path assembles the
+ // full corpus from inside that park, so a `spawn_blocking`
+ // here would queue work on the very pool the waiter is
+ // holding a thread of. tokio grows that pool only when
+ // it observes zero idle threads at push time, so the
+ // core hand-off and this submission can both see the
+ // same idle thread, both merely `notify_one()`, and the
+ // one woken thread takes the core and never comes back.
+ // The decode is then queued behind threads that are all
+ // permanently running worker cores: the search waits for
+ // a task that can never be scheduled. Live-reproduced as
+ // the CI hang in issue #751 (12-min step timeout, 12/60
+ // runs on a 4-cpu mask) and pinned deterministically by
+ // `tests/agg_corpus_hydration_deadlock.rs`.
+ //
+ // The maintenance pool's threads exist for the process
+ // lifetime and are never consumed by tokio, so the wait
+ // cannot be circular. It is the read-side twin of the
+ // work already on this pool (flush side-car builds,
+ // segment finalisation); the cost is that a cold
+ // hydration a search is waiting on now runs at the
+ // pool's `nice(10)`, which only bites when every core is
+ // already saturated.
+ let (decoded_tx, decoded_rx) =
+ tokio::sync::oneshot::channel::<Option<Resident<Vec<Value>>>>();
+ let decode = move || -> Option<Resident<Vec<Value>>> {
#[cfg(test)]
{
load_count.fetch_add(1, Ordering::Relaxed);
@@ -25837,8 +25878,21 @@ impl Index {
}
};
Some(resident)
+ };
+ crate::background_pool().spawn(move || {
+ // Preserve the pre-#751 failure semantics: a panic
+ // in the decode used to surface as a `JoinError`
+ // and leave the waiter with `None` (the caller then
+ // reports the segment unreadable). rayon's default
+ // is to abort the process instead, so catch it here.
+ // Under `panic = "abort"` (the shipped profile) this
+ // is a no-op, exactly as before.
+ let decoded =
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(decode))
+ .unwrap_or(None);
+ let _ = decoded_tx.send(decoded);
});
- if let Ok(Some(value)) = blocking.await {
+ if let Ok(Some(value)) = decoded_rx.await {
let _ = sender.send(Some(value));
}
drop(permit);
diff --git a/engine/crates/xerj-engine/tests/agg_corpus_hydration_deadlock.rs b/engine/crates/xerj-engine/tests/agg_corpus_hydration_deadlock.rs
new file mode 100644
index 000000000..8c19bc830
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/agg_corpus_hydration_deadlock.rs
@@ -0,0 +1,124 @@
+//! Regression test for issue #751 — the CI hang.
+//!
+//! `Index::search` runs the whole search body inside
+//! `block_in_place(|| Handle::current().block_on(search_fut))` on a
+//! multi-thread runtime (the M5.21 read-throughput fix). `block_in_place`
+//! hands the worker's core to a **tokio blocking-pool** thread and keeps the
+//! calling thread parked for the entire search — await points included.
+//!
+//! An aggregation that has no columnar fast path then assembles the full
+//! corpus, and a cold flushed segment is hydrated by
+//! `Index::stored_values_for_async`. Before the fix that hydration queued its
+//! decode with `tokio::task::spawn_blocking` — i.e. **onto the same blocking
+//! pool the search is already holding a thread of**. tokio only grows that
+//! pool when it observes zero idle threads at push time; when it cannot grow
+//! (or when the core hand-off has just consumed the one thread it thought was
+//! idle) the decode task is queued behind threads that are all running worker
+//! cores and never return to the pool. The search then waits for a task that
+//! can never be scheduled — forever. That is the CI hang: `cargo test` at
+//! default parallelism sat in
+//! `script_bucketed_agg_past_the_call_depth_limit_is_an_error_not_empty_buckets`
+//! until the 12-minute step timeout killed the job.
+//!
+//! The runtime below makes the starvation deterministic rather than a race:
+//! one worker, and a blocking pool that may hold exactly one extra thread —
+//! which `block_in_place`'s core hand-off takes. On the unfixed engine the
+//! search never returns; the watchdog turns that into a named failure instead
+//! of a hang, because a regression test for a hang must never hang.
+
+use serde_json::json;
+use std::time::Duration;
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::Schema;
+use xerj_engine::Engine;
+use xerj_query::parse_request;
+
+/// Long enough that a slow machine is never mistaken for the deadlock (the
+/// search itself is single-digit milliseconds), short enough that a regression
+/// fails a CI step instead of hanging it.
+const WATCHDOG: Duration = Duration::from_secs(60);
+
+fn test_config(dir: &TempDir) -> Config {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ // Keep every flush explicit: this test is about the *cold read* of an
+ // already-published segment, not about flush scheduling.
+ config.storage.flush_size_mb = 4096;
+ config.storage.flush_interval_secs = 3600;
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ config
+}
+
+/// A `terms` agg keyed by a Painless script. Scripts carry no field mapping,
+/// so no columnar/doc-values fast path can serve this — it forces the
+/// full-corpus assembly that hydrates every flushed segment's stored section,
+/// which is the path that deadlocked.
+fn scripted_terms_agg() -> xerj_query::ast::SearchRequest {
+ parse_request(&json!({
+ "size": 0,
+ "query": { "match_all": {} },
+ "aggs": {
+ "by_script": { "terms": { "script": { "source": "return doc['rank'];" } } }
+ }
+ }))
+ .expect("parse_request")
+}
+
+#[test]
+fn agg_corpus_hydration_completes_when_the_blocking_pool_cannot_grow() {
+ let (tx, rx) = std::sync::mpsc::channel::<()>();
+ let worker = std::thread::Builder::new()
+ .stack_size(8 * 1024 * 1024)
+ .spawn(move || {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ // One worker + one spare blocking thread. `block_in_place`
+ // inside `Index::search` hands the worker's core to that one
+ // spare, so any *further* `spawn_blocking` submitted while the
+ // search is in flight has no thread that will ever run it.
+ .worker_threads(1)
+ .max_blocking_threads(1)
+ .enable_all()
+ .build()
+ .expect("build test runtime");
+ runtime.block_on(async move {
+ let dir = TempDir::new().expect("tempdir");
+ let engine = Engine::new(test_config(&dir)).expect("engine::new");
+ engine
+ .create_index("aggs", Schema::empty())
+ .expect("create");
+ let idx = engine.get_index("aggs").expect("get_index");
+ idx.index_document(Some("1".into()), json!({ "rank": 7 }))
+ .await
+ .expect("index_document");
+ // Publishes a segment; the stored section stays cold, so the
+ // agg corpus below has to hydrate it.
+ idx.refresh().await.expect("refresh");
+
+ // The search must run ON A WORKER for `block_in_place` to take
+ // its core — `Runtime::block_on`'s own thread holds no core and
+ // would run the closure inline, hiding the bug.
+ let searcher = std::sync::Arc::clone(&idx);
+ tokio::spawn(async move { searcher.search(&scripted_terms_agg()).await })
+ .await
+ .expect("search task")
+ .expect("search");
+ // Keep the data dir alive until the search is done.
+ drop(dir);
+ });
+ let _ = tx.send(());
+ })
+ .expect("spawn test thread");
+
+ match rx.recv_timeout(WATCHDOG) {
+ Ok(()) => {
+ worker.join().expect("test thread panicked");
+ }
+ Err(_) => panic!(
+ "issue #751: the aggregation-corpus segment hydration never completed in {WATCHDOG:?}. \
+ The cold-segment decode is waiting on the tokio blocking pool while the search that \
+ needs it is itself parked on a blocking-pool thread inside `block_in_place` — a \
+ self-deadlock, not a slow test."
+ ),
+ }
+}
diff --git a/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rs b/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rs
index 75c3926bb..89fe05d13 100644
--- a/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rs
+++ b/engine/crates/xerj-server/tests/cleartext_bind_fail_closed.rs
@@ -16,15 +16,76 @@
//! any listener exists, and the ports handed to it are free either way.
use std::io::Read;
-use std::net::TcpListener;
+use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener};
use std::process::{Command, Stdio};
+use std::sync::atomic::{AtomicU16, Ordering};
use std::time::{Duration, Instant};
-/// Three distinct free ports, held simultaneously so they cannot collide,
-/// then released for the child. `Config::validate` requires all three listener
-/// ports to differ; free ports also mean a regressed (serving) binary binds
-/// cleanly and keeps running instead of dying on an unrelated bind error,
-/// which would masquerade as a pass.
+/// Lowest port any supported platform hands out for an *ephemeral* bind:
+/// Linux defaults to 32768-60999, macOS and Windows to 49152-65535.
+///
+/// Ports for a child process must come from BELOW this line — see
+/// [`next_free_port`].
+const EPHEMERAL_FLOOR: u16 = 32_768;
+
+/// Start of the private band these tests allocate from. 15 000 is above the
+/// registered-service crowd and well below [`EPHEMERAL_FLOOR`].
+const BAND_START: u16 = 15_000;
+/// Width of the band: `15_000..31_000`.
+const BAND_LEN: u16 = 16_000;
+
+/// A port that is free on both loopback families, taken from a band no
+/// ephemeral bind can be handed.
+///
+/// This used to be `TcpListener::bind("127.0.0.1:0")`, read the port, drop the
+/// listener, hand the number to a child. That is a race, not an allocation:
+/// the kernel is free to hand the very same ephemeral port to the next
+/// `bind(":0")` anywhere in the process, and several tests in this file start
+/// a real server and keep it alive for seconds, so at `cargo test`'s default
+/// parallelism they overlap. CI run 33359300573 failed exactly that way —
+/// `default_and_loopback_binds_start_normally` died with
+/// `gRPC: bind [::1]:46843 ... Address already in use (os error 98)` against a
+/// port a sibling test's child had already taken. (Issue #751's other half:
+/// "serialise its port/fixture access".)
+///
+/// Two things make the number safe to hand over:
+///
+/// * it comes from outside the ephemeral range, so no `bind(":0")` — ours or
+/// anyone else's — can compete for it, and a process-strided cursor keeps
+/// two concurrent `cargo test` runs apart;
+/// * it is probe-bound on 127.0.0.1 **and** ::1. A port free on 127.0.0.1 can
+/// still be taken on ::1, which is precisely how the CI failure happened,
+/// so probing one family would not have caught it.
+fn next_free_port() -> u16 {
+ static CURSOR: std::sync::LazyLock<AtomicU16> =
+ std::sync::LazyLock::new(|| AtomicU16::new((std::process::id() % BAND_LEN as u32) as u16));
+ for _ in 0..BAND_LEN {
+ let offset = CURSOR.fetch_add(1, Ordering::Relaxed) % BAND_LEN;
+ let port = BAND_START + offset;
+ if loopback_port_is_free(port) {
+ return port;
+ }
+ }
+ panic!("no free port in {BAND_START}..{}", BAND_START + BAND_LEN);
+}
+
+/// True when `port` can be bound on every loopback address a child here might
+/// use. A host with no IPv6 at all fails the ::1 probe for a reason other than
+/// `AddrInUse`, and that must not disqualify the port.
+fn loopback_port_is_free(port: u16) -> bool {
+ if TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).is_err() {
+ return false;
+ }
+ match TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))) {
+ Ok(_) => true,
+ Err(e) => e.kind() != std::io::ErrorKind::AddrInUse,
+ }
+}
+
+/// Three distinct free ports for the child. `Config::validate` requires all
+/// three listener ports to differ; free ports also mean a regressed (serving)
+/// binary binds cleanly and keeps running instead of dying on an unrelated
+/// bind error, which would masquerade as a pass.
fn three_free_ports() -> (u16, u16, u16) {
let (a, b, c, _) = four_free_ports();
(a, b, c)
@@ -32,14 +93,34 @@ fn three_free_ports() -> (u16, u16, u16) {
/// As above plus a fourth for the cluster transport.
fn four_free_ports() -> (u16, u16, u16, u16) {
- let held: Vec<TcpListener> = (0..4)
- .map(|_| TcpListener::bind("127.0.0.1:0").unwrap())
- .collect();
- let p: Vec<u16> = held
- .iter()
- .map(|l| l.local_addr().unwrap().port())
+ (
+ next_free_port(),
+ next_free_port(),
+ next_free_port(),
+ next_free_port(),
+ )
+}
+
+/// The guard for the CI flake above. It pins the two properties that make a
+/// handed-over port safe, and both fail on the old `bind(":0")` helper: that
+/// one returns ephemeral ports by construction, and two concurrent callers can
+/// be handed the same one.
+#[test]
+fn handed_over_ports_are_non_ephemeral_and_never_repeat() {
+ let threads: Vec<_> = (0..8)
+ .map(|_| std::thread::spawn(|| (0..8).map(|_| next_free_port()).collect::<Vec<_>>()))
.collect();
- (p[0], p[1], p[2], p[3])
+ let mut seen = std::collections::HashSet::new();
+ for t in threads {
+ for port in t.join().expect("port thread") {
+ assert!(
+ port < EPHEMERAL_FLOOR,
+ "port {port} is inside the ephemeral range, so any concurrent \
+ bind(\":0\") can be handed it before the child binds it"
+ );
+ assert!(seen.insert(port), "port {port} was handed out twice");
+ }
+ }
}
/// TOML-safe rendering of a temp path (Windows backslashes would be escape