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.

bench(#874): idle-budget fixture + CI gate; delete the O(N) metrics gauge loop

xerj-orgc8c07c90fa92
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5e2d44f51..6e1438482 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -841,3 +841,50 @@ jobs:
env:
XERJ_BIN: engine/target/ci-test/xerj
run: bash .github/scripts/autoindex-fd-smoke.sh
+
+ # Issue #874's verification fixture, kept runnable: 15 repos x ~30 datasets
+ # (~450 tiny indices), boot, settle 120 s, measure idle CPU / wakeups / RSS
+ # via /proc, gate coarsely. The unit-level guards (merge-evaluation counter,
+ # idle-flush, memtable recount tests in xerj-engine) pin the mechanisms; this
+ # job pins the PROCESS-LEVEL budget they exist to protect: an idle node must
+ # cost < 0.5 % of one core, O(1) wakeups/s, <= 0.2 MB per idle index, and
+ # boot without replaying WAL on a cleanly-flushed corpus — independent of N.
+ # ubuntu only on purpose: the sampler walks /proc. Thresholds are coarse
+ # (~2x the measured healthy values, see benchmarks/idle-budget/README.md):
+ # a 2-4 vCPU shared runner cannot support ±1 % claims, and the regressions
+ # this catches (per-index timers, per-index polling, per-index retention)
+ # arrive as multiples, not percents.
+ idle-budget:
+ name: Idle budget (many-index at-rest CPU/RSS)
+ runs-on: ubuntu-latest
+ # One tier up from the no-compile tier: compiles one crate (xerj-server)
+ # on the shared ci-test cache, then boots and measures. The fixture itself
+ # is ~8 min measured (two 120 s settle windows + ~450 PUT/_bulk rounds);
+ # 30 min leaves 3x+ headroom for a cold cache and a slow runner.
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+
+ - name: Install Rust
+ uses: dtolnay/rust-toolchain@032958afbdc797a9164d3bc0b56325c1308924a5 # 1.97.1
+
+ - name: Cache
+ uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
+ with:
+ workspaces: engine
+ # Read-only consumer of build-test's ci-test dependency cache; that
+ # job owns the key (same arrangement as api-checks / conformance).
+ shared-key: ci-test-linux
+ save-if: false
+
+ # ci-test, not release: the thresholds are coarse (O(N) blowups, not
+ # ±1 %), so fat LTO would buy measurement precision this gate does not
+ # claim to have. Same opt-level and features as every other booting job.
+ - name: Build xerj (ci-test profile)
+ working-directory: engine
+ run: cargo build --profile ci-test -p xerj-server
+
+ - name: Idle budget fixture (450 indices, 120 s settle, coarse thresholds)
+ env:
+ XERJ_BIN: ${{ github.workspace }}/engine/target/ci-test/xerj
+ run: bash benchmarks/idle-budget/run.sh
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14241575c..e226b14f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **An idle node no longer spends CPU per index on Prometheus gauges (#874).**
+ The 10 s background loop that fed `xerj_doc_count` / `xerj_segment_count` /
+ `xerj_wal_size_bytes` / `xerj_memory_usage_bytes` walked every index's WAL
+ subtree on an async runtime worker on every tick — one `read_dir` plus one
+ `stat()` per WAL shard (~16 per index at default sharding) whether anyone
+ read the values or not. The new at-rest fixture
+ (`benchmarks/idle-budget/`) measured that at ~0.7–0.9 % of one core for 450
+ idle indices (against #874's < 0.5 % budget), entirely in the `xerj-rt`
+ workers; deleting the loop and refreshing the gauges at scrape time in the
+ `/v1/metrics` handler (the same way the query-cache gauges already
+ reconcile) drops idle CPU to 0.15–0.18 % and wakeups from ~46/s to ~26/s on
+ the same corpus, with the WAL walk moved to the blocking pool. A scrape is
+ the only moment these gauges are observable, so nothing is lost between
+ scrapes. The fixture and its coarse CI gate (`idle-budget` job) keep the
+ whole budget honest: CPU < 0.5 % of one core, O(1) wakeups/s, ≤ 0.2 MB RSS
+ per idle index, boot-to-green with zero WAL replay on a cleanly-flushed
+ corpus.
+
## [1.0.0-rc.77] - 2026-09-21
The stateless-index and reader-fairness release. Two headline changes:
diff --git a/benchmarks/idle-budget/README.md b/benchmarks/idle-budget/README.md
new file mode 100644
index 000000000..478c529ac
--- /dev/null
+++ b/benchmarks/idle-budget/README.md
@@ -0,0 +1,199 @@
+# idle budget — measured on 450 idle indices
+
+Issue #874's "one fixture, kept runnable":
+
+> 15 repos x ~30 datasets, boot, settle 120 s, measure CPU/wakeups/RSS via
+> /proc. Gate the budget in CI on ubuntu (coarse thresholds; the point is
+> catching O(N) regressions, not ±1%).
+
+What [`run.sh`](./run.sh) does, the numbers that came out, and — the reason
+this fixture exists — the idle-CPU regression it caught on its very first run
+against the then-current tree, with the fix that followed. Everything below is
+from real runs on this box; result files as produced by the runs are in
+[`results/`](./results/).
+
+**Units.** Memory figures are `/proc` kB (1024-byte units — `VmRSS` and
+friends are reported in kB by the kernel); "0.2 MB per index" in the issue is
+taken at the issue's word as 204.8 kB. CPU is **% of one core** =
+(utime+stime delta over the window) / CLK_TCK / window seconds, summed over
+all threads — 100 % = one full core, 3.1 % ≈ the box's 32 threads at 1 %.
+Wakeups are context switches per second, voluntary + nonvoluntary, summed
+across `/proc/<pid>/task/*/status`. The three are never mixed into one number.
+
+## Machine
+
+| | |
+|---|---|
+| CPU | AMD Ryzen AI MAX+ 395 w/ Radeon 8060S — 32 threads (16 cores × 2) |
+| RAM | 119 GiB usable |
+| Disk | NVMe, ext4; the throwaway data dir lives on it, NOT on tmpfs (`run.sh` refuses a RAM-backed dir) |
+| OS | Linux 7.0.0-27-generic (Ubuntu), x86_64 |
+| XERJ | v1.0.0-rc.77 + branch `bench/issue-874-idle-budget-gate`, `cargo build --release -p xerj-server` |
+| Node | throwaway data dir, private port in 9610..9639, `--insecure` (TLS+auth off), `--embed-mode lexical` (the default feature-hashing embedder — not neural), no config file — `Config::default()` flush/merge/sampler behaviour is the thing measured |
+| Box load | **shared**: other agents were building and running on it during every window (load average is recorded inside each result file: 38–45 in the run of record, up to 63 in the before-fix artifact). Idle-CPU and wakeup figures are process-wide counters, so a busy neighbour inflates *nonvoluntary* switches (scheduler preemption) but not the process's own CPU time; RSS is unaffected. |
+
+## What the fixture measures
+
+Four arms, in order ([`run.sh`](./run.sh)):
+
+0. **corpus** — [`gen_corpus.sh`](./gen_corpus.sh) writes 15 repo dirs × 30
+ dataset CSVs (3 docs each, unique column names per dataset).
+1. **baseline** — a node on an *empty* data dir, same 120 s window. The
+ per-index RSS line subtracts this node's VmRSS; without it the divisor
+ would include one runtime's worth of allocations.
+2. **load** — boot, create one index per dataset over the ES wire with
+ default settings (no shard override — default behaviour is the point),
+ `_bulk` 3 docs each, `POST /_flush`, SIGTERM (graceful, flushes on the way
+ out).
+3. **restart + measure** — boot again on the cleanly-flushed corpus: this
+ boot-to-green is the boot number, and the restart log must contain **zero**
+ `replayed WAL entries` lines (a clean flush replays nothing). Then 5 s of
+ boot-tail drain and the 120 s measurement window, `/proc` only
+ (`perf_event_paranoid` makes perf unavailable; `ps`/`uptime` are absent
+ here). CPU and wakeups are **deltas over the window**, never spot samples;
+ RSS is read at window end.
+
+One environmental normalization, applied to the load node only: the sandbox
+these numbers were taken on keeps its disk at ~96 % used, above the node's
+default 95 % disk flood-stage watermark, which would 429 the loader for
+reasons that have nothing to do with the idle budget. `run.sh` raises the
+watermark to 99 % on its own throwaway node via the engine's documented
+runtime override (`PUT _cluster/settings` on
+`cluster.routing.allocation.disk.watermark.flood_stage`), waits out the
+resource sampler's apply/release ticks, and probes a real document write
+before loading. On CI (disk nowhere near 95 %) the override is a no-op.
+`KEEP=1` preserves the throwaway dir and both arms' boot logs.
+
+## Measured
+
+The run of record (fixed binary, all gates green, 2026-09-21,
+[`results/result-n450indices.json`](./results/result-n450indices.json)):
+
+| | baseline node (N=0) | 450 indices | gate | verdict |
+|---|---|---|---|---|
+| idle CPU (% of one core, 120 s window) | 0.10 | **0.175** | < 0.5 | ok |
+| wakeups/s (vol + nonvol, process-wide) | 26.0 | **26.6** (24.2 + 2.4) | < 100 | ok |
+| VmRSS (kB) | 76 240 | **158 944** (anon 134 704 + file 24 240; HWM 173 028) | — | — |
+| per-index idle RSS (kB) | — | **183.8** = (158 944 − 76 240) / 450 | ≤ 204.8 | ok |
+| boot-to-green (ms) | 184 (empty) | **215** on the cleanly-flushed corpus | < 10 000 | ok |
+| WAL replay lines after clean flush | — | **0** | 0 | ok |
+| threads / fds | 340 / 15 | **336 / 15** | — | — |
+
+N-independence is the story the CPU and wakeup rows tell: 450 indices cost
+0.075 pp more CPU and 0.6 wakeups/s more than an empty node — both within
+window noise on a box whose load average was 38–45 during the runs (recorded
+in the result file). Per-thread attribution at N=450: `xerj-memtable-s`
+0.083 %, `xerj-mem-sample` 0.058 %, `xerj-rt` 0.008 % — no thread class
+scales with index count.
+
+### What the first run caught: an O(N) idle metrics loop
+
+The fixture's first full run against the then-current tree (same binary
+version, before the fix; result preserved as
+[`results/result-n450-with-metrics-gauge-loop.json`](./results/result-n450-with-metrics-gauge-loop.json))
+**failed the CPU gate**:
+
+| 450 idle indices | CPU (% of one core) | wakeups/s | per-index RSS (kB) |
+|---|---|---|---|
+| background gauge loop present (first run) | **1.12** (0.78 in an earlier window; load 40→63 during the runs) | 46.1 (24.9 vol + 21.2 nonvol) | 185.3 |
+| per-thread attribution | `xerj-rt` 0.92, `xerj-memtable-s` 0.10, `xerj-mem-sample` 0.08 | | |
+| loop disabled, binary otherwise identical (A/B, 4 windows) | **0.15–0.18** | 26.3–26.9 | — |
+| loop deleted (the committed fix; run of record above) | **0.175** | 26.6 | 183.8 |
+
+Root cause: `run_metrics_gauge_loop` — a 10 s ticker that fed the Prometheus
+gauges (`xerj_doc_count`, `xerj_segment_count`, `xerj_wal_size_bytes`,
+`xerj_memory_usage_bytes`) — walked **every index's WAL subtree** on every
+tick: `read_dir` + one `metadata()` per WAL shard. At 450 indices × ~16
+default shards that is ~7 400 `stat()` calls every 10 s on an async runtime
+worker, and it scales with index count: 0.7–0.9 % of one core at N=450 idle,
+against the issue's < 0.5 % budget line, with essentially all of it in the
+`xerj-rt` (tokio) threads. The A/B row is the causal proof: same binary, loop
+disabled by an env kill-switch, four consecutive 120 s windows.
+
+The fix (this branch): the loop is **deleted**; `/v1/metrics` refreshes the
+gauges at scrape time — the only moment they are observable — with the WAL
+subtree walk on the blocking pool
+(`engine/crates/xerj-api/src/es_compat.rs`, `refresh_metric_gauges`;
+wired in `engine/crates/xerj-api/src/native.rs`). A scrape now costs what the
+loop's tick used to, and idle time between scrapes costs nothing. Pinned by
+`engine/crates/xerj-api/tests/metrics_gauges_refresh_at_scrape_time.rs`
+(fail-before shape: with the loop gone and nothing refreshing at scrape time,
+`xerj_doc_count` reads 0 on a node holding documents).
+
+This is what the issue meant by "the point is catching O(N) regressions": a
+per-index background walk is invisible at N=5 in a unit test and 2× the budget
+at N=450.
+
+### Thresholds and why
+
+| gate | value | measured healthy | rationale |
+|---|---|---|---|
+| idle CPU | < 0.5 % of one core | 0.175 % at N=450 (0.10 baseline) | the issue's own line. ~3× above the fixed measurement, loose enough for a shared 2–4 vCPU runner, tight enough that the 0.9–1.1 % loop above fails it |
+| wakeups | < 100/s process-wide | 26.6/s at N=450 (26.0 baseline) | "O(1)/s process-wide" made numeric. ~2× the worst healthy window seen (46/s under load-63 neighbours; ~26/s on the fixed binary). The #871-class regression (~115/s timer churn at 464 indices) fails it; a `GATE_WAKEUPS_PER_S=100` that flaps would get disabled, so it is set where only real per-index timers land |
+| per-index RSS | ≤ 204.8 kB | 183.8 kB at N=450 | the issue's acceptance line, taken literally (0.2 MB = 204.8 kB in /proc units). 32 threads × default sharding is the *large* configuration — a 2–4 vCPU CI runner shards less |
+| boot-to-green | < 10 000 ms | 215 ms at N=450 (184 empty) | ~45× the measured boot; the regression class is O(corpus) WAL replay, which lands in the tens of seconds, not the hundreds of ms |
+| WAL replay after clean flush | 0 lines | 0 | a clean `POST /_flush` + SIGTERM checkpoint means nothing to replay; any `replayed WAL entries` line is the bug |
+
+Overrides (`GATE_CPU_PERCENT`, `GATE_WAKEUPS_PER_S`,
+`GATE_RSS_PER_INDEX_KB`, `GATE_BOOT_MS`) exist for local experiments; the
+defaults are the CI contract. If a gate fails, the finding is the point — do
+not move the line to make a run pass.
+
+## Reproduce
+
+```sh
+cd engine && cargo build --release -p xerj-server && cd ..
+XERJ_BIN=$PWD/engine/target/release/xerj bash benchmarks/idle-budget/run.sh
+# smaller / faster variants:
+REPOS=5 DATASETS=30 SETTLE_SECS=60 LABEL=n150 bash benchmarks/idle-budget/run.sh # N-slope point
+REPOS=15 DATASETS=30 SETTLE_SECS=20 LABEL=smoke bash benchmarks/idle-budget/run.sh # ~3 min smoke
+```
+
+The script picks the first free base port in 9610..9639 (never :9200), refuses
+a non-empty or RAM-backed data dir, and writes `results/result-<LABEL>.json`.
+Expected tail of a green run:
+
+```
+== measured ==
+ boot-to-green, empty node 184 ms
+ boot-to-green, 450 indices 215 ms (cleanly-flushed corpus)
+ WAL replay lines after flush 0 (0 = nothing to replay)
+ idle CPU, 450 indices 0.175 % of one core (window 120.0s)
+ idle CPU, baseline node 0.1 % of one core
+ wakeups/s, 450 indices 26.6 /s (voluntary 24.2/s + nonvoluntary 2.4/s)
+ wakeups/s, baseline node 26.0 /s
+ VmRSS, 450 indices 158944 kB (VmHWM 173028 kB; anon 134704 kB + file 24240 kB)
+ VmRSS, baseline node 76240 kB
+ per-index idle RSS 183.8 kB ((158944 - 76240) / 450)
+ threads 336, fds 15, loadavg ['37.78', '39.23', '40.32']
+
+== gate (coarse thresholds; the point is catching O(N) regressions, not ±1%) ==
+ ok CLAIMED idle CPU < 0.5 % of one core (any N)
+ MEASURED 0.175 % over 120.0s
+ ok CLAIMED wakeups < 100/s process-wide (any N)
+ MEASURED 26.6/s (vol 24.2 + nonvol 2.4)
+ ok CLAIMED per-index idle RSS <= 204.8 kB (0.2 MB; total vs N)
+ MEASURED 183.8 kB = (158944 - 76240) / 450
+ ok CLAIMED boot-to-green < 10000 ms on a cleanly-flushed 450-index corpus
+ MEASURED 215 ms (empty node boots in 184 ms)
+ ok CLAIMED no O(corpus) WAL replay after a clean flush
+ MEASURED 0 'replayed WAL entries' lines in the restart log
+ ok CLAIMED 450 indices
+ MEASURED 450 (doc probe: 3 hits on one index)
+
+IDLE-BUDGET GATE PASSED
+```
+
+CI: the `idle-budget` job in [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml)
+builds `xerj-server` with the shared `ci-test` profile cache and runs the
+fixture with its defaults (450 indices, 120 s settle, the thresholds above) on
+`ubuntu-latest`, `timeout-minutes: 30` — the fixture itself is ~8 min measured.
+
+## Result files
+
+- [`results/result-n450indices.json`](./results/result-n450indices.json) — run of record, fixed binary, all gates green.
+- [`results/result-n450-with-metrics-gauge-loop.json`](./results/result-n450-with-metrics-gauge-loop.json) — the failing first run (CPU 1.12 % > 0.5), kept as the before-artifact of the metrics-loop fix.
+
+Each carries the binary version+path, corpus shape, boot times for all three
+boots, both sample windows (including per-thread CPU attribution and the load
+average at window start), and the computed per-index RSS.
diff --git a/benchmarks/idle-budget/gen_corpus.sh b/benchmarks/idle-budget/gen_corpus.sh
new file mode 100755
index 000000000..577de637a
--- /dev/null
+++ b/benchmarks/idle-budget/gen_corpus.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+# Generate the issue #874 idle-budget corpus: 15 "repos" x ~30 "datasets" of
+# a few small docs each — the synthetic equivalent of the corpus the at-rest
+# budgets were measured on (autoindex over 15 reference repos => ~464 small
+# indices + system indices; see docs/measurements/autoindex-watch-2026-09-19.md).
+#
+# Shape: one directory per repo, one CSV per dataset, UNIQUE column names per
+# dataset — the same dataset-inference key .github/scripts/autoindex-fd-smoke.sh
+# uses (a distinct schema => a distinct inferred dataset). run.sh turns each
+# CSV into one index over the ES wire.
+#
+# benchmarks/idle-budget/gen_corpus.sh <out-dir> [repos] [datasets]
+# env REPOS= / DATASETS= work too; positional args win.
+set -euo pipefail
+OUT=${1:?usage: gen_corpus.sh <out-dir> [repos] [datasets]}
+REPOS=${2:-${REPOS:-15}}
+DATASETS=${3:-${DATASETS:-30}}
+
+mkdir -p "$OUT"
+n=0
+for r in $(seq 1 "$REPOS"); do
+ rd=$(printf 'repo-%02d' "$r")
+ mkdir -p "$OUT/$rd"
+ for d in $(seq 1 "$DATASETS"); do
+ # Global counter across the whole corpus: column names never repeat, so
+ # every dataset has a distinct schema (and run.sh's per-dataset docs with
+ # them). 3 data rows = "a few small docs".
+ i=$((n + 1))
+ printf 'k_%d_id,k_%d_name,k_%d_val\n1,alpha-%d,10\n2,beta-%d,20\n3,gamma-%d,30\n' \
+ "$i" "$i" "$i" "$i" "$i" "$i" > "$OUT/$rd/$(printf 'ds_%03d.csv' "$d")"
+ n=$i
+ done
+done
+echo "generated $n datasets under $OUT ($REPOS repos x $DATASETS datasets, 3 docs each)"
diff --git a/benchmarks/idle-budget/results/result-n450-with-metrics-gauge-loop.json b/benchmarks/idle-budget/results/result-n450-with-metrics-gauge-loop.json
new file mode 100644
index 000000000..7c75372ed
--- /dev/null
+++ b/benchmarks/idle-budget/results/result-n450-with-metrics-gauge-loop.json
@@ -0,0 +1,106 @@
+{
+ "label": "n450",
+ "date_utc": "2026-09-21T20:16:02+00:00",
+ "binary": {
+ "version": "xerj v1.0.0-rc.77",
+ "path": "/root/xerj-874/engine/target/release/xerj"
+ },
+ "corpus": {
+ "shape": "15x30",
+ "indices": 450,
+ "docs_per_index": 3
+ },
+ "port": 9610,
+ "window_s": 120.0,
+ "settle_target_s": 120.0,
+ "boot_ms": {
+ "empty_node": 26,
+ "baseline_arm": 2339,
+ "n_indices": 125
+ },
+ "wal_replay_lines_after_clean_flush": 0,
+ "doc_probe_hits": 3,
+ "baseline": {
+ "pid": 4064592,
+ "window_s": 120.0,
+ "clk_tck": 100,
+ "cpu_ticks": 17,
+ "cpu_percent_of_one_core": 0.1416,
+ "wakeups_per_s": 26.5,
+ "voluntary_per_s": 24.5,
+ "nonvoluntary_per_s": 1.9,
+ "rss_kb": 79180,
+ "hwm_kb": 115412,
+ "rss_anon_kb": 51424,
+ "rss_file_kb": 27756,
+ "threads": 340,
+ "fds": 15,
+ "per_thread_cpu": [
+ {
+ "comm": "xerj-mem-sample",
+ "cpu_ticks": 8,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.067
+ },
+ {
+ "comm": "xerj-memtable-s",
+ "cpu_ticks": 3,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.025
+ },
+ {
+ "comm": "xerj-rt",
+ "cpu_ticks": 2,
+ "threads": 2,
+ "cpu_percent_of_one_core": 0.017
+ }
+ ],
+ "loadavg_start": [
+ "40.21",
+ "36.91",
+ "36.42"
+ ]
+ },
+ "measurement": {
+ "pid": 2373380,
+ "window_s": 120.0,
+ "clk_tck": 100,
+ "cpu_ticks": 135,
+ "cpu_percent_of_one_core": 1.1248,
+ "wakeups_per_s": 46.1,
+ "voluntary_per_s": 24.9,
+ "nonvoluntary_per_s": 21.2,
+ "rss_kb": 162544,
+ "hwm_kb": 175708,
+ "rss_anon_kb": 134896,
+ "rss_file_kb": 27648,
+ "threads": 336,
+ "fds": 15,
+ "per_thread_cpu": [
+ {
+ "comm": "xerj-rt",
+ "cpu_ticks": 110,
+ "threads": 3,
+ "cpu_percent_of_one_core": 0.917
+ },
+ {
+ "comm": "xerj-memtable-s",
+ "cpu_ticks": 12,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.1
+ },
+ {
+ "comm": "xerj-mem-sample",
+ "cpu_ticks": 10,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.083
+ }
+ ],
+ "loadavg_start": [
+ "63.43",
+ "47.76",
+ "40.55"
+ ]
+ },
+ "per_index_rss_kb": 185.3
+}
\ No newline at end of file
diff --git a/benchmarks/idle-budget/results/result-n450indices.json b/benchmarks/idle-budget/results/result-n450indices.json
new file mode 100644
index 000000000..3d0f16aa0
--- /dev/null
+++ b/benchmarks/idle-budget/results/result-n450indices.json
@@ -0,0 +1,106 @@
+{
+ "label": "n450indices",
+ "date_utc": "2026-09-21T21:31:23+00:00",
+ "binary": {
+ "version": "xerj v1.0.0-rc.77",
+ "path": "/root/xerj-874/engine/target/release/xerj"
+ },
+ "corpus": {
+ "shape": "15x30",
+ "indices": 450,
+ "docs_per_index": 3
+ },
+ "port": 9610,
+ "window_s": 120.0,
+ "settle_target_s": 120.0,
+ "boot_ms": {
+ "empty_node": 184,
+ "baseline_arm": 1576,
+ "n_indices": 215
+ },
+ "wal_replay_lines_after_clean_flush": 0,
+ "doc_probe_hits": 3,
+ "baseline": {
+ "pid": 450100,
+ "window_s": 120.0,
+ "clk_tck": 100,
+ "cpu_ticks": 12,
+ "cpu_percent_of_one_core": 0.1,
+ "wakeups_per_s": 26.0,
+ "voluntary_per_s": 24.4,
+ "nonvoluntary_per_s": 1.7,
+ "rss_kb": 76240,
+ "hwm_kb": 115132,
+ "rss_anon_kb": 52200,
+ "rss_file_kb": 24040,
+ "threads": 340,
+ "fds": 15,
+ "per_thread_cpu": [
+ {
+ "comm": "xerj-mem-sample",
+ "cpu_ticks": 8,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.067
+ },
+ {
+ "comm": "xerj-memtable-s",
+ "cpu_ticks": 3,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.025
+ },
+ {
+ "comm": "xerj-rt",
+ "cpu_ticks": 2,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.017
+ }
+ ],
+ "loadavg_start": [
+ "44.69",
+ "41.35",
+ "41.16"
+ ]
+ },
+ "measurement": {
+ "pid": 2228862,
+ "window_s": 120.0,
+ "clk_tck": 100,
+ "cpu_ticks": 21,
+ "cpu_percent_of_one_core": 0.175,
+ "wakeups_per_s": 26.6,
+ "voluntary_per_s": 24.2,
+ "nonvoluntary_per_s": 2.4,
+ "rss_kb": 158944,
+ "hwm_kb": 173028,
+ "rss_anon_kb": 134704,
+ "rss_file_kb": 24240,
+ "threads": 336,
+ "fds": 15,
+ "per_thread_cpu": [
+ {
+ "comm": "xerj-memtable-s",
+ "cpu_ticks": 10,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.083
+ },
+ {
+ "comm": "xerj-mem-sample",
+ "cpu_ticks": 7,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.058
+ },
+ {
+ "comm": "xerj-rt",
+ "cpu_ticks": 1,
+ "threads": 1,
+ "cpu_percent_of_one_core": 0.008
+ }
+ ],
+ "loadavg_start": [
+ "37.78",
+ "39.23",
+ "40.32"
+ ]
+ },
+ "per_index_rss_kb": 183.8
+}
\ No newline at end of file
diff --git a/benchmarks/idle-budget/run.sh b/benchmarks/idle-budget/run.sh
new file mode 100755
index 000000000..4dd3ea851
--- /dev/null
+++ b/benchmarks/idle-budget/run.sh
@@ -0,0 +1,496 @@
+#!/usr/bin/env bash
+# ─────────────────────────────────────────────────────────────────────────────
+# idle-budget — issue #874's "one fixture, kept runnable".
+#
+# "15 repos x ~30 datasets, boot, settle 120 s, measure CPU/wakeups/RSS via
+# /proc. Gate the budget in CI on ubuntu (coarse thresholds; the point is
+# catching O(N) regressions, not ±1%)."
+#
+# In order:
+# 0. generates the corpus (gen_corpus.sh: 15 repo dirs x 30 dataset CSVs,
+# unique column names per dataset — the autoindex inference key)
+# 1. boots a BASELINE node on an empty data dir and samples it over the
+# same settle window — the per-index RSS math subtracts this
+# 2. boots the measurement node, loads ONE INDEX PER DATASET over the ES
+# wire with DEFAULT settings (no settings.index.xerj_ingest_shards
+# override — default behaviour is the point), POST /_flush, SIGTERM
+# 3. re-boots on the cleanly-flushed corpus: boot-to-green is the boot
+# number, and the second boot's log must contain ZERO "replayed WAL
+# entries" lines (a clean flush replays nothing; O(corpus) WAL replay
+# after a clean flush is the regression class this catches)
+# 4. settles SETTLE_SECS (default 120, the issue's number) and measures,
+# /proc only (perf_event_paranoid makes perf unavailable; ps/uptime are
+# absent on the shared box this was written on):
+# CPU utime+stime delta over the window -> % of one core
+# wakeups voluntary+nonvoluntary ctxt-switch delta -> per second
+# RSS VmRSS at window end (VmHWM/RssAnon/RssFile recorded too)
+# 5. gates coarsely — ::error:: annotations + exit 1 — and writes
+# results/result-<label>.json
+#
+# CPU and wakeups are DELTAS over the window, never spot samples: the runner
+# is a shared 2-4 vCPU ubuntu-latest box and a spot sample is scheduler noise.
+# RSS is inherently instantaneous; it is read at the END of the window, after
+# the full settle. Thresholds are coarse on purpose (~2x the healthy
+# measurement): a gate that flaps on ±1% gets disabled, and the regression it
+# exists to catch (per-index timers, per-index polling, per-index retention)
+# shows up as a multiple, not a percent.
+#
+# Environment:
+# XERJ_BIN server binary (default engine/target/release/xerj)
+# PORT force the base port (default: first free in 9610..9639).
+# +1 (rest) and +2 (grpc) are claimed too. NEVER :9200 — that
+# is the reference-coding server in this sandbox.
+# XERJ_DATA throwaway data dir (default mktemp -d). Must not exist
+# non-empty, and must be on a real disk: on tmpfs the corpus
+# and index live in RAM and every RSS figure is wrong (same
+# refusal as benchmarks/mbox-ingest/run.sh).
+# REPOS / DATASETS corpus shape (default 15 x 30 = 450 indices)
+# SETTLE_SECS idle measurement window (default 120; CI keeps 120)
+# DRAIN_SECS boot-tail drain before the window opens (default 5): boot
+# work has its own gate (boot-to-green), the idle window must
+# measure steady state
+# LABEL result-file name (default: n<N>indices)
+# KEEP=1 keep the throwaway dir + logs
+# GATE_* threshold overrides. Defaults are the measured-run values
+# from README.md — do not move one to make a run pass; if a
+# gate fails, the finding is the point.
+set -euo pipefail
+HERE=$(cd "$(dirname "$0")" && pwd)
+REPO=$(cd "$HERE/../.." && pwd)
+
+XERJ_BIN=${XERJ_BIN:-$REPO/engine/target/release/xerj}
+REPOS=${REPOS:-15}
+DATASETS=${DATASETS:-30}
+SETTLE_SECS=${SETTLE_SECS:-120}
+DRAIN_SECS=${DRAIN_SECS:-5}
+KEEP=${KEEP:-0}
+RESULTS_DIR=${RESULTS_DIR:-$HERE/results}
+N=$((REPOS * DATASETS))
+LABEL=${LABEL:-n${N}indices}
+
+# ── gate thresholds (coarse CI lines; rationale + measured healthy values in
+# README.md). CPU/RSS/boot are the issue's own budget lines; wakeups is the
+# established /proc proxy for timer churn (#334, #871). Values are ~2x the
+# measured healthy state (see README) — loose enough for a shared 2-4 vCPU
+# runner, tight enough that the regression classes they exist for (per-index
+# timers, per-index polling, per-index retention, O(corpus) WAL replay) trip
+# them by multiples.
+GATE_CPU_PERCENT=${GATE_CPU_PERCENT:-0.5} # < 0.5 % of one core, any N
+GATE_WAKEUPS_PER_S=${GATE_WAKEUPS_PER_S:-100} # O(1)/s process-wide, any N
+GATE_RSS_PER_INDEX_KB=${GATE_RSS_PER_INDEX_KB:-204.8} # <= 0.2 MB per idle index
+GATE_BOOT_MS=${GATE_BOOT_MS:-10000} # boot-to-green ceiling, N indices
+
+[ -x "$XERJ_BIN" ] || { echo "no server binary at $XERJ_BIN — build one:"; \
+ echo " cd engine && cargo build --release -p xerj-server"; exit 2; }
+command -v curl >/dev/null || { echo "curl is required"; exit 2; }
+command -v python3 >/dev/null || { echo "python3 (stdlib) is required"; exit 2; }
+mkdir -p "$RESULTS_DIR"
+
+# ── throwaway data dir: fresh, on a real disk ───────────────────────────────
+if [ -n "${XERJ_DATA:-}" ]; then
+ DATA=$XERJ_DATA
+ if [ -e "$DATA" ] && [ -n "$(ls -A "$DATA" 2>/dev/null)" ]; then
+ echo "refusing: XERJ_DATA=$DATA exists and is not empty (the fixture treats its data dir as throwaway; point it at a fresh path)"
+ exit 2
+ fi
+ mkdir -p "$DATA"
+else
+ DATA=$(mktemp -d "${TMPDIR:-/tmp}/idle-budget.XXXXXX")
+fi
+if command -v findmnt >/dev/null; then
+ case "$(findmnt -no FSTYPE -T "$DATA" 2>/dev/null || true)" in
+ tmpfs|ramfs) echo "refusing: $DATA is RAM-backed — RSS figures would be wrong; set XERJ_DATA to a dir on a real disk"; exit 2 ;;
+ esac
+fi
+
+# ── private port (never :9200): first free base in 9610..9639 ───────────────
+port_free() {
+ python3 - "$1" <<'PY'
+import socket, sys
+base = int(sys.argv[1])
+for p in (base, base + 1, base + 2):
+ s = socket.socket()
+ try:
+ s.bind(("127.0.0.1", p))
+ except OSError:
+ sys.exit(1)
+ finally:
+ s.close()
+PY
+}
+if [ -n "${PORT:-}" ]; then
+ # :9200 is the reference-coding server on dev boxes — refuse it by name, not
+ # only because it is usually busy.
+ [ "$PORT" = "9200" ] && { echo "refusing: PORT=9200 is reserved (reference-coding server); pick a private port"; exit 2; }
+ port_free "$PORT" || { echo "refusing: PORT=$PORT (or +1/+2) is busy"; exit 2; }
+else
+ PORT=""
+ for p in $(seq 9610 9639); do
+ if port_free "$p"; then PORT=$p; break; fi
+ done
+ [ -n "$PORT" ] || { echo "no free port in 9610..9639"; exit 2; }
+fi
+URL="http://127.0.0.1:$PORT"
+
+SERVER_PID=""
+cleanup() {
+ if [ -n "$SERVER_PID" ]; then
+ kill "$SERVER_PID" 2>/dev/null || true
+ for _ in $(seq 1 100); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.1; done
+ kill -9 "$SERVER_PID" 2>/dev/null || true
+ fi
+ if [ "${KEEP:-0}" = 1 ]; then
+ echo "KEEP=1 — data dir and logs kept at $DATA"
+ else
+ rm -rf "$DATA"
+ fi
+}
+trap cleanup EXIT
+
+# ── node lifecycle (a direct child of this shell; the EXIT trap owns it) ────
+node_start() { # $1 = data dir, $2 = log file; sets SERVER_PID
+ mkdir -p "$1"
+ # --insecure => TLS+auth off only; --port => es_compat/rest/grpc = P/P+1/P+2;
+ # no -c => Config::default() — default flush/merge/sampler behaviour is what
+ # this fixture measures. Lexical embedder, explicitly (the default
+ # feature-hashing embedder, never called neural).
+ "$XERJ_BIN" --insecure --port "$PORT" --data-dir "$1" \
+ --embed-mode lexical > "$2" 2>&1 &
+ SERVER_PID=$!
+ sleep 0.4
+ if ! kill -0 "$SERVER_PID" 2>/dev/null; then
+ echo "node failed to start; log:"; tail -20 "$2"; exit 1
+ fi
+}
+
+wait_green() { # $1 = log for context; sets BOOT_MS (process start -> health green)
+ local t0 t1 body
+ t0=$(date +%s.%N)
+ for _ in $(seq 1 300); do
+ body=$(curl -s -m 2 "$URL/_cluster/health" 2>/dev/null || true)
+ case "$body" in
+ *'"status":"green"'*)
+ t1=$(date +%s.%N)
+ BOOT_MS=$(python3 -c "print(int(($t1 - $t0) * 1000))")
+ # Never write into somebody else's node: a curl that succeeds while our
+ # process failed to bind means SOMEBODY ELSE answered. Same check as
+ # mbox-ingest/run.sh, run after green because the bind happens during
+ # startup, not at exec.
+ local listener
+ listener=$(ss -ltnp 2>/dev/null | grep -E ":$PORT\b" | grep -o 'pid=[0-9]*' | head -1 | cut -d= -f2 || true)
+ [ "$listener" = "$SERVER_PID" ] || { echo "refusing: :$PORT is held by pid ${listener:-?}, not by the node this script started ($SERVER_PID)"; exit 2; }
+ return 0 ;;
+ esac
+ kill -0 "$SERVER_PID" 2>/dev/null || { echo "node died while waiting for green; log:"; tail -20 "$1"; exit 1; }
+ sleep 0.2
+ done
+ echo "node never reached green within 60 s; log:"; tail -20 "$1"; exit 1
+}
+
+node_stop() { # graceful: SIGTERM runs flush_all_force on the way out
+ kill -TERM "$SERVER_PID" 2>/dev/null || true
+ for _ in $(seq 1 200); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.1; done
+ kill -9 "$SERVER_PID" 2>/dev/null || true
+ wait "$SERVER_PID" 2>/dev/null || true
+ SERVER_PID=""
+}
+
+# ── /proc sampling over a window (deltas, never spot samples) ───────────────
+# Wakeups are summed across /proc/<pid>/task/*/status, NOT read from
+# /proc/<pid>/status: the process-level counters describe the MAIN thread
+# only, and the main thread of this server parks after boot and never wakes
+# (every timer lives on a worker) — the process-level delta reads 0/s on a
+# node that is demonstrably ticking. Per-thread CPU (utime+stime grouped by
+# comm) rides along so a failing CPU line names its offender instead of
+# leaving a bare percentage.
+sample_window() { # $1 = pid, $2 = seconds, $3 = out json; echoes the json
+ python3 - "$1" "$2" "$3" <<'PY'
+import json, os, sys, time
+pid, secs, out = int(sys.argv[1]), float(sys.argv[2]), sys.argv[3]
+
+def sample():
+ stat = open(f"/proc/{pid}/stat").read()
+ rest = stat.rsplit(")", 1)[1].split() # after comm; [11],[12] = utime,stime
+ st = {}
+ for line in open(f"/proc/{pid}/status"):
+ k, _, v = line.partition(":")
+ st[k] = v.split()
+ def num(key): return int(st[key][0])
+ def cnt(path):
+ try: return len(os.listdir(f"/proc/{pid}/{path}"))
+ except OSError: return -1
+ vol = non = 0
+ tasks = {}
+ try: tids = os.listdir(f"/proc/{pid}/task")
+ except OSError: tids = []
+ for tid in tids:
+ try:
+ tstat = open(f"/proc/{pid}/task/{tid}/stat").read()
+ trest = tstat.rsplit(")", 1)[1].split()
+ comm = tstat.split(" (", 1)[1].rsplit(")", 1)[0]
+ tasks[tid] = (comm, int(trest[11]) + int(trest[12]))
+ tstatus = {
+ line.partition(":")[0]: line.partition(":")[2].split()
+ for line in open(f"/proc/{pid}/task/{tid}/status")
+ }
+ vol += int(tstatus["voluntary_ctxt_switches"][0])
+ non += int(tstatus["nonvoluntary_ctxt_switches"][0])
+ except (OSError, KeyError, IndexError, ValueError):
+ pass
+ return dict(t=time.monotonic(), utime=int(rest[11]), stime=int(rest[12]),
+ vol=vol, non=non, tasks=tasks,
+ rss_kb=num("VmRSS"), hwm_kb=num("VmHWM"),
+ rss_anon_kb=num("RssAnon"), rss_file_kb=num("RssFile"),
+ threads=cnt("task"), fds=cnt("fd"))
+
+a = sample(); time.sleep(secs); b = sample()
+elapsed = b["t"] - a["t"]
+clk = os.sysconf("SC_CLK_TCK")
+ticks = (b["utime"] - a["utime"]) + (b["stime"] - a["stime"])
+vol = b["vol"] - a["vol"]; non = b["non"] - a["non"]
+per_comm = {}
+for tid, (comm, ticks_then) in a["tasks"].items():
+ if tid in b["tasks"]:
+ d = b["tasks"][tid][1] - ticks_then
+ if d > 0:
+ name = b["tasks"][tid][0]
+ c = per_comm.setdefault(name, [0, 0])
+ c[0] += d; c[1] += 1
+top_threads = [
+ dict(comm=k, cpu_ticks=v[0], threads=v[1],
+ cpu_percent_of_one_core=round(100.0 * v[0] / clk / elapsed, 3))
+ for k, v in sorted(per_comm.items(), key=lambda kv: -kv[1][0])[:10]
+]
+res = dict(
+ pid=pid, window_s=round(elapsed, 1), clk_tck=clk, cpu_ticks=ticks,
+ cpu_percent_of_one_core=round(100.0 * ticks / clk / elapsed, 4),
+ wakeups_per_s=round((vol + non) / elapsed, 1),
+ voluntary_per_s=round(vol / elapsed, 1),
+ nonvoluntary_per_s=round(non / elapsed, 1),
+ rss_kb=b["rss_kb"], hwm_kb=b["hwm_kb"],
+ rss_anon_kb=b["rss_anon_kb"], rss_file_kb=b["rss_file_kb"],
+ threads=b["threads"], fds=b["fds"],
+ per_thread_cpu=top_threads,
+ loadavg_start=open("/proc/loadavg").read().split()[:3],
+)
+json.dump(res, open(out, "w"), indent=1)
+print(json.dumps(res))
+PY
+}
+
+echo "== idle-budget fixture =="
+echo " binary $XERJ_BIN ($("$XERJ_BIN" --version | head -1))"
+echo " port $PORT (private; +1 rest, +2 grpc)"
+echo " data dir $DATA (throwaway)"
+echo " corpus $REPOS repos x $DATASETS datasets = $N indices x 3 docs"
+echo " window ${SETTLE_SECS}s settle (+${DRAIN_SECS}s boot-tail drain)"
+echo " host $(uname -srm), nproc=$(nproc 2>/dev/null || echo '?'), load1=$(cut -d' ' -f1 /proc/loadavg)"
+echo
+
+# ── 0. corpus ───────────────────────────────────────────────────────────────
+bash "$HERE/gen_corpus.sh" "$DATA/corpus" "$REPOS" "$DATASETS" >&2
+
+# ── 1. baseline arm: empty node, same window (per-index RSS subtracts it) ───
+node_start "$DATA/node-base" "$DATA/base-boot.log"
+wait_green "$DATA/base-boot.log"
+BASE_BOOT_MS=$BOOT_MS
+sleep "$DRAIN_SECS"
+echo "== baseline arm (0 user indices): ${SETTLE_SECS}s window =="
+sample_window "$SERVER_PID" "$SETTLE_SECS" "$DATA/base-sample.json" > /dev/null
+node_stop
+
+# ── 2. load arm: one index per dataset, default settings ───────────────────
+node_start "$DATA/node-n" "$DATA/n-boot1.log"
+wait_green "$DATA/n-boot1.log"
+EMPTY_BOOT_MS=$BOOT_MS
+# Environmental normalization, not a behaviour change: the node's own disk
+# flood-stage watermark (95% used) blocks writes with 429 when the throwaway
+# dir lives on a nearly-full shared disk — it gates WRITE AVAILABILITY and has
+# nothing to do with the idle budget this fixture measures. Raise it to 99%
+# on this throwaway node (the runtime override the engine itself documents for
+# exactly this unblock) so a full sandbox cannot fail the run spuriously.
+curl -s -XPUT "$URL/_cluster/settings" -H 'content-type: application/json' \
+ -d '{"persistent":{"cluster.routing.allocation.disk.watermark.flood_stage":"99%"}}' \
+ -o /dev/null -w "flood-stage override PUT: %{http_code}\n" || true
+curl -s -XPUT "$URL/_all/_settings" -H 'content-type: application/json' \
+ -d '{"index.blocks.read_only_allow_delete": null}' \
+ -o /dev/null -w "index-block clear PUT: %{http_code}\n" || true
+# The override is applied by the node's resource sampler at the END of its
+# first tick, and the flood-stage latch releases on the tick AFTER that. A
+# first tick that lands after this PUT still engages the block with the
+# pre-override default for ~one tick (100 ms) — so first let a couple of
+# sampler periods pass, then probe with a DOCUMENT write (index creation does
+# not consult the disk block; a doc write is the gated operation) until the
+# node accepts one, and delete the probe index.
+sleep 2
+PROBE_ATTEMPTS=0
+for _ in $(seq 1 300); do
+ PROBE_CODE=$(curl -s -XPUT "$URL/idle-budget-write-probe/_doc/1" \
+ -H 'content-type: application/json' -d '{"probe":true}' -o /dev/null -w '%{http_code}' 2>/dev/null || true)
+ if [ "$PROBE_CODE" = 201 ] || [ "$PROBE_CODE" = 200 ]; then
+ echo "write probe accepted after $PROBE_ATTEMPTS refused attempt(s)"
+ curl -fs -XDELETE "$URL/idle-budget-write-probe" >/dev/null 2>&1 || true
+ break
+ fi
+ PROBE_ATTEMPTS=$((PROBE_ATTEMPTS + 1))
+ if [ $((PROBE_ATTEMPTS % 25)) = 0 ]; then echo " write probe still refused ($PROBE_ATTEMPTS x $PROBE_CODE)"; fi
+ sleep 0.1
+done
+echo "== loading $N indices over the ES wire (default settings) =="
+python3 - "$URL" "$DATA/corpus" <<'PY' >&2
+import csv, json, os, sys, urllib.request
+base, corpus = sys.argv[1], sys.argv[2]
+def req(method, path, body=None, ctype="application/json"):
+ r = urllib.request.Request(base + path, data=body.encode() if body else None, method=method)
+ if body: r.add_header("content-type", ctype)
+ try:
+ with urllib.request.urlopen(r, timeout=60) as resp:
+ return json.loads(resp.read().decode())
+ except urllib.error.HTTPError as e:
+ detail = e.read().decode(errors="replace")[:600]
+ print(f"{method} {path} -> {e.code}: {detail}", file=sys.stderr)
+ raise
+created = docs = 0
+for root, dirs, files in os.walk(corpus):
+ dirs.sort()
+ for f in sorted(files):
+ if not f.endswith(".csv"): continue
+ repo = os.path.basename(root); ds = f[:-4]
+ idx = f"idle-{repo}-{ds}"
+ req("PUT", f"/{idx}")
+ lines = []
+ with open(os.path.join(root, f), newline="") as fh:
+ reader = csv.reader(fh)
+ header = next(reader)
+ for row in reader:
+ lines.append(json.dumps({"index": {"_index": idx}}))
+ lines.append(json.dumps(dict(zip(header, row))))
+ resp = req("POST", "/_bulk", "\n".join(lines) + "\n", "application/x-ndjson")
+ if resp.get("errors"):
+ print(f"BULK ERRORS on {idx}: {json.dumps(resp)[:300]}", file=sys.stderr)
+ sys.exit(3)
+ created += 1; docs += len(lines) // 2
+ if created % 100 == 0: print(f" …{created} indices, {docs} docs")
+print(f"loaded {created} indices ({docs} docs)")
+PY
+# The engine's _cat/indices ignores ?h=index and always returns the full
+# table (health status first, index name third column) — count on $3.
+count_idle_indices() { curl -s "$URL/_cat/indices" | awk '$3 ~ /^idle-/ {n++} END {print n+0}'; }
+LOADED=$(count_idle_indices)
+[ "$LOADED" = "$N" ] || { echo "::error::expected $N idle-* indices after load, got $LOADED"; exit 1; }
+# flush_all: every memtable -> segment + WAL checkpoint; 200 means durable.
+curl -fs -XPOST "$URL/_flush" >/dev/null || { echo "::error::POST /_flush failed"; exit 1; }
+echo "flushed all indices; letting the 5 s merge debounce finish"
+sleep 10
+node_stop
+
+# ── 3. restart on the cleanly-flushed corpus: boot + WAL-replay gates ──────
+node_start "$DATA/node-n" "$DATA/n-boot2.log"
+wait_green "$DATA/n-boot2.log"
+N_BOOT_MS=$BOOT_MS
+REPLAY_LINES=$(grep -c 'replayed WAL entries' "$DATA/n-boot2.log" || true)
+COUNTED=$(count_idle_indices)
+# one doc probe: the corpus is real docs that survived the restart, not empty dirs
+PROBE=$(python3 -c "
+import json, urllib.request
+j = json.load(urllib.request.urlopen('$URL/idle-repo-01-ds_001/_search?size=0', timeout=10))
+print(j['hits']['total']['value'] if isinstance(j['hits']['total'], dict) else j['hits']['total'])
+")
+[ "$PROBE" = 3 ] || { echo "::error::doc probe returned $PROBE hits on idle-repo-01-ds_001, expected 3 (corpus did not survive the flush+restart)"; exit 1; }
+
+# ── 4. the measurement window ───────────────────────────────────────────────
+sleep "$DRAIN_SECS"
+echo "== measurement arm ($COUNTED indices): ${SETTLE_SECS}s window =="
+sample_window "$SERVER_PID" "$SETTLE_SECS" "$DATA/n-sample.json" > /dev/null
+node_stop
+
+# ── 5. math + gate + results ────────────────────────────────────────────────
+BASE_JSON="$DATA/base-sample.json" N_JSON="$DATA/n-sample.json" \
+N_INDICES="$COUNTED" EXPECTED_INDICES="$N" BASE_BOOT_MS="$BASE_BOOT_MS" \
+EMPTY_BOOT_MS="$EMPTY_BOOT_MS" N_BOOT_MS="$N_BOOT_MS" REPLAY_LINES="$REPLAY_LINES" \
+PROBE_HITS="$PROBE" GATE_CPU_PERCENT="$GATE_CPU_PERCENT" \
+GATE_WAKEUPS_PER_S="$GATE_WAKEUPS_PER_S" GATE_RSS_PER_INDEX_KB="$GATE_RSS_PER_INDEX_KB" \
+GATE_BOOT_MS="$GATE_BOOT_MS" LABEL="$LABEL" RESULTS_DIR="$RESULTS_DIR" \
+BIN_VERSION="$("$XERJ_BIN" --version | head -1)" BIN_PATH="$(readlink -f "$XERJ_BIN")" \
+CORPUS_SHAPE="${REPOS}x${DATASETS}" PORT="$PORT" \
+python3 - <<'PY'
+import json, os, sys
+
+env = os.environ
+base = json.load(open(env["BASE_JSON"]))
+n = json.load(open(env["N_JSON"]))
+N = int(env["N_INDICES"]); expected = int(env["EXPECTED_INDICES"])
+
+per_index_kb = (n["rss_kb"] - base["rss_kb"]) / N
+out = dict(
+ label=env["LABEL"], date_utc=__import__("datetime").datetime.now(__import__("datetime").timezone.utc).isoformat(timespec="seconds"),
+ binary=dict(version=env["BIN_VERSION"], path=env["BIN_PATH"]),
+ corpus=dict(shape=env["CORPUS_SHAPE"], indices=N, docs_per_index=3),
+ port=int(env["PORT"]),
+ window_s=n["window_s"], settle_target_s=float(os.environ.get("SETTLE_SECS", 120)),
+ boot_ms=dict(empty_node=int(env["EMPTY_BOOT_MS"]), baseline_arm=int(env["BASE_BOOT_MS"]), n_indices=int(env["N_BOOT_MS"])),
+ wal_replay_lines_after_clean_flush=int(env["REPLAY_LINES"]),
+ doc_probe_hits=int(env["PROBE_HITS"]),
+ baseline=base, measurement=n,
+ per_index_rss_kb=round(per_index_kb, 1),
+)
+path = os.path.join(env["RESULTS_DIR"], f"result-{env['LABEL']}.json")
+json.dump(out, open(path, "w"), indent=1)
+
+print()
+print("== measured ==")
+print(f" boot-to-green, empty node {out['boot_ms']['empty_node']:>8} ms")
+print(f" boot-to-green, {N:>4} indices {out['boot_ms']['n_indices']:>8} ms (cleanly-flushed corpus)")
+print(f" WAL replay lines after flush {out['wal_replay_lines_after_clean_flush']:>8} (0 = nothing to replay)")
+print(f" idle CPU, {N:>4} indices {n['cpu_percent_of_one_core']:>8} % of one core (window {n['window_s']}s)")
+print(f" idle CPU, baseline node {base['cpu_percent_of_one_core']:>8} % of one core")
+print(f" wakeups/s, {N:>4} indices {n['wakeups_per_s']:>8} /s (voluntary {n['voluntary_per_s']}/s + nonvoluntary {n['nonvoluntary_per_s']}/s)")
+print(f" wakeups/s, baseline node {base['wakeups_per_s']:>8} /s")
+print(f" VmRSS, {N:>4} indices {n['rss_kb']:>8} kB (VmHWM {n['hwm_kb']} kB; anon {n['rss_anon_kb']} kB + file {n['rss_file_kb']} kB)")
+print(f" VmRSS, baseline node {base['rss_kb']:>8} kB")
+print(f" per-index idle RSS {per_index_kb:>8.1f} kB (({n['rss_kb']} - {base['rss_kb']}) / {N})")
+print(f" threads {n['threads']}, fds {n['fds']}, loadavg {n['loadavg_start']}")
+print(f" results: {path}")
+
+# ── the gate: coarse lines, ::error:: + FAIL, exit code ────────────────────
+print()
+print("== gate (coarse thresholds; the point is catching O(N) regressions, not ±1%) ==")
+FAIL = 0
+def gate(claimed, measured, ok, detail=""):
+ global FAIL
+ verdict = "ok" if ok else "FAIL"
+ if not ok:
+ FAIL = 1
+ print(f"::error::idle-budget: {claimed} — measured {measured}{detail}")
+ print(f" {'ok ' if ok else 'FAIL'} CLAIMED {claimed}")
+ print(f" MEASURED {measured}{detail}")
+
+gate(f"idle CPU < {env['GATE_CPU_PERCENT']} % of one core (any N)",
+ f"{n['cpu_percent_of_one_core']} % over {n['window_s']}s",
+ n["cpu_percent_of_one_core"] < float(env["GATE_CPU_PERCENT"]))
+gate(f"wakeups < {env['GATE_WAKEUPS_PER_S']}/s process-wide (any N)",
+ f"{n['wakeups_per_s']}/s (vol {n['voluntary_per_s']} + nonvol {n['nonvoluntary_per_s']})",
+ n["wakeups_per_s"] < float(env["GATE_WAKEUPS_PER_S"]))
+gate(f"per-index idle RSS <= {env['GATE_RSS_PER_INDEX_KB']} kB (0.2 MB; total vs N)",
+ f"{per_index_kb:.1f} kB = ({n['rss_kb']} - {base['rss_kb']}) / {N}",
+ per_index_kb <= float(env["GATE_RSS_PER_INDEX_KB"]))
+gate(f"boot-to-green < {env['GATE_BOOT_MS']} ms on a cleanly-flushed {N}-index corpus",
+ f"{out['boot_ms']['n_indices']} ms (empty node boots in {out['boot_ms']['empty_node']} ms)",
+ out["boot_ms"]["n_indices"] < int(env["GATE_BOOT_MS"]))
+gate("no O(corpus) WAL replay after a clean flush",
+ f"{out['wal_replay_lines_after_clean_flush']} 'replayed WAL entries' lines in the restart log",
+ out["wal_replay_lines_after_clean_flush"] == 0)
+if N != expected:
+ print(f"::error::idle-budget: expected {expected} indices, fixture counted {N}")
+ print(f" FAIL CLAIMED {expected} indices")
+ FAIL = 1
+else:
+ print(f" ok CLAIMED {expected} indices")
+ print(f" MEASURED {N} (doc probe: {out['doc_probe_hits']} hits on one index)")
+
+print()
+if FAIL:
+ print("IDLE-BUDGET GATE FAILED — see the ::error:: lines above")
+ sys.exit(1)
+print("IDLE-BUDGET GATE PASSED")
+PY
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 9bbe1d331..bc49c0130 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -40779,24 +40779,45 @@ async fn real_node_search_index_totals(state: &AppState) -> (u64, u64, u64, u64)
(q_total, q_ms, i_total, i_ms)
}
-/// Refresh the process-level Prometheus gauges from live engine state. Reads
-/// only cheap snapshots (a lock-free store RCU snapshot per index plus a stat
-/// of each WAL dir), so it is safe to call on a short interval.
-async fn refresh_metric_gauges(state: &AppState) {
+/// Refresh the process-level Prometheus gauges from live engine state, on
+/// demand. The `/v1/metrics` handler calls this at scrape time (#874): a
+/// scrape is the only moment these gauges are observable, so paying there
+/// makes them live exactly when they can be read and free the rest of the
+/// time.
+///
+/// This replaced a 10 s background loop whose per-tick work was this same
+/// function running whether anyone read the values or not. That is not
+/// "cheap snapshots" at every scale: `dir_size_bytes` over each index's WAL
+/// subtree is one `read_dir` plus one `metadata()` per WAL file (~16 shards
+/// per index by default), i.e. O(indices x wal shards) of real filesystem
+/// metadata work on an async runtime worker — an idle CPU cost that grows
+/// with index count, measured at ~0.7 % of one core for 450 idle indices on
+/// the at-rest fixture (benchmarks/idle-budget/README.md). The walk now runs
+/// on the blocking pool, never on a runtime worker, and only on scrape.
+pub(crate) async fn refresh_metric_gauges(state: &AppState) {
let indices = state.engine.list_indices().await;
let mut total_docs: i64 = 0;
- let mut total_segments: i64 = 0;
- let mut wal_bytes: i64 = 0;
+ let mut handles = Vec::with_capacity(indices.len());
for info in &indices {
total_docs += info.doc_count as i64;
if let Ok(idx) = state.engine.get_index(&info.name) {
+ handles.push(idx);
+ }
+ }
+ let (total_segments, wal_bytes) = tokio::task::spawn_blocking(move || {
+ let mut total_segments: i64 = 0;
+ let mut wal_bytes: i64 = 0;
+ for idx in &handles {
total_segments += idx.store_snapshot().segments.len() as i64;
// WAL files live under `<index>/wal/*.wal`; sum just that subtree so
// the gauge tracks WAL growth (the WAL-runaway ticket) and not the
// segments alongside it.
wal_bytes += dir_size_bytes(&idx.data_dir().join("wal")) as i64;
}
- }
+ (total_segments, wal_bytes)
+ })
+ .await
+ .unwrap_or((0, 0));
state.metrics.doc_count.set(total_docs);
state.metrics.segment_count.set(total_segments);
state.metrics.wal_size_bytes.set(wal_bytes);
@@ -40806,23 +40827,6 @@ async fn refresh_metric_gauges(state: &AppState) {
}
}
-/// Background loop that refreshes the Prometheus gauges
-/// (`doc_count` / `segment_count` / `wal_size_bytes` / `memory_usage`) every
-/// 10 s. These are otherwise never written, so before this task `/metrics`
-/// reported them as a flat zero even at millions of docs — hiding exactly the
-/// RSS-runaway and WAL-growth signals operators need. The server spawns this
-/// once at startup. `tokio::time::interval` fires its first tick immediately,
-/// so the gauges are populated on the first pass rather than reading zero for
-/// the first 10 s.
-pub async fn run_metrics_gauge_loop(state: AppState) {
- let mut ticker = tokio::time::interval(std::time::Duration::from_secs(10));
- ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
- loop {
- ticker.tick().await;
- refresh_metric_gauges(&state).await;
- }
-}
-
#[cfg(test)]
mod scripted_update_tests {
use super::*;
diff --git a/engine/crates/xerj-api/src/native.rs b/engine/crates/xerj-api/src/native.rs
index d927a1f68..f6178012d 100644
--- a/engine/crates/xerj-api/src/native.rs
+++ b/engine/crates/xerj-api/src/native.rs
@@ -1173,6 +1173,16 @@ pub async fn metrics(State(state): State<AppState>) -> impl IntoResponse {
// lives at the API layer). Cheap: a sum over the open-index set.
let (qc_hits, qc_misses) = state.engine.query_cache_totals();
state.metrics.set_query_cache(qc_hits, qc_misses);
+ // #874: doc_count / segment_count / wal_size_bytes / memory_usage refresh
+ // here too, at scrape time, the same way. A 10 s background loop used to
+ // feed them; its per-tick walk of every index's WAL subtree (one stat()
+ // per WAL shard, on an async runtime worker) was an idle CPU cost that
+ // scales with index count — ~0.7 % of one core at 450 idle indices,
+ // measured in benchmarks/idle-budget/README.md. A scrape is the only
+ // moment these gauges are observable, so refreshing here keeps them live
+ // exactly when they can be read and costs nothing in between. The WAL
+ // walk itself runs on the blocking pool (see refresh_metric_gauges).
+ crate::es_compat::refresh_metric_gauges(&state).await;
match state.metrics.gather_text() {
Ok(text) => (
StatusCode::OK,
diff --git a/engine/crates/xerj-api/tests/metrics_gauges_refresh_at_scrape_time.rs b/engine/crates/xerj-api/tests/metrics_gauges_refresh_at_scrape_time.rs
new file mode 100644
index 000000000..efefc69c4
--- /dev/null
+++ b/engine/crates/xerj-api/tests/metrics_gauges_refresh_at_scrape_time.rs
@@ -0,0 +1,102 @@
+//! #874: the Prometheus gauges (`xerj_doc_count` / `xerj_segment_count` /
+//! `xerj_wal_size_bytes` / `xerj_memory_usage_bytes`) must be live at scrape
+//! time — and must not be fed by a background loop.
+//!
+//! They used to be written by a 10 s ticker whose per-tick work walked every
+//! index's WAL subtree (`read_dir` + one `metadata()` per WAL shard — ~16 per
+//! index at default sharding) on an async runtime worker. That is an idle CPU
+//! cost that scales with index count: measured ~0.7 % of one core for 450
+//! idle indices on the at-rest fixture (benchmarks/idle-budget/README.md),
+//! against issue #874's < 0.5 % budget. The loop is gone; the `/v1/metrics`
+//! handler refreshes the gauges itself.
+//!
+//! Fail-before shape: with the loop deleted and nothing refreshing at scrape
+//! time, this test reports `xerj_doc_count 0` on a node holding documents —
+//! exactly the "flat zero at millions of docs" regression the loop was
+//! originally added to fix, so this pins BOTH properties: live when scraped,
+//! idle the rest of the time.
+
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::json;
+use tower::ServiceExt;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+
+async fn app() -> (axum::Router, tempfile::TempDir) {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+
+ let mut schema = Schema::empty();
+ schema
+ .add_field(FieldConfig::new("body", FieldType::Text))
+ .expect("body");
+ state.engine.create_index("docs", schema).expect("create");
+ let idx = state.engine.get_index("docs").expect("get");
+ for i in 0..5 {
+ idx.index_document(
+ Some(format!("d{i}")),
+ json!({"body": format!("document number {i} with searchable prose")}),
+ )
+ .await
+ .expect("index");
+ }
+ idx.refresh().await.expect("refresh");
+ (xerj_api::router::build_es_compat_router(state), dir)
+}
+
+/// Last whitespace-separated field of the metric's sample line (Prometheus
+/// text exposition: `name value`), skipping the `# HELP`/`# TYPE` lines.
+fn gauge_value(text: &str, name: &str) -> Option<i64> {
+ text.lines()
+ .find(|l| l.starts_with(name) && !l.starts_with('#'))
+ .and_then(|l| l.rsplit(' ').next())
+ .and_then(|v| v.parse().ok())
+}
+
+#[tokio::test]
+async fn scrape_reports_live_gauges_without_a_background_loop() {
+ let (app, _dir) = app().await;
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri("/v1/metrics")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .expect("oneshot");
+ assert_eq!(response.status(), StatusCode::OK);
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let text = String::from_utf8_lossy(&bytes).into_owned();
+
+ // doc_count must count the 5 documents indexed above (plus whatever the
+ // system indices hold — hence >=, not ==). Before the scrape-time
+ // refresh, this read 0 the moment the background loop was gone.
+ let docs = gauge_value(&text, "xerj_doc_count")
+ .unwrap_or_else(|| panic!("xerj_doc_count missing from /v1/metrics:\n{text}"));
+ assert!(docs >= 5, "xerj_doc_count = {docs}, expected >= 5:\n{text}");
+
+ // One refreshed index => at least one segment; the WAL gauge must be
+ // present and parseable (its value depends on the wal_sync mode).
+ let segments = gauge_value(&text, "xerj_segment_count")
+ .unwrap_or_else(|| panic!("xerj_segment_count missing from /v1/metrics:\n{text}"));
+ assert!(
+ segments >= 1,
+ "xerj_segment_count = {segments}, expected >= 1"
+ );
+ assert!(
+ gauge_value(&text, "xerj_wal_size_bytes").is_some(),
+ "xerj_wal_size_bytes missing from /v1/metrics:\n{text}"
+ );
+ assert!(
+ gauge_value(&text, "xerj_memory_usage_bytes").is_some(),
+ "xerj_memory_usage_bytes missing from /v1/metrics:\n{text}"
+ );
+}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 1b5e4786a..e34834bd7 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -2446,13 +2446,15 @@ async fn async_main() -> Result<()> {
// flush/merge/WAL/index-latency observations into — the flush, merge
// and WAL write sites live deep in xerj-engine, which is built before
// `Metrics` exists and holds no handle to it.
- // (b) Spawn the 10 s gauge refresher that keeps doc_count / segment_count
- // / wal_size_bytes / memory_usage live (otherwise a flat zero even at
- // millions of docs, hiding the RSS-runaway and WAL-growth signals).
+ // (b) used to spawn a 10 s gauge refresher here. #874 removed it: its
+ // per-tick cost walked every index's WAL subtree on an async runtime
+ // worker — O(indices x wal shards) of stat()s whether anyone read the
+ // values or not, ~0.7 % of one core at 450 idle indices (measured in
+ // benchmarks/idle-budget/README.md). The /v1/metrics handler now
+ // refreshes doc_count / segment_count / wal_size_bytes / memory_usage
+ // at scrape time, so the gauges are live exactly when they are
+ // observable and cost nothing while nobody is looking.
xerj_engine::set_engine_metrics(state.metrics.clone());
- if storage_available {
- tokio::spawn(xerj_api::es_compat::run_metrics_gauge_loop(state.clone()));
- }
// 9b-2. WAL tap (issue #320) — one-directional push of an allowlisted
// index subset to an external ES-compatible target. The loop always