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(autoindex): never lose the ticker's stop — an early exit no longer waits out --progress-interval

xerj-orge4c1e750f6f4
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 39ed95faf..3b6b4ff60 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -146,11 +146,16 @@ pub fn print_help() {
PROGRESS STREAM:\n\
stdout is the RESULT, stderr is PROGRESS — pipe them separately.\n\
Every run that reaches an exit — success OR error — ends with one\n\
- terminal line, in every mode, so an outcome never has to be guessed\n\
- from silence:\n\
+ terminal line, in every progress mode EXCEPT `none` (which --quiet\n\
+ selects), so an outcome never has to be guessed from silence:\n\
xerj-done ok=true exit=3 reason=completed-with-junk wall=57.6s …\n\
- (A run killed by a signal cannot print one; a missing terminal line\n\
- after the process is gone means it died, not that it finished.)\n\
+ --quiet/--progress none prints no progress and NO terminal line\n\
+ (only a fatal `error:` line, if any) — poll `autoindex status\n\
+ --state-dir <dir>` or read the exit code instead of waiting for\n\
+ output that never comes.\n\
+ (A run killed by a signal cannot print one either; a missing\n\
+ terminal line after the process is gone means it died, not that it\n\
+ finished.)\n\
--progress plain emits `xerj-progress phase=… pct=… eta_s=…` lines;\n\
`pct`/`eta_s` are the literal word `unknown` (JSON null) whenever they\n\
cannot be computed honestly, never a filler number.\n\
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index 401998ee6..addc4e737 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -1115,8 +1115,10 @@ fn zero_live_documents_after_journaled_records_fails_the_run() {
/// the REAL progress surface a production run uses:
/// 1. phase B reports as it goes, with a percent and an ETA field;
/// 2. the previously-silent finalize block reports at all;
-/// 3. every run ends with a terminal line that states the outcome in words,
-/// because exit 3 is a success an agent otherwise reads as failure.
+/// 3. every run on a surface that prints at all ends with a terminal line
+/// stating the outcome in words, because exit 3 is a success an agent
+/// otherwise reads as failure. (`--progress none` prints nothing —
+/// asserted by `quiet_runs_emit_no_progress_stream_at_all` below.)
#[test]
fn a_run_reports_progress_through_every_phase_and_closes_the_stream() {
let _guard = FAILPOINT_TEST_LOCK.lock().unwrap();
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 1c3316034..db02d51d0 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -2622,9 +2622,10 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
} else {
0
};
- // Terminal line, in every mode. Exit 3 means "completed, some files were
- // unparseable" — success — and an agent reading a bare `3` off a silent
- // stream reads failure (#241 §9). Say it in words.
+ // Terminal line, in every progress mode but `none` (which `--quiet`
+ // selects, and which prints nothing by definition). Exit 3 means
+ // "completed, some files were unparseable" — success — and an agent reading
+ // a bare `3` off a silent stream reads failure (#241 §9). Say it in words.
pr.finish(
true,
code,
diff --git a/engine/crates/xerj-autoindex/src/progress.rs b/engine/crates/xerj-autoindex/src/progress.rs
index bbec0c515..eb3d7a5da 100644
--- a/engine/crates/xerj-autoindex/src/progress.rs
+++ b/engine/crates/xerj-autoindex/src/progress.rs
@@ -9,7 +9,11 @@
//! worker-driven heartbeat cannot bound silence — a timer can.
//! * **Liveness is time-based, never item-based.** `--progress-interval`
//! seconds is the guaranteed upper bound on silence between the first phase
-//! and the terminal line.
+//! and the terminal line. It is an upper bound on silence *only* — never a
+//! floor on the run: stopping the ticker must be observed at once, not at the
+//! next tick, or a run that exits early pays the whole interval to shut down.
+//! `--progress none` (`--quiet`) opts out of the surface entirely and so out
+//! of both the liveness bound and the terminal line.
//! * **Nothing is displayed that cannot be computed honestly.** A percent is
//! emitted only when a real denominator exists, and an ETA only after the
//! quality gate below is satisfied; otherwise the field is literally
@@ -452,14 +456,22 @@ impl Progress {
self.emit();
}
- /// The terminal line, in every mode. An exit code alone is ambiguous —
- /// autoindex exits 3 on success-with-junk — so the reason is spelled out.
+ /// The terminal line, in every mode that has a surface at all. An exit code
+ /// alone is ambiguous — autoindex exits 3 on success-with-junk — so the
+ /// reason is spelled out.
///
/// Every run that *reaches an exit* emits exactly one of these: on success
/// from the call sites below, and on any error path from [`Ticker::drop`].
- /// A run killed by a signal, or aborted by a panic (the release profile is
- /// `panic = "abort"`, so unwinding never reaches `Drop`), cannot print one
- /// — which is itself the signal that the process died abnormally.
+ ///
+ /// Two documented exceptions, both of which a caller must plan for:
+ /// - [`Surface::Silent`] (`--progress none`, which `--quiet` selects)
+ /// returns early below and emits nothing — no progress and no terminal
+ /// line. A quiet run is watched with `autoindex status` or its exit code,
+ /// never by waiting on this stream. (A fatal `error:` line is printed by
+ /// the caller and is unaffected.)
+ /// - A run killed by a signal, or aborted by a panic (the release profile
+ /// is `panic = "abort"`, so unwinding never reaches `Drop`), cannot print
+ /// one — which is itself the signal that the process died abnormally.
pub fn finish(&self, ok: bool, exit: i32, reason: &str, extra: &[(&str, u64)]) {
if self.reported.swap(true, Ordering::SeqCst) || !self.enabled() {
return;
@@ -662,17 +674,38 @@ impl Progress {
let interval = self.interval;
let handle = std::thread::Builder::new()
.name("autoindex-progress".into())
- .spawn(move || loop {
- let stopped = progress.stopped.lock().unwrap();
- let (stopped, _timeout) = progress
- .wake
- .wait_timeout(stopped, interval)
- .expect("progress ticker mutex poisoned");
- if *stopped {
- break;
+ .spawn(move || {
+ // Hold the guard across the loop and test the flag BEFORE
+ // waiting. A condvar notification reaches only threads already
+ // parked in `wait`, so a `stop()` that lands while this thread
+ // is anywhere else — above all before its very first wait — is
+ // delivered to nobody and is gone. Re-checking the predicate
+ // under the lock is what makes it impossible to miss: the flag
+ // is set under the same mutex, so either we see it here or we
+ // are already parked and the notify wakes us.
+ //
+ // Getting this wrong is not a latency detail. `Ticker::drop`
+ // joins this thread, so a lost stop turns every early exit —
+ // `es.ping()` refused, `no-files`, a small `--dry-run` — into a
+ // full `--progress-interval` of silence AFTER the terminal line
+ // has printed, and `--progress-interval 3600` makes that an
+ // hour.
+ let mut stopped = progress.stopped.lock().unwrap();
+ while !*stopped {
+ let (guard, _timeout) = progress
+ .wake
+ .wait_timeout(stopped, interval)
+ .expect("progress ticker mutex poisoned");
+ stopped = guard;
+ if *stopped {
+ break;
+ }
+ // Never emit while holding `stopped`: `stop()` would block
+ // behind a write to a slow pipe.
+ drop(stopped);
+ progress.emit();
+ stopped = progress.stopped.lock().unwrap();
}
- drop(stopped);
- progress.emit();
})
.ok();
Ticker {
@@ -1205,4 +1238,102 @@ mod tests {
"a displayed ETA may move at most 20% per tick, got {eta}"
);
}
+
+ /// Run `f` on its own thread and return how long it took, or `None` if it
+ /// had not finished within `limit`. The thread is deliberately **not**
+ /// joined on the timeout path: the failure under test is a thread that is
+ /// parked for an entire `--progress-interval`, so joining it would make a
+ /// failing test hang for that interval instead of reporting in seconds.
+ fn time_boxed(limit: Duration, f: impl FnOnce() + Send + 'static) -> Option<Duration> {
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let start = Instant::now();
+ f();
+ let _ = tx.send(start.elapsed());
+ });
+ rx.recv_timeout(limit).ok()
+ }
+
+ /// Window 1 — `stop()` before the ticker's first wait.
+ ///
+ /// A condvar notification reaches only threads already parked in `wait`.
+ /// The original loop locked `stopped` and went straight into
+ /// `wait_timeout` without testing the flag, so a `stop()` that landed
+ /// before the thread parked was delivered to nobody, and `Ticker::drop`'s
+ /// `join()` blocked for a full `--progress-interval`. Every early exit hits
+ /// this: `es.ping()` refused (lib.rs), the `no-files` return, a small
+ /// `--dry-run`.
+ ///
+ /// The interval here is an hour against a five-second box, so the assertion
+ /// cannot pass by being lucky with the scheduler and no machine is slow
+ /// enough to make a correct implementation fail it. Fifty attempts because
+ /// the defect is a race: pre-fix, the standalone reproduction of this loop
+ /// hung 11/12 at a 5 s interval and 4/5 at 30 s, not 12/12.
+ #[test]
+ fn a_stop_before_the_first_wait_is_not_lost() {
+ for attempt in 0..50 {
+ let blocked = time_boxed(Duration::from_secs(5), || {
+ let (progress, _buffer) =
+ Progress::capture(Surface::Plain, Duration::from_secs(3600));
+ let ticker = progress.spawn_ticker();
+ drop(ticker);
+ });
+ assert!(
+ blocked.is_some(),
+ "attempt {attempt}: drop(ticker) had not returned after 5s at a \
+ 3600s interval — the stop() racing the ticker's first wait was \
+ lost, and a real run would sit silent for the whole interval"
+ );
+ }
+ }
+
+ /// Window 2 — `stop()` while the ticker is inside `emit()`.
+ ///
+ /// Held deterministically open rather than raced for: the capture sink
+ /// takes the buffer mutex on every write, so holding that mutex parks the
+ /// ticker thread inside `emit()`, provably outside `wait_timeout`. The
+ /// wakeup is delivered by `notify_all` directly (the interval is an hour,
+ /// so the timeout can never rescue a broken loop), and `stop()` is made to
+ /// land while the thread is parked in the sink. A loop that re-enters
+ /// `wait_timeout` without re-testing the flag hangs for the hour.
+ #[test]
+ fn a_stop_that_lands_while_the_ticker_is_emitting_is_not_lost() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(3600));
+ let ticker = progress.spawn_ticker();
+
+ // Own the sink the ticker writes to, then wake it. Notified repeatedly
+ // for 300 ms rather than once, because a notify sent before the thread
+ // parks is lost by definition — that is this module's whole subject,
+ // and a single early notify would leave the thread parked, where
+ // `stop()` wakes it normally and the test proves nothing. After this
+ // loop the thread is provably blocked in `emit()`: it took at least one
+ // notify while parked, and it cannot return to `wait_timeout` until the
+ // sink is released. The notifies stop here, so nothing rescues a loop
+ // that re-parks after emitting.
+ let held = buffer.lock().unwrap();
+ for _ in 0..60 {
+ progress.wake.notify_all();
+ std::thread::sleep(Duration::from_millis(5));
+ }
+
+ // Drop on another thread: stop() takes `stopped` (which the ticker is
+ // not holding while it emits) and lands now; join() then blocks.
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let start = Instant::now();
+ drop(ticker);
+ let _ = tx.send(start.elapsed());
+ });
+ std::thread::sleep(Duration::from_millis(100));
+
+ // Let emit() complete. A loop that re-tests the flag exits here; one
+ // that goes straight back into wait_timeout sleeps for the hour.
+ drop(held);
+
+ assert!(
+ rx.recv_timeout(Duration::from_secs(5)).is_ok(),
+ "drop(ticker) had not returned after 5s at a 3600s interval — a \
+ stop() that landed while the ticker was emitting was lost"
+ );
+ }
}
diff --git a/landing/llms.txt b/landing/llms.txt
index 4e98a31a4..cefcab348 100644
--- a/landing/llms.txt
+++ b/landing/llms.txt
@@ -79,7 +79,7 @@ If you are an AI coding agent driving XERJ on a person's machine, indexing is th
- **Read the progress stream — it is designed for you.** `autoindex` writes its RESULT to stdout and its LIVENESS to stderr, so `--json` stdout stays one clean parseable document while stderr narrates. When stderr is not a terminal (you), you get one line per interval, by default every 5 s: `xerj-progress phase=index basis=bytes pct=1.9 items=250/251 bytes=693420/37004502 rate=152775.9 eta_s=unknown eta_quality=unknown since_progress_s=5.0 phase_elapsed_s=9.5 elapsed_s=10.0 waiting_on=big-events.jsonl(34.6MB)` (a real line from the run that verified this). Use `--progress json` for one JSON object per line, `--progress-interval SECS` to change the cadence, `--progress none` (or `--quiet`) to silence it. Relay `pct`, `eta_s` and `waiting_on` to your user as they arrive.
* **`pct` and `eta_s` are honest or absent.** Both can be the literal string `unknown` (JSON `null`) — before a denominator exists, before the estimate has settled, or when nothing has completed recently (`eta_quality=stalled`, meaning one big file is still streaming). Never invent a number to fill the gap; report `waiting_on` instead, which names the file it is actually on.
* **Percent is bytes-based, not file-based.** `items=250/251` with `pct=1.9` is normal and correct: in that measured corpus one 34.6 MB file held 98% of the bytes, so 250 of 251 files done really was 1.9% of the work. A file-count percent would have claimed 99.6% and then sat there.
- * **Every run that reaches an exit ends with one terminal line, in every mode** — `xerj-done ok=true exit=3 reason=completed-with-junk wall=57.6s files=1922 records=115139`, and `ok=false … reason=aborted` on the error path. Wait for it rather than inferring completion from silence. A run killed by a signal cannot print one, so a process that is gone with no terminal line died; it did not finish.
+ * **Every run that reaches an exit ends with one terminal line — in every progress mode except `none`** — `xerj-done ok=true exit=3 reason=completed-with-junk wall=57.6s files=1922 records=115139`, and `ok=false … reason=aborted` on the error path. In those modes, wait for it rather than inferring completion from silence. **Do not wait for it under `--quiet` (an alias for `--progress none`)**: quiet prints no progress and no terminal line at all — a successful quiet run writes zero bytes to stderr, and a failing one writes only its `error:` line — so a quiet run is one you poll with `xerj autoindex status --state-dir <dir>` or judge by its exit code. A run killed by a signal cannot print one either, so a process that is gone with no terminal line died; it did not finish.
- **You can still poll from outside.** Start the run in the background with an explicit `--state-dir <dir>`, then poll `xerj autoindex status --state-dir <dir>` with the *same* directory — it prints `N files done, M records, in progress` (or `FINISHED`) plus live per-index doc counts. Passing no `--state-dir` to `status` prints one line per journal under `~/.xerj/autoindex`, including unrelated runs from weeks ago, which is how an agent ends up reporting someone else's progress. `status` has **no** `--json` (only `map` does); parse its text, or poll `GET /_cat/indices` / `GET /ax-*/_count` for machine-readable counts.
- **Stopping is safe, so offer it.** The resume journal plus idempotent `_id`s mean an interrupted run resumes where it stopped and never duplicates. A user may abort a long index without losing the work already done.
- **Read the exit code correctly.** `0` complete · **`3` completed-with-junk — this is SUCCESS**, junk records are recorded and never fatal; do not report it as a failure · `2` usage error · `1` **any error at all** — it is the catch-all for every failure, so read the `error:` line on stderr before you act. Endpoint-unreachable is only the most common one; a bulk failure, an index-creation conflict, a journal-config mismatch, a state-dir lock conflict, corruption or a disk error all exit 1 too, and restarting the node "because 1 means it is down" will not fix any of them.