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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(engine): #948 — prune published memtable entries, charge what they retain, bound merge batches, drain on breaker
xerj-org6c96c96853d5
diff --git a/benchmarks/mbox-ingest/README.md b/benchmarks/mbox-ingest/README.mdindex 667debe3e..51ef5bd82 100644--- a/benchmarks/mbox-ingest/README.md+++ b/benchmarks/mbox-ingest/README.md@@ -329,6 +329,193 @@ an inference, not profiled. Server VmHWM after the passes: ~13.5 GB in bothconfigurations, for a 760 MB index. The seconds are upper bounds (sharedbox); the ~1000× split is not a load effect. Engine-side, appended to #948.+## The engine fix for #948 — base vs fixed, measured on this box++Everything above documents the problem, on the mbox-branch binaries. This+section is the engine-side fix, measured as a strict pair: **base** =+`origin/main` at `9c64a7c6`, **fixed** = that commit plus this branch's engine+changes, both built `cargo build --profile ci-test -p xerj-server`, both run+through the same harness with the same flags, sequentially, on this box+(2026-09-21, 1-min load 0.2–3.2 during the runs below). Result files:+[`results/fix-*.json`](./results/) and [`results/fix-atrest-bisect.txt`](./results/).++What changed in the engine (details in the commit):++1. **The leak** — `IndexStore::memtable_shards` retained one parsed+ `Arc<serde_json::Value>` per explicit-id write for the life of the process:+ the engine's flush path drains the FTS memtable and finalises from *that*,+ so the storage-side shards were never emptied. `prune_published_memtable()`+ now runs at the end of every successful flush finalise and drops entries the+ version map has repointed at a real segment.+2. **The accounting lie** — a raw-bytes (turbo `_bulk`) memtable entry charged+ a flat 800 bytes regardless of payload (a ~10 KB mailbox doc counted as+ 800), and the explicit-id path charged a full JSON re-serialisation. Both+ now charge what the entry retains; the 800-byte floor keeps the compressed+ log-doc cadence byte-for-byte (the M5.17 regression stays fixed).+3. **Merge batches are bounded by input bytes** (`clamp(cap/64, 32, 512) MiB`,+ `XERJ_MERGE_BATCH_MAX_INPUT_MB` overrides) — the executor materialises+ decoded + re-encoded copies of every input doc, measured 5–9× input bytes,+ so a count-chunked batch of large segments is an unbounded spike. Forcemerge+ chunking obeys the same cap. Peers bound the same thing by memory+ (quickwit `quickwit-parquet-engine/src/storage/streaming_writer.rs:378`,+ `…/merge/streaming.rs:148`; tantivy sizes candidates before batching,+ `src/indexer/log_merge_policy.rs:22,94`).+4. **The breaker now drains, not just rejects** — when the parent RSS breaker+ engages, the sampler requests a drain of every loaded index (flush ++ release rebuildable caches + a jemalloc `arena.4096.purge` hook installed by+ the server), rate-limited to one per 2 s while engaged; publish-warming is+ skipped while it is engaged. A breaker that only 429s frees nothing.+5. **The ingest-memory ledger now sees the caches and merges** — the segment+ hydration cache is charged at admission, the merge executor charges its+ decoded/survivor/json-buffer/parsed/encoded buffers, so the ledger's view+ and RSS agree where they used to diverge by gigabytes.++### At-rest retention — the leak, isolated ([raw](./results/fix-atrest-bisect.txt))++[`atrest_bisect.sh`](./atrest_bisect.sh) loads mailbox-shaped docs straight+through ES `_bulk` ([`synth_bulk_ingest.py`](./synth_bulk_ingest.py) — the+record shape without autoindex's catalog/brain/edge traffic), flushes, waits+45 s, and reads the node's `VmRSS`/`VmHWM` from `/proc`. Variant A: 20,000+docs × 10 KB body ≈ 210 MB of source, cap lifted (`65536`) so the breaker+never gates the load.++| variant A, 20k × 10 KB | base | fixed |+|---|---|---|+| idle before load | 135.5 MiB | 131.4 MiB |+| post-flush RSS | 1,361.3 MiB | 860.7 MiB |+| **settled RSS (45 s after flush)** | **972.8 MiB** | **481.4 MiB** |+| VmHWM over the whole run | 1,944.1 MiB | 1,941.7 MiB |+| RSS after DELETE of the index | 226.9 MiB | 199.0 MiB |+| **settled retention** (settled − after-delete) | **~764 MB** | **~289 MB** |++The ledger explains the difference exactly: at settle, the base run's RSS is+~935 MB of which the ledger can account for ~272 MB (the segment-hydration+cache) — **~533 MB is invisible to every category**, which is the storage+memtable's per-doc `Arc<Value>` trees (~2.5× the 210 MB source). On the fixed+binary the unattributed remainder is **~3 MB**; what is left at rest is the+rebuildable hydration cache, which a drain or a delete releases. The fixed+side's settled figure reproduced across three independent runs (481.4, 481+and 488.2 MiB; the third, on 2026-09-21, had its load pacing shaped by the+box's disk-flood retry grind — see the note under variant C — and settled+within 7 MiB of the others). The **peak** barely moves (1.94 GiB both+sides): the leak was retention, not the transient working set.++### Variant C — the same leak, per document ([raw](./results/fix-atrest-bisect.txt))++Variant C holds the source at ~10 MB but raises the count: 100,000 docs ×+100 B bodies. This isolates the per-document component of the retention+(variant A isolates the per-byte one).++| variant C, 100k × 100 B (~10 MB source) | base | fixed |+|---|---|---|+| idle before load | 127.7 MiB | 126.4 MiB |+| post-flush RSS | 1,575.0 MiB | 1,352.9 MiB |+| **settled RSS (45 s after flush)** | **883.0 MiB** | **280.8 MiB** |+| VmHWM over the whole run | 1,973.8 MiB | 1,570.9 MiB |+| RSS after DELETE of the index | 205.9 MiB | 172.8 MiB |+| **settled retention** (settled − after-delete) | **~677 MB** | **~108 MB** |++A 10 MB source leaving ~677 MB resident at rest is ~7 KB retained per+100-byte document on the base — the parsed per-doc `Arc<Value>` trees again,+this time counted per head instead of per byte. At this document count the+leak is big enough to move the peak too (−403 MiB VmHWM). Both sides landed+exactly 100,000 documents (the loader reports `docs_sent` = `node_count` =+requested; the base side needed 8 retry rounds, the fixed side 2).++A note on the 2026-09-21 re-runs: the shared box's root filesystem sat at+97–98 % (other tenants' data), which crosses the node's 95 %+`disk.watermark.flood_stage` at boot and puts it in `read_only_allow_delete`.+The throwaway nodes for these re-runs were unblocked with the documented+transient cluster setting+(`PUT _cluster/settings {"transient":{"cluster.routing.allocation.disk.watermark.flood_stage":"99%"}}`),+which changes no retention behaviour — only which writes are admitted. The+variant A re-run's wall time (1,472 s, 147 retry rounds) is that grind and is+not comparable to anything; every RSS/retention figure above is measured+after the load had fully landed.++Merge-side attribution, same run, fixed binary only (the wiring is part of the+fix; base reports the categories `unavailable`): for a ~290 MB-on-disk index+the biggest merge batch peaked at 135.4 MB survivors + 134.6 MB re-encoded+JSON buffer + 155.0 MB parsed FTS input + 12.9 MB decoded stored + 33.2 MB+compressed output — a few hundred MB of working set, which is what change 3+now bounds by input bytes instead of leaving to segment count.++### 300 MB at a laptop's 8 GiB cap ([base](./results/fix-mixed-300M-cap8g-base.json), [fixed](./results/fix-mixed-300M-cap8g-fixed.json))++`XERJ_MAX_PROCESS_MEMORY_MB=8192`, same tree (seed 42, 30,403 documents),+every planted needle checked.++| | base | fixed |+|---|---|---|+| exit | 3 (complete) | 3 (complete) |+| wall | 66.5 s | 73.0 s |+| documents | 30,403 | 30,403 |+| server VmHWM | **14,766.6 MiB (1.8× the cap)** | **7,963.6 MiB (under the 8,192 MiB cap)** |+| breaker engagements | **178** | **2** |+| memtable flushes / merges | 140 / 10 | 129 / 9 |+| verify | 735/735 needles, 0 missing; `replies_to` 5,992 = truth; `attachment_of` 11,169 = attachment docs; sender 40/40; subject-in-body 40/40 | identical, figure for figure |++The fixed node still touches the watermark once (RSS 8,027 MB as the node logs+it) — but the drain fires, RSS comes back down, and the run finishes inside+its cap instead of 1.8× outside it. On a real 16 GiB laptop the base numbers+mean swap or an OOM kill; the fixed numbers fit.++### 1 GB at the default 16 GiB cap — the run from the issue ([base](./results/fix-mixed-1G-capped16g-base.json), [fixed](./results/fix-mixed-1G-capped16g-fixed.json))++Same tree as run B above (seed 42, 40,799 mbox entries, 2,530 planted needles,+21,544 resolvable replies), same harness, run sequentially on 2026-09-20+(1-min load 1.5–5.5). This is the pair that answers #948's title.++| | base (`9c64a7c6`) | fixed |+|---|---|---|+| exit | **1 — aborted** (breaker 429 after the 600 s re-offer budget) | **3 — complete** |+| wall | 817.1 s (the 600 s patience, then the abort) | **407.7 s** |+| documents on node | 85,722 of ~107k (the tail was never sent) | **107,698** (107,668 mbox records, 39,619 attachment docs) |+| server VmHWM | 25,356.9 MiB | **21,405.3 MiB — still 1.3× the 16,384 MiB cap** |+| breaker engagements | 31 | 24 |+| needles | 2,020 of 2,530 (510 missing, 0 wrong) | **2,530 of 2,530, 0 missing, 0 duplicated, 0 wrong** (1 in overlapping sections) |+| `replies_to` / `attachment_of` | **0 / 0** (edges are written after a file's nodes land) | **21,544 = truth / 39,619 = attachment docs** |+| subjects in `body` | 40/40 | 40/40 |+| verify latency | median 6.5 ms, p95 7.5 ms, 2 requests over 10 s | median 9.2 ms, **p95 5.54 s, 509 over 1 s, max 71.5 s** |++**The capped 1 GB mailbox now completes, and its content is complete and+correct.** The fixed node crossed the finish line with every needle, every+edge, and both index-level checks green, in half the base's wall time (the+base number is 600 s of waiting plus the abort). The `sender_filter` row is+absent from the table on purpose: on the fixed run it reports `sampled: 0`+while the base reported 40/40 — investigated, and it is a verify-time+artifact, not data loss. `verify.py` samples senders with a terms aggregation+on `email_from_address`, the single most expensive request it makes (47.5 s+cold, server-side `timed_out: true`, on this index with the cap lifted and the+node otherwise idle); during the run's verify the node was under the cap and+draining every ~2 s, the aggregation request failed, and `verify.py`'s+`post()` swallows errors, so `buckets()` read `[]`. Re-booted on a byte copy+of the fixed run's data dir with the cap lifted, the same aggregation returns+40 buckets and **all 40 sender checks pass** (`term` count = display-form+count, 0 mismatches). The data was on disk the whole time.++### What the fix does not fix — measured, not guessed++- **The 1 GB run's peak still exceeds its own cap.** 21,405 MiB VmHWM against+ a 16,384 MiB cap. The drain keeps the run *completing* (the base aborted at+ 87 % with 25,357 MiB); it does not make the ingest fit inside 16 GiB. The+ remaining peak is the read/merge working set under pressure, not the leak+ (see the at-rest table: the leak was retention, and the transient peak+ barely moves).+- **Verify-time reads under the cap thrash.** p95 5.54 s and 509 of 2,619+ requests over 1 s on the fixed 1 GB node (base: p95 7.5 ms), because the+ drain that frees memory also drops the segment-hydration cache that reads+ were relying on, and the next read re-hydrates it. Median latency is still+ 9.2 ms; the tail is the cost. This is the #948 read-side story+ (`segment_loop` first-query latency) wearing the drain's clothes.+- **At-rest VmHWM for a 210 MB load is unchanged** (~1.94 GiB both sides):+ the fix recovered the *settled* floor (972.8 → 481.4 MiB), not the+ high-water mark the load passes through.+- **The sender `sampled: 0` above** — a `verify.py` robustness gap (it+ swallows request errors and reports empties) triggered by real drain+ pressure. The index was correct; the verifier could not tell the+ difference. Not fixed here.+## What this says, plainly- **The extractor is correct on this corpus and cheap.** Under 300 MiB ofdiff --git a/benchmarks/mbox-ingest/atrest_bisect.sh b/benchmarks/mbox-ingest/atrest_bisect.shnew file mode 100755index 000000000..fbb0ead60--- /dev/null+++ b/benchmarks/mbox-ingest/atrest_bisect.sh@@ -0,0 +1,90 @@+#!/usr/bin/env bash+# Issue #948 experiment: the at-rest retention bisection.+#+# Loads mailbox-shaped docs via ES _bulk into a throwaway node, flushes,+# settles, then reports VmRSS/VmHWM and the ingest-memory ledger's view+# (jemalloc allocated/active/resident). Variants separate per-doc from+# per-byte retention:+# A 20k docs x 10 KB body (~210 MB source)+# B 20k docs x 100 B body (~2 MB source)+# C 100k docs x 100 B body (~10 MB source, 5x docs of B)+set -euo pipefail+PORT=${PORT:-9341}+WORK=$(mktemp -d /tmp/948-atrest.XXXXXX)+VARIANT=${1:-A}+case "$VARIANT" in+ A) DOCS=20000; BODY_KB=10;;+ B) DOCS=20000; BODY_KB=0;;+ C) DOCS=100000; BODY_KB=0;;+ *) echo "variant must be A|B|C"; exit 2;;+esac+# BODY_KB=0 -> tiny bodies: patch via --body-kb 0 in the generator = 0*1024+# bytes target; body() would return empty string. Give it 100 B instead.+# Binary under test: default = the worktree build; override for A/B, e.g.+# XERJ=/root/948-runs/bin/xerj-draft-citest ./atrest_bisect.sh A # main+# XERJ=/root/948-runs/bin/xerj-948-fixed ./atrest_bisect.sh A # fixed+XERJ=${XERJ:-/root/xerj-main/engine/target-b/ci-test/xerj}+HERE=$(cd "$(dirname "$0")" && pwd)+URL=http://127.0.0.1:$PORT++cat > "$WORK/node.toml" <<TOML+[server]+es_compat_port = $PORT+rest_port = $((PORT+1))+grpc_port = $((PORT+2))+data_dir = "$WORK/data"+[tls]+enabled = false+[embedding]+mode = "lexical"+TOML+mkdir -p "$WORK/data"++# No memory cap (large limit): the breaker must not 429 the load — we want+# the retention, not the pressure behaviour, in this experiment.+XERJ_MAX_PROCESS_MEMORY_MB=65536 \+XERJ_INGEST_MEMORY_TRACE=summary \+XERJ_INGEST_MEMORY_SAMPLE_MS=1000 \+XERJ_INGEST_MEMORY_OUTPUT="$WORK/ledger.ndjson" \+nohup "$XERJ" -c "$WORK/node.toml" --embed-mode lexical > "$WORK/server.log" 2>&1 &+SERVER=$!+cleanup() { kill "$SERVER" 2>/dev/null || true; wait "$SERVER" 2>/dev/null || true; }+trap cleanup EXIT++KEY=""+for _ in $(seq 1 120); do+ [ -s "$WORK/data/admin.key" ] && KEY=$(cat "$WORK/data/admin.key")+ [ -n "$KEY" ] && curl -fsS -H "Authorization: ApiKey $KEY" "$URL/_cluster/health" >/dev/null 2>&1 && break+ sleep 0.5+done+curl -fsS -H "Authorization: ApiKey $KEY" "$URL/_cluster/health" >/dev/null || { echo "node did not come up"; tail -5 "$WORK/server.log"; exit 1; }+LISTENER=$(ss -ltnp 2>/dev/null | grep -E ":$PORT\b" | grep -o 'pid=[0-9]*' | head -1 | cut -d= -f2)+[ "$LISTENER" = "$SERVER" ] || { echo "refusing: :$PORT held by pid ${LISTENER:-?} not $SERVER"; exit 2; }++rss() { awk '/^VmRSS:/{print $2}' "/proc/$SERVER/status"; }+hwm() { awk '/^VmHWM:/{print $2}' "/proc/$SERVER/status"; }+echo "variant=$VARIANT docs=$DOCS body_kb=$BODY_KB idle_rss_kb=$(rss) idle_hwm_kb=$(hwm)"++python3 "$HERE/synth_bulk_ingest.py" --url "$URL" --docs "$DOCS" --body-kb "$BODY_KB" \+ --bulk-mb 8 --key "$WORK/data/admin.key" --json > "$WORK/load.json" || {+ cat "$WORK/load.json"; tail -20 "$WORK/server.log"; exit 3; }+cat "$WORK/load.json"++# Explicit flush, then settle: merges (if any) finish, sampler records at-rest.+curl -fsS -X POST -H "Authorization: ApiKey $KEY" "$URL/bench-docs/_flush" >/dev/null+echo "post-flush rss_kb=$(rss)"+sleep 45+echo "settled rss_kb=$(rss) hwm_kb=$(hwm)"+echo "cache/view stats:"; curl -fsS -H "Authorization: ApiKey $KEY" "$URL/bench-docs/_stats" > "$WORK/stats.json" || true; wc -c < "$WORK/stats.json"+echo "index bytes on disk: $(du -sk "$WORK/data" | cut -f1) kB"++# Retention release test: does deleting the index return the pages?+BEFORE_DEL=$(rss)+curl -fsS -X DELETE -H "Authorization: ApiKey $KEY" "$URL/bench-docs" >/dev/null || true+sleep 10+echo "after-delete rss_kb=$(rss) (was $BEFORE_DEL before delete)"++# Ledger tail: last snapshot line (at-rest view).+echo "ledger last snapshot:"+tail -2 "$WORK/ledger.ndjson" | head -1 | python3 -c 'import json,sys; d=json.loads(sys.stdin.read()); print(json.dumps(d.get("snapshot", d))[:1500])' || tail -2 "$WORK/ledger.ndjson"+echo "WORKDIR=$WORK"diff --git a/benchmarks/mbox-ingest/results/fix-atrest-bisect.txt b/benchmarks/mbox-ingest/results/fix-atrest-bisect.txtnew file mode 100644index 000000000..361df0f99--- /dev/null+++ b/benchmarks/mbox-ingest/results/fix-atrest-bisect.txt@@ -0,0 +1,61 @@+########## VARIANT A AFTER clean re-run ##########+variant=A docs=20000 body_kb=10 idle_rss_kb=131936 idle_hwm_kb=131936+{"docs_requested": 20000, "docs_sent": 20000, "node_count": 20000, "body_kb": 10, "bulk_mb": 8.0, "retry_rounds": 147, "wall_s": 1472.1, "docs_per_s": 13.6}+post-flush rss_kb=875708+settled rss_kb=499944 hwm_kb=1928908+cache/view stats:+6447+index bytes on disk: 294456 kB+after-delete rss_kb=211812 (was 500148 before delete)+ledger last snapshot:+{"schema": "xerj.ingest_memory.v1", "seq": 1527, "ts_unix_ns": 1789961058428583400, "event": "trace_snapshot", "scope": {"index_hash": null, "request": null, "flush": null, "merge": null, "shard": null}, "logical": [{"category": "http_body", "current": 0, "peak": 8398962, "measurement": "serialized_size"}, {"category": "http_rewrite_buffer", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "raw_source", "current": 0, "peak": 0, "measurement": "serialized_size"}, {"category": "parsed_source", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "parsed_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "prepared_document", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "prepared_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "memtable_active", "current": 0, "peak": 478961091, "measurement": "estimated"}, {"category": "flush_drained", "current": 0, "peak": 216101357, "measurement": "estimated"}, {"category": "merge_decoded", "current": 0, "peak": 16248091, "measurement": "estimated"}, {"category": "merge_survivor", "current": 0, "peak": 163292797, "measurement": "estimated"}, {"category": "merge_json_buffer", "current": 0, "peak": 162223281, "measurement": "serialized_size"}, {"category": "merge_parsed", "current": 0, "peak": 186934251, "measurement": "estimated"}, {"category": "merge_encoded", "current": 0, "peak": 39973405, "measurement": "serialized_size"}+WORKDIR=/tmp/948-atrest.vMKPdM+########## VARIANT C BASE (100k x 100B) ##########+variant=C docs=100000 body_kb=0 idle_rss_kb=130788 idle_hwm_kb=130788+{"docs_requested": 100000, "docs_sent": 100000, "node_count": 100000, "body_kb": 0, "bulk_mb": 8.0, "retry_rounds": 8, "wall_s": 92.0, "docs_per_s": 1086.5}+post-flush rss_kb=1612780+settled rss_kb=904136 hwm_kb=2020212+cache/view stats:+6455+index bytes on disk: 63568 kB+after-delete rss_kb=215120 (was 904444 before delete)+ledger last snapshot:+{"schema": "xerj.ingest_memory.v1", "seq": 150, "ts_unix_ns": 1789961209342658723, "event": "trace_snapshot", "scope": {"index_hash": null, "request": null, "flush": null, "merge": null, "shard": null}, "logical": [{"category": "http_body", "current": 0, "peak": 8418673, "measurement": "serialized_size"}, {"category": "http_rewrite_buffer", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "raw_source", "current": 0, "peak": 0, "measurement": "serialized_size"}, {"category": "parsed_source", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "parsed_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "prepared_document", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "prepared_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "memtable_active", "current": 865, "peak": 160096907, "measurement": "estimated"}, {"category": "flush_drained", "current": 0, "peak": 71920064, "measurement": "estimated"}, {"category": "merge_decoded", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_survivor", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_json_buffer", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_parsed", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_encoded", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "cache_stored_slices", "c+WORKDIR=/tmp/948-atrest.8HDjdQ+########## VARIANT C AFTER ##########+variant=C docs=100000 body_kb=0 idle_rss_kb=129460 idle_hwm_kb=129460+{"docs_requested": 100000, "docs_sent": 100000, "node_count": 100000, "body_kb": 0, "bulk_mb": 8.0, "retry_rounds": 2, "wall_s": 47.1, "docs_per_s": 2124.2}+post-flush rss_kb=1385352+settled rss_kb=287496 hwm_kb=1607592+cache/view stats:+6459+index bytes on disk: 63576 kB+after-delete rss_kb=176968 (was 287744 before delete)+ledger last snapshot:+{"schema": "xerj.ingest_memory.v1", "seq": 105, "ts_unix_ns": 1789961314285513277, "event": "trace_snapshot", "scope": {"index_hash": null, "request": null, "flush": null, "merge": null, "shard": null}, "logical": [{"category": "http_body", "current": 0, "peak": 8418673, "measurement": "serialized_size"}, {"category": "http_rewrite_buffer", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "raw_source", "current": 0, "peak": 0, "measurement": "serialized_size"}, {"category": "parsed_source", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "parsed_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "prepared_document", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "prepared_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "memtable_active", "current": 865, "peak": 162499652, "measurement": "estimated"}, {"category": "flush_drained", "current": 0, "peak": 82164391, "measurement": "estimated"}, {"category": "merge_decoded", "current": 0, "peak": 10325213, "measurement": "estimated"}, {"category": "merge_survivor", "current": 0, "peak": 63570782, "measurement": "estimated"}, {"category": "merge_json_buffer", "current": 0, "peak": 56381893, "measurement": "serialized_size"}, {"category": "merge_parsed", "current": 0, "peak": 233834144, "measurement": "estimated"}, {"category": "merge_encoded", "current": 0, "peak": 8009843, "measurement": "serialized_size"}, {+WORKDIR=/tmp/948-atrest.lH663L+########## ATREST TAIL DONE ##########+########## VARIANT A BASE (xerj-948-base) ##########+variant=A docs=20000 body_kb=10 idle_rss_kb=135528 idle_hwm_kb=135528+{"docs_requested": 20000, "docs_sent": 20000, "node_count": 20000, "body_kb": 10, "bulk_mb": 8.0, "retry_rounds": 0, "wall_s": 17.4, "docs_per_s": 1147.7}+post-flush rss_kb=1393996+settled rss_kb=996188 hwm_kb=1990784+cache/view stats:+6447+index bytes on disk: 294476 kB+after-delete rss_kb=232300 (was 996388 before delete)+ledger last snapshot:+{"schema": "xerj.ingest_memory.v1", "seq": 75, "ts_unix_ns": 1789952795164577083, "event": "trace_snapshot", "scope": {"index_hash": null, "request": null, "flush": null, "merge": null, "shard": null}, "logical": [{"category": "http_body", "current": 0, "peak": 8398962, "measurement": "serialized_size"}, {"category": "http_rewrite_buffer", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "raw_source", "current": 0, "peak": 0, "measurement": "serialized_size"}, {"category": "parsed_source", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "parsed_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "prepared_document", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "prepared_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "memtable_active", "current": 865, "peak": 477629276, "measurement": "estimated"}, {"category": "flush_drained", "current": 0, "peak": 205390028, "measurement": "estimated"}, {"category": "merge_decoded", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_survivor", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_json_buffer", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_parsed", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "merge_encoded", "current": 0, "peak": 0, "measurement": "unavailable"}, {"category": "cache_stored_slices", "c+WORKDIR=/tmp/948-atrest.Hljq0P+########## VARIANT A AFTER (xerj-948-after) ##########+variant=A docs=20000 body_kb=10 idle_rss_kb=131400 idle_hwm_kb=131400+{"docs_requested": 20000, "docs_sent": 20000, "node_count": 20000, "body_kb": 10, "bulk_mb": 8.0, "retry_rounds": 0, "wall_s": 18.6, "docs_per_s": 1077.0}+post-flush rss_kb=880792+settled rss_kb=492972 hwm_kb=1988256+cache/view stats:+6447+index bytes on disk: 294860 kB+after-delete rss_kb=203808 (was 493424 before delete)+ledger last snapshot:+{"schema": "xerj.ingest_memory.v1", "seq": 77, "ts_unix_ns": 1789952871701833462, "event": "trace_snapshot", "scope": {"index_hash": null, "request": null, "flush": null, "merge": null, "shard": null}, "logical": [{"category": "http_body", "current": 0, "peak": 8398962, "measurement": "serialized_size"}, {"category": "http_rewrite_buffer", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "raw_source", "current": 0, "peak": 0, "measurement": "serialized_size"}, {"category": "parsed_source", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "parsed_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "prepared_document", "current": 0, "peak": 0, "measurement": "estimated"}, {"category": "prepared_vector", "current": 0, "peak": 0, "measurement": "exact_capacity"}, {"category": "memtable_active", "current": 865, "peak": 477629276, "measurement": "estimated"}, {"category": "flush_drained", "current": 0, "peak": 216974534, "measurement": "estimated"}, {"category": "merge_decoded", "current": 0, "peak": 13576868, "measurement": "estimated"}, {"category": "merge_survivor", "current": 0, "peak": 142017230, "measurement": "estimated"}, {"category": "merge_json_buffer", "current": 0, "peak": 141086859, "measurement": "serialized_size"}, {"category": "merge_parsed", "current": 0, "peak": 162577428, "measurement": "estimated"}, {"category": "merge_encoded", "current": 0, "peak": 34775188, "measurement": "serialized_size"}+WORKDIR=/tmp/948-atrest.SSIO8gdiff --git a/benchmarks/mbox-ingest/results/fix-mixed-1G-capped16g-base.json b/benchmarks/mbox-ingest/results/fix-mixed-1G-capped16g-base.jsonnew file mode 100644index 000000000..c1cc8ad5d--- /dev/null+++ b/benchmarks/mbox-ingest/results/fix-mixed-1G-capped16g-base.json@@ -0,0 +1,199 @@+{+ "profile": "mixed",+ "target_size": "1G",+ "label": "capped16g-base",+ "extra_autoindex_flags": "",+ "resumed_after_a_failed_run": false,+ "autoindex_exit_code": 1,+ "autoindex_last_line": "error: autoindex stopped with bulk/backend failures: bulk backend failed for 38 item(s): {\"type\":\"engine_exception\",\"reason\":\"[parent] real memory circuit breaker tripped: rss=15569MB >= watermark=15564MB (94% of limit=16384MB); writes rejected to prevent an out-of-memory kill\",\"status\":429}. Source file was not journaled complete; fix the server condition (or wait for it to clear) and rerun autoindex \u2014 the run resumes from the journal. Failed source files were not journaled complete; fix the reported server or embedding configuration and rerun the same command to resume safely",+ "source": {+ "mbox_bytes": 1073777879,+ "tree_bytes": 1073794434,+ "entries": 40799,+ "attachments": {+ "binary": 5698,+ "pdf": 4261,+ "text": 4300+ },+ "mbox_sha256": "4098bf60c0cba54e6dc21737c5ddb0883da45854eec928e3e39ff1434aec0323"+ },+ "wall_seconds": 817.1,+ "node_docs_indexed": 85722,+ "docs_per_second": 104.9,+ "source_mb_per_second": 1.31,+ "peak_rss_unit": "MiB (VmHWM kB / 1024) - the key says mb for compatibility with earlier result files",+ "peak_rss_mb": {+ "autoindex_process": 242.7,+ "largest_single_process_in_autoindex_tree": 241.2,+ "server": 25356.9,+ "server_at_autoindex_exit": 25356.9,+ "server_idle_before_run": 132.7+ },+ "server_memory_cap": "auto tier (see the node log)",+ "server_breaker_engagements": 31,+ "disk_bytes": {+ "index_at_autoindex_exit": 608292835,+ "index_settled": 605235632,+ "index_settled_over_mbox": 0.564,+ "state_dir_peak_during_run": 262950092+ },+ "loadavg_before": "1.54 1.67 2.02",+ "loadavg_after": [+ "2.34",+ "2.10",+ "2.02"+ ],+ "verify": {+ "node_docs": 85722,+ "mbox_docs": 85692,+ "attachment_docs": 31731,+ "needles": {+ "body": {+ "planted": 418,+ "found_exactly_once": 329,+ "found_in_overlapping_sections": 1,+ "missing": 88,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 418+ },+ "latin1-8bit-body": {+ "planted": 1160,+ "found_exactly_once": 916,+ "found_in_overlapping_sections": 0,+ "missing": 244,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 1160+ },+ "cp1252-undeclared-body": {+ "planted": 417,+ "found_exactly_once": 335,+ "found_in_overlapping_sections": 0,+ "missing": 82,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 417+ },+ "after-unquoted-prose-from": {+ "planted": 41,+ "found_exactly_once": 32,+ "found_in_overlapping_sections": 0,+ "missing": 9,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 41+ },+ "pdf-attachment": {+ "planted": 265,+ "found_exactly_once": 216,+ "found_in_overlapping_sections": 0,+ "missing": 49,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 265+ },+ "text-attachment": {+ "planted": 216,+ "found_exactly_once": 178,+ "found_in_overlapping_sections": 0,+ "missing": 38,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 216+ },+ "keep-note": {+ "planted": 12,+ "found_exactly_once": 12,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 12+ },+ "drive-markdown": {+ "planted": 1,+ "found_exactly_once": 1,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 1+ }+ },+ "needle_examples_of_failure": [+ {+ "missing": {+ "message_id": "[email protected]",+ "token": "xqtonelubedo",+ "where": "after-unquoted-prose-from"+ },+ "response_error": null+ },+ {+ "missing": {+ "message_id": "[email protected]",+ "token": "xqputorusobi",+ "where": "cp1252-undeclared-body"+ },+ "response_error": null+ },+ {+ "missing": {+ "message_id": "[email protected]",+ "token": "xqcatamadege",+ "where": "body"+ },+ "response_error": null+ },+ {+ "missing": {+ "message_id": "[email protected]",+ "token": "xqbozamucuru",+ "where": "cp1252-undeclared-body"+ },+ "response_error": null+ },+ {+ "missing": {+ "message_id": "[email protected]",+ "token": "xqrorepakifa",+ "where": "latin1-8bit-body"+ },+ "response_error": null+ }+ ],+ "edges": {+ "replies_to": {+ "live": 0,+ "stored_including_invalidated": 0,+ "truth_resolvable_replies": 21544+ },+ "attachment_of": {+ "live": 0,+ "stored_including_invalidated": 0,+ "attachment_docs": 31731+ }+ },+ "sender_filter": {+ "sampled": 40,+ "term_matches_display_form": 40,+ "mismatch": []+ },+ "subject_search": {+ "sampled": 40,+ "subject_found_in_body": 40,+ "mismatch": []+ },+ "empty_no_subject_docs": 0,+ "query_latency_seconds": {+ "requests": 2700,+ "total": 66.5,+ "median": 0.0065,+ "p95": 0.0075,+ "max": 33.001,+ "over_1s": 2,+ "over_10s": 2+ }+ }+}\ No newline at end of filediff --git a/benchmarks/mbox-ingest/results/fix-mixed-1G-capped16g-fixed.json b/benchmarks/mbox-ingest/results/fix-mixed-1G-capped16g-fixed.jsonnew file mode 100644index 000000000..5d9464e7f--- /dev/null+++ b/benchmarks/mbox-ingest/results/fix-mixed-1G-capped16g-fixed.json@@ -0,0 +1,158 @@+{+ "profile": "mixed",+ "target_size": "1G",+ "label": "capped16g-fix",+ "extra_autoindex_flags": "",+ "resumed_after_a_failed_run": false,+ "autoindex_exit_code": 3,+ "autoindex_last_line": "xerj-done ok=true exit=3 reason=completed-with-junk wall=407.6s files=16 records=107698 datasets=1 junk_files=2 code_files=0 code_files_indexed=0 code_files_junked=0",+ "source": {+ "mbox_bytes": 1073777879,+ "tree_bytes": 1073794434,+ "entries": 40799,+ "attachments": {+ "binary": 5698,+ "pdf": 4261,+ "text": 4300+ },+ "mbox_sha256": "4098bf60c0cba54e6dc21737c5ddb0883da45854eec928e3e39ff1434aec0323"+ },+ "wall_seconds": 407.7,+ "node_docs_indexed": 107698,+ "docs_per_second": 264.1,+ "source_mb_per_second": 2.63,+ "peak_rss_unit": "MiB (VmHWM kB / 1024) - the key says mb for compatibility with earlier result files",+ "peak_rss_mb": {+ "autoindex_process": 318.3,+ "largest_single_process_in_autoindex_tree": 318.3,+ "server": 21405.3,+ "server_at_autoindex_exit": 21405.3,+ "server_idle_before_run": 131.0+ },+ "server_memory_cap": "auto tier (see the node log)",+ "server_breaker_engagements": 24,+ "disk_bytes": {+ "index_at_autoindex_exit": 776955683,+ "index_settled": 776726956,+ "index_settled_over_mbox": 0.723,+ "state_dir_peak_during_run": 262950092+ },+ "loadavg_before": "4.87 2.63 2.19",+ "loadavg_after": [+ "5.50",+ "5.42",+ "6.60"+ ],+ "verify": {+ "node_docs": 107698,+ "mbox_docs": 107668,+ "attachment_docs": 39619,+ "needles": {+ "body": {+ "planted": 418,+ "found_exactly_once": 417,+ "found_in_overlapping_sections": 1,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 418+ },+ "latin1-8bit-body": {+ "planted": 1160,+ "found_exactly_once": 1160,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 1160+ },+ "cp1252-undeclared-body": {+ "planted": 417,+ "found_exactly_once": 417,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 417+ },+ "after-unquoted-prose-from": {+ "planted": 41,+ "found_exactly_once": 41,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 41+ },+ "pdf-attachment": {+ "planted": 265,+ "found_exactly_once": 265,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 265+ },+ "text-attachment": {+ "planted": 216,+ "found_exactly_once": 216,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 216+ },+ "keep-note": {+ "planted": 12,+ "found_exactly_once": 12,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 12+ },+ "drive-markdown": {+ "planted": 1,+ "found_exactly_once": 1,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 1+ }+ },+ "needle_examples_of_failure": [],+ "edges": {+ "replies_to": {+ "live": 21544,+ "stored_including_invalidated": 21544,+ "truth_resolvable_replies": 21544+ },+ "attachment_of": {+ "live": 39619,+ "stored_including_invalidated": 39619,+ "attachment_docs": 39619+ }+ },+ "sender_filter": {+ "sampled": 0,+ "term_matches_display_form": 0,+ "mismatch": []+ },+ "subject_search": {+ "sampled": 40,+ "subject_found_in_body": 40,+ "mismatch": []+ },+ "empty_no_subject_docs": 0,+ "query_latency_seconds": {+ "requests": 2619,+ "total": 3055.9,+ "median": 0.0092,+ "p95": 5.5393,+ "max": 71.549,+ "over_1s": 509,+ "over_10s": 18+ }+ }+}\ No newline at end of filediff --git a/benchmarks/mbox-ingest/results/fix-mixed-300M-cap8g-base.json b/benchmarks/mbox-ingest/results/fix-mixed-300M-cap8g-base.jsonnew file mode 100644index 000000000..969fa9616--- /dev/null+++ b/benchmarks/mbox-ingest/results/fix-mixed-300M-cap8g-base.json@@ -0,0 +1,158 @@+{+ "profile": "mixed",+ "target_size": "300M",+ "label": "cap8g-base",+ "extra_autoindex_flags": "",+ "resumed_after_a_failed_run": false,+ "autoindex_exit_code": 3,+ "autoindex_last_line": "xerj-done ok=true exit=3 reason=completed-with-junk wall=66.3s files=16 records=30403 datasets=1 junk_files=2 code_files=0 code_files_indexed=0 code_files_junked=0 bulk_retries=9",+ "source": {+ "mbox_bytes": 314676844,+ "tree_bytes": 314693315,+ "entries": 11478,+ "attachments": {+ "binary": 1632,+ "pdf": 1192,+ "text": 1213+ },+ "mbox_sha256": "8db4b57314368947cf1e26ef857e1453b6e708544aff3c420cbb6a85fbbddf12"+ },+ "wall_seconds": 66.5,+ "node_docs_indexed": 30403,+ "docs_per_second": 457.4,+ "source_mb_per_second": 4.73,+ "peak_rss_unit": "MiB (VmHWM kB / 1024) - the key says mb for compatibility with earlier result files",+ "peak_rss_mb": {+ "autoindex_process": 229.7,+ "largest_single_process_in_autoindex_tree": 229.7,+ "server": 14766.6,+ "server_at_autoindex_exit": 14766.6,+ "server_idle_before_run": 133.9+ },+ "server_memory_cap": "8192",+ "server_breaker_engagements": 178,+ "disk_bytes": {+ "index_at_autoindex_exit": 222739763,+ "index_settled": 222446466,+ "index_settled_over_mbox": 0.707,+ "state_dir_peak_during_run": 74145290+ },+ "loadavg_before": "2.42 2.52 2.63",+ "loadavg_after": [+ "3.21",+ "2.36",+ "2.46"+ ],+ "verify": {+ "node_docs": 30403,+ "mbox_docs": 30373,+ "attachment_docs": 11169,+ "needles": {+ "body": {+ "planted": 118,+ "found_exactly_once": 118,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 118+ },+ "latin1-8bit-body": {+ "planted": 332,+ "found_exactly_once": 332,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 332+ },+ "cp1252-undeclared-body": {+ "planted": 131,+ "found_exactly_once": 131,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 131+ },+ "after-unquoted-prose-from": {+ "planted": 12,+ "found_exactly_once": 12,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 12+ },+ "pdf-attachment": {+ "planted": 69,+ "found_exactly_once": 69,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 69+ },+ "text-attachment": {+ "planted": 60,+ "found_exactly_once": 60,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 60+ },+ "keep-note": {+ "planted": 12,+ "found_exactly_once": 12,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 12+ },+ "drive-markdown": {+ "planted": 1,+ "found_exactly_once": 1,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 1+ }+ },+ "needle_examples_of_failure": [],+ "edges": {+ "replies_to": {+ "live": 5992,+ "stored_including_invalidated": 5992,+ "truth_resolvable_replies": 5992+ },+ "attachment_of": {+ "live": 11169,+ "stored_including_invalidated": 11169,+ "attachment_docs": 11169+ }+ },+ "sender_filter": {+ "sampled": 40,+ "term_matches_display_form": 40,+ "mismatch": []+ },+ "subject_search": {+ "sampled": 40,+ "subject_found_in_body": 40,+ "mismatch": []+ },+ "empty_no_subject_docs": 0,+ "query_latency_seconds": {+ "requests": 905,+ "total": 280.03,+ "median": 0.0039,+ "p95": 1.593,+ "max": 11.43,+ "over_1s": 167,+ "over_10s": 1+ }+ }+}\ No newline at end of filediff --git a/benchmarks/mbox-ingest/results/fix-mixed-300M-cap8g-fixed.json b/benchmarks/mbox-ingest/results/fix-mixed-300M-cap8g-fixed.jsonnew file mode 100644index 000000000..63e089e0e--- /dev/null+++ b/benchmarks/mbox-ingest/results/fix-mixed-300M-cap8g-fixed.json@@ -0,0 +1,158 @@+{+ "profile": "mixed",+ "target_size": "300M",+ "label": "cap8g-fix",+ "extra_autoindex_flags": "",+ "resumed_after_a_failed_run": false,+ "autoindex_exit_code": 3,+ "autoindex_last_line": "xerj-done ok=true exit=3 reason=completed-with-junk wall=72.8s files=16 records=30403 datasets=1 junk_files=2 code_files=0 code_files_indexed=0 code_files_junked=0",+ "source": {+ "mbox_bytes": 314676844,+ "tree_bytes": 314693315,+ "entries": 11478,+ "attachments": {+ "binary": 1632,+ "pdf": 1192,+ "text": 1213+ },+ "mbox_sha256": "8db4b57314368947cf1e26ef857e1453b6e708544aff3c420cbb6a85fbbddf12"+ },+ "wall_seconds": 73.0,+ "node_docs_indexed": 30403,+ "docs_per_second": 416.3,+ "source_mb_per_second": 4.31,+ "peak_rss_unit": "MiB (VmHWM kB / 1024) - the key says mb for compatibility with earlier result files",+ "peak_rss_mb": {+ "autoindex_process": 225.4,+ "largest_single_process_in_autoindex_tree": 225.4,+ "server": 7963.6,+ "server_at_autoindex_exit": 7963.6,+ "server_idle_before_run": 129.9+ },+ "server_memory_cap": "8192",+ "server_breaker_engagements": 2,+ "disk_bytes": {+ "index_at_autoindex_exit": 222031647,+ "index_settled": 221737169,+ "index_settled_over_mbox": 0.705,+ "state_dir_peak_during_run": 74145290+ },+ "loadavg_before": "3.21 2.36 2.46",+ "loadavg_after": [+ "1.41",+ "1.65",+ "2.02"+ ],+ "verify": {+ "node_docs": 30403,+ "mbox_docs": 30373,+ "attachment_docs": 11169,+ "needles": {+ "body": {+ "planted": 118,+ "found_exactly_once": 118,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 118+ },+ "latin1-8bit-body": {+ "planted": 332,+ "found_exactly_once": 332,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 332+ },+ "cp1252-undeclared-body": {+ "planted": 131,+ "found_exactly_once": 131,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 131+ },+ "after-unquoted-prose-from": {+ "planted": 12,+ "found_exactly_once": 12,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 12+ },+ "pdf-attachment": {+ "planted": 69,+ "found_exactly_once": 69,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 69+ },+ "text-attachment": {+ "planted": 60,+ "found_exactly_once": 60,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 60+ },+ "keep-note": {+ "planted": 12,+ "found_exactly_once": 12,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 12+ },+ "drive-markdown": {+ "planted": 1,+ "found_exactly_once": 1,+ "found_in_overlapping_sections": 0,+ "missing": 0,+ "duplicated": 0,+ "wrong_message": 0,+ "checked": 1+ }+ },+ "needle_examples_of_failure": [],+ "edges": {+ "replies_to": {+ "live": 5992,+ "stored_including_invalidated": 5992,+ "truth_resolvable_replies": 5992+ },+ "attachment_of": {+ "live": 11169,+ "stored_including_invalidated": 11169,+ "attachment_docs": 11169+ }+ },+ "sender_filter": {+ "sampled": 40,+ "term_matches_display_form": 40,+ "mismatch": []+ },+ "subject_search": {+ "sampled": 40,+ "subject_found_in_body": 40,+ "mismatch": []+ },+ "empty_no_subject_docs": 0,+ "query_latency_seconds": {+ "requests": 905,+ "total": 758.84,+ "median": 1.4364,+ "p95": 1.6303,+ "max": 25.632,+ "over_1s": 455,+ "over_10s": 2+ }+ }+}\ No newline at end of filediff --git a/benchmarks/mbox-ingest/synth_bulk_ingest.py b/benchmarks/mbox-ingest/synth_bulk_ingest.pynew file mode 100755index 000000000..bbf95fa4a--- /dev/null+++ b/benchmarks/mbox-ingest/synth_bulk_ingest.py@@ -0,0 +1,176 @@+#!/usr/bin/env python3+"""Mailbox-shaped synthetic bulk load against a running xerj node (issue #948).++Generates the record shape that dominates a Google-Takeout mailbox ingest+(~60 text/keyword fields, a multi-KB body per doc) and drives the ES-compat+`_bulk` API with the same 8 MB request bodies `xerj autoindex` uses, WITHOUT+autoindex's catalog/brain/edge traffic — so the numbers isolate the engine's+ingest-side memory behaviour.++ synth_bulk_ingest.py --url http://127.0.0.1:9341 --docs 20000 --body-kb 10 \+ [--index bench-docs] [--bulk-mb 8] [--key FILE] [--json]++Every doc is unique (`msg-<i>`); `--seed` makes bodies reproducible. Writes+one JSON line to stdout (--json) with docs, wall seconds, and the node's own+count/_stats views. Memory figures are read by the caller from /proc.+"""+import argparse+import json+import random+import sys+import time+import urllib.request++WORDS = (+ "deployment window roadmap vendor renewal sync notes thread reply "+ "forward attached please review the following document as discussed "+ "earlier this week let me know when convenient regards team update "+ "quarterly planning budget review milestone delivery customer feedback"+).split()+++def body(rng: random.Random, kb: int) -> str:+ # kb=0 means "tiny body" (100 B) for the per-doc vs per-byte bisection —+ # the field stays present so doc SHAPE is constant across variants.+ target = max(kb * 1024, 100)+ parts: list[str] = []+ while sum(len(p) + 1 for p in parts) < target:+ sent = " ".join(rng.choice(WORDS) for _ in range(rng.randint(6, 14)))+ parts.append(f"{rng.randint(1, 999_999):06d} {sent}.")+ return "\n".join(parts)[:target]+++def doc(rng: random.Random, i: int, kb: int) -> dict:+ d = {+ "_id": f"msg-{i}",+ "_source": {+ "message_id": f"<{i:08d}@takeout.example>",+ "from": f"user{i % 97}@example.org",+ "to": f"peer{i % 89}@example.net",+ "subject": " ".join(rng.choice(WORDS) for _ in range(rng.randint(3, 9))),+ "date": f"2024-{1 + i % 12:02d}-{1 + i % 28:02d}T10:{i % 60:02d}:00Z",+ "body": body(rng, kb),+ "labels": [rng.choice(WORDS) for _ in range(3)],+ "attachment_name": f"report-{i % 500}.pdf",+ "attachment_content_type": "application/pdf",+ "attachment_bytes": rng.randint(10_000, 900_000),+ "ax_paths": [f"Takeout/Mail/{i % 40}.mbox"],+ "kind": "email",+ },+ }+ return d+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--url", required=True)+ ap.add_argument("--docs", type=int, default=20_000)+ ap.add_argument("--body-kb", type=int, default=10)+ ap.add_argument("--index", default="bench-docs")+ ap.add_argument("--bulk-mb", type=float, default=8.0)+ ap.add_argument("--seed", type=int, default=42)+ ap.add_argument("--body-type", choices=["text", "keyword"], default="text",+ help="mapping for the body field: text (postings) or keyword (none)")+ ap.add_argument("--key", help="file with the admin API key")+ ap.add_argument("--json", action="store_true")+ ap.add_argument("--auto-id", action="store_true",+ help="omit _id from bulk actions (turbo-raw path) instead of "+ "explicit ids (per-doc path)")+ ap.add_argument("--retry-rounds", type=int, default=300,+ help="bulk rounds to re-offer 429-rejected records (like autoindex)")+ args = ap.parse_args()++ rng = random.Random(args.seed)+ headers = {"Content-Type": "application/x-ndjson"}+ if args.key:+ headers["Authorization"] = "ApiKey " + open(args.key).read().strip()++ req = urllib.request.Request(+ f"{args.url}/{args.index}",+ data=json.dumps({"mappings": {"properties": {+ "body": {"type": args.body_type}, "subject": {"type": "text"},+ "message_id": {"type": "keyword"}, "from": {"type": "keyword"},+ "to": {"type": "keyword"}, "date": {"type": "date"},+ "labels": {"type": "keyword"}, "attachment_name": {"type": "keyword"},+ "attachment_content_type": {"type": "keyword"},+ "attachment_bytes": {"type": "long"}, "ax_paths": {"type": "keyword"},+ "kind": {"type": "keyword"},+ }}}).encode(), headers=headers, method="PUT")+ try:+ urllib.request.urlopen(req).read()+ except urllib.error.HTTPError as e:+ if b"resource_already_exists" not in e.read():+ raise++ t0 = time.time()+ sent = 0+ bulk_bytes = int(args.bulk_mb * 1024 * 1024)++ def send(items: list[tuple[str, str]]) -> list[tuple[str, str]]:+ """POST one bulk batch; return the (action, line) pairs to retry (429s)."""+ payload = ("\n".join(a + "\n" + l for a, l in items) + "\n").encode()+ r = urllib.request.Request(f"{args.url}/_bulk", data=payload,+ headers=headers, method="POST")+ try:+ with urllib.request.urlopen(r) as resp:+ out = json.load(resp)+ except urllib.error.HTTPError as e:+ if e.code == 429:+ return items # whole-request admission rejection: retry all+ raise+ if not out.get("errors"):+ return []+ retry: list[tuple[str, str]] = []+ for item, (a, l) in zip(out["items"], items):+ op = item.get("index") or item.get("create") or {}+ status = op.get("status", 500)+ if status == 429:+ retry.append((a, l))+ elif status >= 400:+ print(f"non-429 bulk error: {json.dumps(op)[:200]}", file=sys.stderr)+ return retry++ retries = 0+ pending: list[tuple[str, str]] = []+ for i in range(args.docs):+ d = doc(rng, i, args.body_kb)+ line = json.dumps(d, separators=(",", ":"))+ if args.auto_id:+ action = json.dumps({"index": {"_index": args.index}},+ separators=(",", ":"))+ else:+ action = json.dumps({"index": {"_index": args.index, "_id": d["_id"]}},+ separators=(",", ":"))+ pending.append((action, line))+ sent += 1+ if sum(len(a) + len(l) for a, l in pending) >= bulk_bytes or i == args.docs - 1:+ batch, pending = pending, []+ for attempt in range(args.retry_rounds):+ batch = send(batch)+ if not batch:+ break+ retries += 1+ time.sleep(min(2.0 * (attempt + 1), 10.0))+ if batch:+ print(f"giving up on {len(batch)} records after {args.retry_rounds} retry rounds",+ file=sys.stderr)+ return 2+ wall = time.time() - t0++ q = urllib.request.Request(+ f"{args.url}/{args.index}/_count",+ data=json.dumps({"query": {"match_all": {}}}).encode(),+ headers=headers, method="POST")+ with urllib.request.urlopen(q) as resp:+ count = json.load(resp)["count"]+ print(json.dumps({+ "docs_requested": args.docs, "docs_sent": sent, "node_count": count,+ "body_kb": args.body_kb, "bulk_mb": args.bulk_mb, "retry_rounds": retries,+ "wall_s": round(wall, 1),+ "docs_per_s": round(sent / wall, 1) if wall else None,+ }))+ return 0 if count == args.docs else 3+++if __name__ == "__main__":+ sys.exit(main())diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 0029ea588..494bab394 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -19,6 +19,58 @@ use crate::cluster_state::{use crate::index::{Index, IndexStats};use crate::{EngineError, Result};+// ── Memory-pressure drain plumbing (issue #948) ─────────────────────────────+//+// The parent RSS breaker used to only REJECT writes (429). Under a workload+// whose caches hold gigabytes of re-hydratable state and whose memtable+// holds raw write payloads, rejection frees nothing: the breaker stays+// engaged, the client retries forever, and the run never finishes — exactly+// the #948 mailbox ingest (16 GiB cap, 26.5 GiB demand, 118-147 s engaged+// stretches, 3-4 s releases). The sampler now also requests a DRAIN: flush+// every index, release rebuildable caches, purge allocator pages.++/// Minimum spacing between automatic drains while the breaker stays engaged.+/// The engage edge always fires immediately; repeats are rate-limited so a+/// long pinned stretch drains progressively (caches refill under continued+/// reads) without the drain worker competing with ingest for every tick.+const MEMORY_DRAIN_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);++/// Bounded request channel from the sampler thread to the drain worker.+/// Capacity 1 + try_send ⇒ requests coalesce: one arrives mid-drain is+/// dropped, and the next sampler tick re-requests if still engaged.+static MEMORY_DRAIN_TX: std::sync::OnceLock<std::sync::mpsc::SyncSender<()>> =+ std::sync::OnceLock::new();++/// Allocator page purge hook, installed by the binary that owns the global+/// allocator (xerj-server installs a jemalloc epoch+purge closure). Freeing+/// heap is not enough: the RSS breaker keys on resident pages, and jemalloc+/// keeps freed pages resident until they are purged back to the OS. The+/// engine crate itself is allocator-agnostic, so the default is a no-op.+type AllocatorPurgeHook = Arc<dyn Fn() + Send + Sync + 'static>;+static ALLOCATOR_PURGE_HOOK: std::sync::RwLock<Option<AllocatorPurgeHook>> =+ std::sync::RwLock::new(None);++/// Install the allocator page-purge hook (see [`ALLOCATOR_PURGE_HOOK`]).+/// Called once by the server binary during boot, before any drain can fire.+pub fn set_allocator_purge_hook(hook: AllocatorPurgeHook) {+ let mut slot = ALLOCATOR_PURGE_HOOK+ .write()+ .unwrap_or_else(|e| e.into_inner());+ *slot = Some(hook);+}++/// Run the installed allocator purge, if any. Never panics: a broken hook+/// must not take the drain (or the process) down — purging is an+/// optimisation for RSS return, not a correctness step.+fn purge_allocator_pages() {+ let hook = ALLOCATOR_PURGE_HOOK+ .read()+ .unwrap_or_else(|e| e.into_inner());+ if let Some(hook) = hook.as_ref() {+ hook();+ }+}+/// Privacy-safe identity of the embedding execution contract exposed to/// remote ingestion clients. The digest is opaque: model paths, provider URLs,/// credentials, and model names never cross the API boundary.@@ -3813,6 +3865,44 @@ impl Engine {.sum()}+ /// Memory-pressure drain (issue #948): flush every loaded index's+ /// memtable, then release its rebuildable caches via+ /// [`crate::index::Index::release_memory`], then hand the freed pages+ /// back to the OS through the allocator-purge hook (installed by the+ /// server binary; a no-op elsewhere).+ ///+ /// Why the flush comes first: the memtable holds not-yet-published+ /// writes that no cache release can reclaim, and on the raw-bytes bulk+ /// path its live heap is the payload itself — the exact bytes a pinned+ /// breaker needs gone. Caches only ever mirror durable data, so this is+ /// the same ordering [`Self::close_index`] uses (#463), applied to every+ /// index without closing anything: reads re-hydrate from disk.+ ///+ /// Best-effort by design: an index whose flush fails is still+ /// cache-released and never aborts the drain — a drain must not become a+ /// new way to wedge. Returns the number of indexes drained; closed+ /// indexes are skipped (their caches were already released at close).+ pub async fn drain_rebuildable_memory(&self) -> usize {+ let mut drained = 0usize;+ for entry in self.indices.iter() {+ let idx = Arc::clone(entry.value());+ let name = entry.key();+ if self.closed_indices.contains_key(name.as_str()) {+ continue;+ }+ if idx.flush().await.is_err() {+ tracing::warn!(+ index = name.as_str(),+ "memory-pressure drain: flush failed, releasing caches anyway"+ );+ }+ idx.release_memory();+ drained += 1;+ }+ purge_allocator_pages();+ drained+ }+/// Spawn the background resource sampler (item 1/3): every/// [`crate::governor::SAMPLE_INTERVAL_MS`] it refreshes the governor's/// summed-memtable / RSS / disk-usage atomics, which drive the hot-path@@ -3835,6 +3925,42 @@ impl Engine {}let period = std::time::Duration::from_millis(crate::governor::SAMPLE_INTERVAL_MS);+ // ── Thread C: memory-pressure drain worker (#948) ─────────────+ // Thread A (below) must touch no engine lock, so it cannot run the+ // drain itself: it only requests one over this bounded channel. The+ // worker owns a single-threaded tokio runtime so the drain's async+ // flushes work even though this thread lives outside the server+ // runtime; a capacity-1 channel with try_send makes coalescing+ // automatic — requests that arrive mid-drain are dropped, and the+ // next sampler tick re-requests if the breaker is still engaged.+ // Requires a tokio handle at spawn time so flush internals that+ // spawn detached work (merge handoff) land on the REAL runtime+ // instead of dying with this thread's runtime.+ let drain_handle = tokio::runtime::Handle::try_current().ok();+ let (drain_tx, drain_rx) = std::sync::mpsc::sync_channel::<()>(1);+ let _ = MEMORY_DRAIN_TX.set(drain_tx);+ let weak_c = Arc::downgrade(self);+ let _ = std::thread::Builder::new()+ .name("xerj-mem-drain".to_string())+ .spawn(move || {+ let Some(handle) = drain_handle else {+ // Spawned outside a runtime (unit tests): the drain+ // method stays directly callable; only the sampler's+ // automatic wiring is inert.+ return;+ };+ while let Ok(()) = drain_rx.recv() {+ let Some(engine) = weak_c.upgrade() else {+ return; // engine dropped+ };+ let drained = handle.block_on(engine.drain_rebuildable_memory());+ tracing::info!(+ indexes = drained,+ "memory breaker engaged — drained rebuildable state (flush + cache release + purge)"+ );+ }+ });+// ── Thread A: memory + disk ──────────────────────────────────────// Touches NO engine lock — just `/proc/self/statm` + `statvfs`. Kept// on its own thread so a memtable-sum stall (below) can NEVER delay@@ -3853,6 +3979,10 @@ impl Engine {period_ms = crate::governor::SAMPLE_INTERVAL_MS,"memory/disk sampler thread started (parent circuit breaker)");+ // #948 drain bookkeeping: None while the breaker is+ // disengaged (so the next engage edge fires immediately),+ // Some(last-drain) while engaged (rate-limited repeats).+ let mut last_drain_at: Option<std::time::Instant> = None;loop {std::thread::sleep(period);if weak_a.strong_count() == 0 {@@ -3867,6 +3997,28 @@ impl Engine {crate::governor::disk_used_pct_and_avail(&data_dir);governor.refresh_memory_disk(rss, disk_pct, disk_avail);+ // Issue #948 — a breaker that only rejects never lets a+ // memory-pinned workload finish: caches hold gigabytes+ // of re-hydratable state and the memtable holds raw+ // write payloads, and 429s free none of it. Request a+ // drain on the engage edge and at most once per window+ // while engaged. try_send never blocks, so Thread A's+ // no-lock/no-block contract above still holds.+ if governor.memory_breaker_engaged() {+ let fire = match last_drain_at {+ None => true,+ Some(at) => at.elapsed() >= MEMORY_DRAIN_MIN_INTERVAL,+ };+ if fire {+ last_drain_at = Some(std::time::Instant::now());+ if let Some(tx) = MEMORY_DRAIN_TX.get() {+ let _ = tx.try_send(());+ }+ }+ } else {+ last_drain_at = None;+ }+// Runtime disk flood-stage override, matching ES's// `PUT _cluster/settings` unblock without a restart. A// non-blocking read: on contention we just keep lastdiff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rsindex 7eb4e8490..58bd42ae2 100644--- a/engine/crates/xerj-engine/src/governor.rs+++ b/engine/crates/xerj-engine/src/governor.rs@@ -142,6 +142,16 @@ impl ResourceGovernor {Ok(())}+ /// Whether the parent RSS memory breaker is currently engaged (issue+ /// #948). Admission (429) is only half of the contract: the resource+ /// sampler uses this same flag to request a memory-pressure DRAIN of+ /// rebuildable state (flush + cache release), because a breaker that+ /// only rejects never lets a workload whose caches hold gigabytes of+ /// re-hydratable data make progress.+ pub fn memory_breaker_engaged(&self) -> bool {+ self.memory_tripped.load(Ordering::Relaxed)+ }+/// Disk flood-stage admission. Returns an ES-shaped/// `read_only_allow_delete` cluster block (HTTP 429) when the data-dir/// filesystem is over the flood-stage watermark. `index` names the@@ -1588,6 +1598,31 @@ mod tests {assert!(g.check_ingest_admission().is_ok());}+ /// #948: the sampler's drain wiring keys on this accessor, so it must+ /// track the RSS watermark latch exactly — engaging when the breaker+ /// engages, releasing when it releases. A stale engaged reading drains+ /// forever; a stale released one never drains at all.+ #[test]+ fn memory_breaker_engaged_tracks_the_rss_watermark() {+ let mut cfg = Config::default();+ cfg.limits.max_total_memtable_mb = 0; // isolate the RSS path+ cfg.limits.memory_watermark_percent = 95;+ let g = build(&cfg);+ let watermark = g.memory_watermark_bytes;+ assert!(watermark > 0, "this test needs a live RSS watermark");+ assert!(!g.memory_breaker_engaged(), "fresh governor is disengaged");+ g.refresh(0, watermark, 0);+ assert!(+ g.memory_breaker_engaged(),+ "RSS at the watermark engages the breaker"+ );+ g.refresh(0, watermark / 2, 0);+ assert!(+ !g.memory_breaker_engaged(),+ "RSS back under the watermark releases it"+ );+ }+#[test]fn disk_flood_blocks_with_hysteresis() {let mut cfg = Config::default();diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 0910053a2..f7fafdfa7 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -11193,6 +11193,42 @@ impl Index {Ok(total)}+ /// Upper bound on the total INPUT bytes of one merge batch. Issue #948.+ ///+ /// The merge executor materialises decoded and re-encoded copies of+ /// every input document (measured 5-9x input bytes on mailbox-shaped+ /// docs: `merge_parsed` alone held 191 MB current on a 20k-doc index),+ /// so batch heap cost scales with bytes, not segment count. Peers+ /// bound the same thing by memory, not count: Quickwit caps the bytes+ /// buffered by pending merge writers+ /// (`quickwit-parquet-engine/src/storage/streaming_writer.rs:378`+ /// `pending_writers_memory_size`) and streams segment files+ /// (`quickwit-parquet-engine/src/merge/streaming.rs:148`); tantivy's+ /// `LogMergePolicy` filters candidates by size before batching+ /// (`max_docs_before_merge`, `src/indexer/log_merge_policy.rs:22,94`).+ ///+ /// Derived: `clamp(process cap / 64, 32 MiB, 512 MiB)` — at #948's+ /// 16 GiB auto-cap that is a 256 MiB batch, i.e. a worst-case merge+ /// working set of ~1.5-2.4 GiB at the measured multipliers.+ /// `XERJ_MERGE_BATCH_MAX_INPUT_MB` overrides (0 disables the bound).+ /// A non-numeric cap (`auto`, `off`) falls back to the 512 MiB+ /// default.+ fn merge_batch_cap_bytes() -> u64 {+ const MB: u64 = 1024 * 1024;+ if let Ok(raw) = std::env::var("XERJ_MERGE_BATCH_MAX_INPUT_MB") {+ if let Ok(mb) = raw.trim().parse::<u64>() {+ return mb * MB;+ }+ }+ match std::env::var("XERJ_MAX_PROCESS_MEMORY_MB")+ .ok()+ .and_then(|raw| raw.trim().parse::<u64>().ok())+ {+ Some(limit_mb) if limit_mb > 0 => (limit_mb / 64).clamp(32, 512) * MB,+ _ => 512 * MB,+ }+ }+/// One merge pass. Caller MUST hold `merge_in_progress` (and clear it/// after — see `MergeFlagClear`).///@@ -11237,6 +11273,7 @@ impl Index {max_merge_count: mc.max_merge_count as usize,tier_floor_bytes: mc.tier_floor_mb * 1024 * 1024,max_merged_segment_bytes: mc.max_segment_mb * 1024 * 1024,+ max_batch_input_bytes: Self::merge_batch_cap_bytes(),};let segments_snapshot_init = {@@ -11246,15 +11283,37 @@ impl Index {let batches: Vec<Vec<SegmentId>> = match force_max_segments {// Forcemerge: chunk every segment (smallest first) into// max_merge_count-sized batches, ignoring tier/size caps.+ // #948 — the byte cap still applies: an explicit forcemerge+ // on a mailbox index used to build one count-sized batch of+ // ~100 MB segments and hold ~16 GiB of decoded docs at once.+ // Multiple capped batches still converge to `target`+ // segments (the caller loops passes).Some(target) if segments_snapshot_init.len() > target => {+ let cap = Self::merge_batch_cap_bytes();let mut segs: Vec<&xerj_storage::segment::SegmentMeta> =segments_snapshot_init.iter().collect();segs.sort_by_key(|s| s.size_bytes);+ let sizes: Vec<u64> = segs.iter().map(|s| s.size_bytes).collect();let ids: Vec<SegmentId> = segs.into_iter().map(|s| s.id.clone()).collect();- ids.chunks((mc.max_merge_count as usize).max(2))- .filter(|c| c.len() >= 2)- .map(|c| c.to_vec())- .collect()+ let chunk_len = (mc.max_merge_count as usize).max(2);+ let mut chunks: Vec<Vec<SegmentId>> = Vec::new();+ let mut batch: Vec<SegmentId> = Vec::new();+ let mut batch_bytes = 0u64;+ for (id, size) in ids.into_iter().zip(sizes) {+ if !batch.is_empty()+ && (batch.len() >= chunk_len || (cap > 0 && batch_bytes + size > cap))+ {+ chunks.push(std::mem::take(&mut batch));+ batch_bytes = 0;+ }+ batch_bytes = batch_bytes.saturating_add(size);+ batch.push(id);+ }+ if !batch.is_empty() {+ chunks.push(batch);+ }+ chunks.retain(|c| c.len() >= 2);+ chunks}Some(_) => Vec::new(),None => policy.select_merges(&segments_snapshot_init),@@ -11496,6 +11555,24 @@ impl Index {};let merge_postings = merge_readers.is_some();+ // Ingest-memory attribution (#948): the replay path holds+ // every input's decompressed postings + norms for the whole+ // batch, and the same bytes bound the writer's in-memory+ // rebuild (a merged posting list is the inputs' lists+ // remapped, not re-derived). `retained_bytes` charges only+ // what the reader OWNS (an mmap'd `.post` contributes 0),+ // matching what this batch adds to the heap.+ let merge_reader_retained = merge_readers.as_ref().map(|readers| {+ let bytes: u64 = readers+ .iter()+ .map(|reader| reader.retained_bytes())+ .sum();+ crate::ingest_memory::Retained::new(+ crate::ingest_memory::Category::MergeDecoded,+ bytes as usize,+ )+ });+// Per-phase attribution of one merge batch, gated on// XERJ_PROF, matching the flush path's `XERJ_PROF// flush-sidecar` line. The #876 A/B is read off `fts_us`.@@ -11560,6 +11637,10 @@ impl Index {// doc ids, and the global `_seq_no` sort below scrambles the// per-input order, so the pair has to ride along.let mut survivors: Vec<(u64, String, String, u32, u32)> = Vec::new();+ // #948 attribution: running estimate of the survivor+ // set's retained bytes (raw JSON + id + tuple), observed+ // once per input segment as a sampled checkpoint.+ let mut survivor_bytes: usize = 0;// One entry per document in each input segment, in that// segment's own ordinal order: the merged ordinal it becomes,// or `None` if it does not survive.@@ -11688,6 +11769,15 @@ impl Index {return None;}};+ // Ingest-memory attribution (#948): one guard per+ // input for its decompressed stored section, held+ // until this iteration ends (the RawValue parse and+ // the survivor scan both read it; the buffer drops+ // with the iteration scope).+ let _stored_guard = crate::ingest_memory::Retained::new(+ crate::ingest_memory::Category::MergeDecoded,+ stored_bytes.len(),+ );// `Box<RawValue>` uses a serde-private newtype tag that// simd_json's serde adapter does not recognise — the// deserialiser fails with "invalid type: newtype struct,@@ -11755,8 +11845,21 @@ impl Index {source_index as u32,source_ordinal as u32,));+ survivor_bytes = survivor_bytes.saturating_add(+ raw_str.len()+ + id_seq.id.len()+ + std::mem::size_of::<(u64, String, String, u32, u32)>(),+ );}// raw_docs + stored_bytes drop here — segment RAM reclaimed.+ // One sampled checkpoint per input segment: the+ // survivor set grows monotonically inside the input+ // loop, so the trailing edge of the peak is at most+ // one input's worth of growth (#948 attribution).+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeSurvivor,+ survivor_bytes,+ );}// Global insertion-order (_seq_no) sort — see the B1 note@@ -11767,6 +11870,8 @@ impl Index {// Single sorted stream → all four outputs. `into_iter`// frees each raw String right after its bytes are copied// into `merged_json_buf`, keeping peak memory ~1× stored.+ let mut drain_checkpoint = 0u64;+ let mut fts_input_bytes: usize = 0;for (seq_no, id_str, raw_str, source_index, source_ordinal) in survivors {if !first_doc {merged_json_buf.push(b',');@@ -11813,13 +11918,50 @@ impl Index {} else {extract_fts_fields_excluding(&source, &excluded_fts_fields_for_task)};+ // #948 attribution: the Value tree the FTS/DV passes+ // hold until the end of the batch. The walk is+ // per-document but only when tracing is enabled.+ if crate::ingest_memory::enabled() {+ fts_input_bytes = fts_input_bytes+ .saturating_add(crate::ingest_memory::estimated_json_heap(+ doc_value.get("_source").unwrap_or(&Value::Null),+ ));+ }fts_input.push((id_str, fields, source));+ // Sampled checkpoints every 8192 drained docs: the+ // survivor set shrinks as `merged_json_buf` and+ // `fts_input` grow, so the crossover IS the batch's+ // stored-side peak.+ drain_checkpoint += 1;+ if drain_checkpoint.is_multiple_of(8192) {+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeJsonBuffer,+ merged_json_buf.len(),+ );+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeParsed,+ fts_input_bytes,+ );+ }}+ // Drained: the survivors vec is empty now.+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeSurvivor,+ 0,+ );if live_doc_count == 0 {return None;}merged_json_buf.push(b']');+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeJsonBuffer,+ merged_json_buf.len(),+ );+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeParsed,+ fts_input_bytes,+ );// Write merged stored section using the columnar v2 codec.let mut writer = match SegmentWriter::new(&segments_dir_for_task, 1, 0, 0) {@@ -11835,8 +11977,19 @@ impl Index {&merged_json_buf,merge_zstd_level,);+ // #948 attribution: the compressed output buffer is an+ // exact owned length; it coexists with the drained buffer+ // for one encode call.+ let _encoded_guard = crate::ingest_memory::Retained::new(+ crate::ingest_memory::Category::MergeEncoded,+ encoded.len(),+ );let stored_us = stored_timer.elapsed().as_micros();drop(merged_json_buf);+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeJsonBuffer,+ 0,+ );if let Err(e) = writer.add_section(SectionType::Stored, &encoded) {tracing::error!("merge ABORTED: failed to add section: {e}");failed_for_task.fetch_add(1, Ordering::Relaxed);@@ -11989,6 +12142,7 @@ impl Index {// Release the inputs' decompressed postings before the// doc-values build, which is now the batch's memory peak.drop(merge_readers);+ drop(merge_reader_retained);// Update version_map so doc → segment_id points to the// merged segment, using each doc's REAL seq_no from@@ -12041,6 +12195,13 @@ impl Index {}let dv_us = dv_timer.elapsed().as_micros();+ // `fts_input` (raw ids + the per-doc `_source` Value+ // trees) survives its last reader here — the batch's+ // parsed-side attribution ends with it.+ crate::ingest_memory::observe_checkpoint(+ crate::ingest_memory::Category::MergeParsed,+ 0,+ );if prof {eprintln!("XERJ_PROF merge-batch inputs={} docs={live_doc_count} \@@ -22146,6 +22307,14 @@ impl Index {self.memtable.size_bytes()}+ /// #948 — entries currently resident in the STORAGE memtable+ /// (`IndexStore::memtable_shards`). Diagnostic twin of+ /// [`Self::memtable_bytes`]: the FTS memtable drains on every flush,+ /// the storage one used to never drain at all.+ pub fn resident_memtable_entries(&self) -> usize {+ self.store.resident_memtable_entries()+ }+pub fn flush_threshold(&self) -> usize {self.flush_byte_threshold}@@ -29056,14 +29225,20 @@ async fn do_flush_shard(let storage_entries: Vec<xerj_storage::index_store::MemEntry> = raw.into_iter()- .map(- |(seq_no, doc_id, arc, raw_bytes)| xerj_storage::index_store::MemEntry {+ .map(|(seq_no, doc_id, arc, raw_bytes)| {+ let charge = if !raw_bytes.is_empty() {+ raw_bytes.len() as u64+ } else {+ xerj_storage::index_store::estimate_value_bytes(&arc)+ };+ xerj_storage::index_store::MemEntry {seq_no,doc_id,source: Some(arc),source_bytes: raw_bytes,- },- )+ charge,+ }+ }).collect();let storage_drained = xerj_storage::index_store::DrainedMemtable {entries: storage_entries,@@ -43924,6 +44099,16 @@ fn warm_segment_at_publish(if *NO_WARM {return;}+ // Issue #948 — publish warming retains ~10-15× the flushed segment's+ // raw bytes. Doing that while the parent memory breaker is ENGAGED buys+ // query latency with exactly the memory the process just ran out of,+ // and the warmer fills the segment-hydration budget with artifacts at+ // the worst moment (the breaker only rejects; it cannot reclaim what+ // warming keeps re-adding). Skip when engaged — the next read+ // re-hydrates on demand, and warming resumes once memory frees up.+ if crate::governor::global().is_some_and(|g| g.memory_breaker_engaged()) {+ return;+ }// 1. Stored slices.if !caches.slices.contains_key(seg_id) {let built: Option<StoredSlices> = (|| {diff --git a/engine/crates/xerj-engine/src/ingest_memory.rs b/engine/crates/xerj-engine/src/ingest_memory.rsindex ea58c6374..c84b9ec10 100644--- a/engine/crates/xerj-engine/src/ingest_memory.rs+++ b/engine/crates/xerj-engine/src/ingest_memory.rs@@ -6,10 +6,13 @@//! constructing events.//!//! `summary` is the only enabled mode in v1: it emits bounded periodic-//! start/snapshot/stop NDJSON. Lifecycle `EventKind` variants and merge/cache-//! categories are reserved schema vocabulary; until their owners are wired,-//! their measurements are `unavailable` and their gauges must not be treated-//! as measured zero.+//! start/snapshot/stop NDJSON. Lifecycle `EventKind` variants beyond the+//! trace lifecycle remain reserved schema vocabulary; until their owners are+//! wired, their measurements are `unavailable` and their gauges must not be+//! treated as measured zero. The cache categories are charged by the segment+//! hydration budget at every admission, and the merge categories are charged+//! by the merge task (guards for whole buffers, sampled checkpoints for+//! per-document streams) — see `run_merge_once` in `crate::index`.//!//! `MemtableActive` is sampled from the engine while `FlushDrained` is owned at//! the authoritative drain boundary. Those authorities cannot be sampled@@ -498,8 +501,24 @@ fn measurement(category: Category) -> Measurement {| Category::CacheSortShadow| Category::CacheIdPositions| Category::CacheRowSequences- | Category::CacheDecodedStored => Measurement::Estimated,- _ => Measurement::Unavailable,+ | Category::CacheDecodedStored+ | Category::CacheFtsReader+ | Category::MergeDecoded+ | Category::MergeSurvivor+ | Category::MergeParsed => Measurement::Estimated,+ // Exact owned buffer lengths observed at the buffer boundary.+ Category::MergeJsonBuffer | Category::MergeEncoded => Measurement::SerializedSize,+ }+}++/// Sampled checkpoint for a merge-owned buffer whose size changes per+/// document (`survivors`, `merged_json_buf`, `fts_input`). One atomic+/// transition per checkpoint instead of one per document; the sampled peak+/// can trail the true peak by up to one checkpoint interval of growth, which+/// the `Estimated` measurement kind already admits.+pub(crate) fn observe_checkpoint(category: Category, bytes: usize) {+ if let Some(ledger) = active_ledger() {+ ledger.observe(category, bytes);}}diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rsindex f040c72a6..089f6a490 100644--- a/engine/crates/xerj-engine/src/memtable.rs+++ b/engine/crates/xerj-engine/src/memtable.rs@@ -182,6 +182,33 @@ struct MemEntry {size_bytes: usize,}+/// Charge for one raw-bytes (turbo `_bulk`) memtable entry — issue #948.+///+/// The entry retains the full NDJSON payload plus the doc-id string twice+/// (`doc_id_index` key + `MemEntry.doc_id`) and the entry/index nodes; the+/// parsed `Value` and postings are deferred to the flush thread, so the+/// payload length IS the honest hot-path footprint. The historical flat+/// 800-byte estimate stays as the floor so compressed log docs (~115 B)+/// keep their exact M5.6/M5.17 charge and flush cadence — only docs larger+/// than the floor charge more, which is precisely the case where the flat+/// number let a ~10 KB mailbox doc count as 800 bytes while the+/// process-wide memtable budget believed it had 12× more headroom than it+/// did.+const RAW_BYTES_CHARGE_FLOOR: usize = 800;+/// `MemEntry` + Arc header + `doc_id_index` node allowance for one raw-bytes+/// entry. Sized from the struct fields (2×u64, 2×String, Arc<Value>,+/// Arc<[u8]>, OnceLock, usize ≈ 100 B) plus a hash-map node (~48 B).+const RAW_BYTES_ENTRY_OVERHEAD: usize = 160;++fn raw_bytes_charge(doc_id: &str, source_bytes: &[u8]) -> usize {+ RAW_BYTES_CHARGE_FLOOR.max(+ source_bytes+ .len()+ .saturating_add(doc_id.len())+ .saturating_add(RAW_BYTES_ENTRY_OVERHEAD),+ )+}+/// Reconstruct the (field_name → flattened text) map that pre-M4.9/// `MemEntry` used to cache eagerly at ingest time. Called only by/// the legacy `drain_with_sources` / `drain` / `get_source` paths, which@@ -2591,14 +2618,23 @@ impl FtsMemtable {doc_id: String,source_bytes: Arc<[u8]>,) {- // M5.6 flat-800-byte estimate retained — changing it to a- // per-doc `source_bytes.len()` in M5.17 regressed ingest- // throughput (varies 400-640 k vs 870 k baseline) because- // the math interacts non-obviously with the shard flush- // scheduler. Revert. The 800-byte number over-estimates- // compressed log docs by ~7× but keeps the flush cadence- // predictable.- let estimated = 800usize;+ // Issue #948 — the charge must be an estimate of what this entry+ // actually retains. On this path that is the raw NDJSON payload+ // (`source_bytes`), the doc-id string (duplicated into+ // `doc_id_index` and `MemEntry`), and the entry/index nodes — the+ // parsed `Value` and postings are built later, on the flush thread.+ //+ // History, so nobody re-breaks M5.17: a bare `source_bytes.len()`+ // charge there regressed log-ingest throughput (400-640 k vs 870 k+ // docs/s) by disturbing the shard flush scheduler's cadence for+ // SMALL docs. The flat 800 bytes stays as the FLOOR — compressed+ // log docs (~115 B) keep their exact historical charge and cadence —+ // but a mailbox-shaped doc (~10 KB of raw JSON retained verbatim)+ // now charges its real footprint. At 800 B/doc the process-wide+ // memtable budget (governor item 1) was admitting ~12× more live+ // bytes than it was told about, which is exactly how the #948+ // mailbox ingest overshot the memory cap while "under budget".+ let estimated = raw_bytes_charge(&doc_id, &source_bytes);self.total_bytes += estimated;self.aggregate_bytes.fetch_add(estimated, Ordering::Relaxed);@@ -2624,7 +2660,7 @@ impl FtsMemtable {/// Currently we still clone since stable Rust HashMap requires an/// owned key; the gain is skipping the prior `remove()` miss lookup.pub fn insert_raw_bytes_fresh(&mut self, seq_no: u64, doc_id: String, source_bytes: Arc<[u8]>) {- let estimated = 800usize;+ let estimated = raw_bytes_charge(&doc_id, &source_bytes);self.total_bytes += estimated;self.aggregate_bytes.fetch_add(estimated, Ordering::Relaxed);@@ -5871,4 +5907,48 @@ mod aggregate_bytes_tests {check("drain_with_sources");assert_eq!(mem.size_bytes(), 0, "fully drained memtable must read 0");}++ /// Issue #948: the raw-bytes entry charge must track what the entry+ /// actually retains. A mailbox-shaped doc (~10 KB of NDJSON held+ /// verbatim until flush) must charge at least its payload length — the+ /// pre-fix flat 800 bytes let the process-wide memtable budget admit+ /// ~12× more live bytes than it was told about. Small (log-shaped) docs+ /// must keep the historical 800-byte floor so the M5.17 flush-cadence+ /// behaviour is byte-for-byte unchanged for them.+ ///+ /// Uses only the public insert/size_bytes surface (no helper symbols+ /// introduced by the fix) so the mailbox assertion is a mechanical+ /// FAIL-BEFORE on pre-fix source: it charged 800 there.+ #[test]+ fn raw_bytes_charge_tracks_payload_with_an_800_byte_floor() {+ use std::sync::Arc as StdArc;++ let registry = StdArc::new(AnalyzerRegistry::default());+ let mem = ShardedFtsMemtable::with_registry_and_shards(registry, 2);++ // Small (log-shaped) doc: keeps the historical flat charge exactly.+ mem.insert_raw_bytes_with_seq(+ 1,+ "id-1".to_string(),+ StdArc::from(&b"{\"body\":\"log line\"}"[..]),+ );+ assert_eq!(+ mem.size_bytes(),+ 800,+ "small docs must keep the M5.6/M5.17 flat charge and flush cadence"+ );++ // Mailbox-shaped doc: must charge at least its own payload length.+ let payload = vec![b'x'; 9_830];+ mem.insert_raw_bytes_with_seq(+ 2,+ "message-42".to_string(),+ StdArc::from(payload.clone().into_boxed_slice()),+ );+ assert!(+ mem.size_bytes() >= 800 + payload.len(),+ "memtable size_bytes must not under-count a mailbox-sized doc by ~12x (pre-fix: 800/doc)"+ );+ assert_eq!(mem.size_bytes(), recount(&mem));+ }}diff --git a/engine/crates/xerj-engine/tests/drain_releases_memory.rs b/engine/crates/xerj-engine/tests/drain_releases_memory.rsnew file mode 100644index 000000000..9cd5f7365--- /dev/null+++ b/engine/crates/xerj-engine/tests/drain_releases_memory.rs@@ -0,0 +1,186 @@+//! Issue #948: a memory-pressure drain must flush every loaded index and+//! release its rebuildable caches WITHOUT closing anything — the parent RSS+//! breaker now requests this drain when it engages, because a breaker that+//! only rejects (429) frees nothing and a cache-heavy ingest never finishes+//! under a memory cap.+//!+//! The drain is the `close_index` (#463) flush+release pair applied to every+//! loaded index at once, minus the closed flag. These tests pin the two+//! properties that pair must keep: data safety (flush-first, so+//! memtable-resident docs survive) and service continuity (the index stays+//! loaded and queryable, reads re-hydrate from disk).++use serde_json::json;+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::{FieldConfig, FieldType, Schema};+use xerj_engine::Engine;+use xerj_query::parse_request;++fn make_engine(dir: &TempDir) -> Engine {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ Engine::new(config).expect("engine::new")+}++async fn count_all(engine: &Engine, name: &str) -> u64 {+ let idx = engine.get_index(name).expect("get index");+ let req = parse_request(&json!({ "query": { "match_all": {} }, "size": 0, "from": 0 }))+ .expect("parse_request");+ idx.search(&req).await.expect("search").total.value+}++async fn seed(engine: &Engine, name: &str, n: usize) {+ let mut schema = Schema::empty();+ schema+ .fields+ .push(FieldConfig::new("body", FieldType::Text));+ engine.create_index(name, schema).expect("create");+ let idx = engine.get_index(name).expect("get");+ for i in 0..n {+ idx.index_document(+ Some(format!("d{i}")),+ json!({ "body": format!("document number {i}") }),+ )+ .await+ .expect("index");+ }+}++/// Run a size>0 search so the per-segment caches actually hydrate.+async fn hydrate(engine: &Engine, name: &str) -> u64 {+ let idx = engine.get_index(name).expect("get index");+ let req = parse_request(&json!({ "query": { "match": { "body": "document" } }, "size": 25 }))+ .expect("parse_request");+ idx.search(&req).await.expect("search").total.value+}++/// The drain releases every loaded index's caches and keeps the index in+/// service: loaded, not closed, queryable, lossless. FAIL-BEFORE: with the+/// `idx.release_memory()` call inside `drain_rebuildable_memory` reverted,+/// `total_cache_entries == 0` fails.+#[tokio::test]+async fn drain_releases_caches_and_keeps_indexes_in_service() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ seed(&engine, "docs", 50).await;+ engine.get_index("docs").unwrap().refresh().await.unwrap();++ hydrate(&engine, "docs").await;+ let cached_before = engine.get_index("docs").unwrap().total_cache_entries();+ assert!(+ cached_before > 0,+ "a query should have hydrated the caches, got {cached_before}"+ );++ let drained = engine.drain_rebuildable_memory().await;+ assert_eq!(drained, 1, "one loaded index must be drained");+ assert!(+ engine.is_index_loaded("docs"),+ "a drain never closes or unloads an index"+ );+ assert!(+ !engine.closed_indices.contains_key("docs"),+ "a drain must not mark the index closed"+ );+ let cached_after = engine.get_index("docs").unwrap().total_cache_entries();+ assert_eq!(+ cached_after, 0,+ "#948: the drain must release resident caches (was {cached_before}, now {cached_after})"+ );+ // Reads still work — caches re-hydrate from disk on demand.+ assert_eq!(count_all(&engine, "docs").await, 50);+}++/// Data-safety: documents still in the memtable (never refreshed/flushed)+/// must survive the drain — it flushes FIRST, exactly like `close_index`+/// (#463). Guards against a memory win that silently drops unflushed writes.+#[tokio::test]+async fn drain_flushes_so_unrefreshed_docs_survive() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ seed(&engine, "docs", 30).await; // NO refresh — docs sit in the memtable/WAL++ let drained = engine.drain_rebuildable_memory().await;+ assert_eq!(drained, 1);+ assert_eq!(+ engine.get_index("docs").unwrap().memtable_bytes(),+ 0,+ "the drain must leave the memtable empty"+ );+ assert_eq!(+ count_all(&engine, "docs").await,+ 30,+ "#948: drain must flush before releasing — no doc may be lost"+ );+}++/// A closed index is skipped (its caches were already released by+/// `close_index`), and its existence must not abort the drain for the rest.+#[tokio::test]+async fn drain_skips_closed_indexes_and_drains_the_rest() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ seed(&engine, "open-docs", 10).await;+ seed(&engine, "closed-docs", 10).await;+ engine.close_index("closed-docs").await.expect("close");++ let drained = engine.drain_rebuildable_memory().await;+ assert_eq!(+ drained, 1,+ "only the loaded-and-open index counts; closed caches were freed at close"+ );+ assert_eq!(count_all(&engine, "open-docs").await, 10);+}++/// #948 — the storage memtable must not retain one parsed `Arc<Value>` per+/// explicit-id write forever.+///+/// The engine flush path drains the FTS memtable and builds its+/// `DrainedMemtable` from THAT; `IndexStore::memtable_shards` (pushed by+/// every `store.index()` / `index_batch()` — the per-doc route explicit-id+/// bulk takes) was never drained on that path, so every flush left the full+/// parsed document trees resident for the life of the process. Measured as+/// the dominant un-attributed at-rest RSS on mailbox-shaped bulk loads+/// (~2.4-3.1x source bytes). `prune_published_memtable`, run at the end of+/// every successful `finalize_flush_with_publisher`, drops them once the+/// version map repoints at the published segment.+///+/// FAIL-BEFORE: with the `prune_published_memtable()` call in+/// `finalize_flush_with_publisher` reverted (but this test and the accessor+/// kept), `resident == 0` fails — entries survive the flush.+#[tokio::test]+async fn flush_prunes_published_storage_memtable_entries() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ // seed() writes with an explicit id → the per-doc `store.index()` path+ // that pushes a MemEntry per doc.+ seed(&engine, "docs", 40).await;+ let idx = engine.get_index("docs").unwrap();+ let before = idx.resident_memtable_entries();+ assert!(+ before >= 40,+ "explicit-id writes must land in the storage memtable, got {before}"+ );++ idx.refresh().await.expect("refresh");++ // refresh → flush is async (spawned finalize); poll for completion.+ let mut resident = before;+ for _ in 0..200 {+ resident = idx.resident_memtable_entries();+ if resident == 0 {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ assert_eq!(+ resident, 0,+ "#948: a completed flush must prune the storage memtable entries it \+ published (started at {before})"+ );++ // And the prune dropped nothing the index still needs: all docs+ // readable, all durable.+ assert_eq!(count_all(&engine, "docs").await, 40);+}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex cd7812c42..aa2960ff7 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -2477,7 +2477,24 @@ async fn async_main() -> Result<()> {// parent circuit breaker and the disk flood-stage write block. This// is the structural guard against the 112 GiB OOM class — writes get// a 429 circuit_breaking_exception before the kernel OOM-kills us.+ // Since #948 the sampler also requests a memory-pressure DRAIN+ // (flush + cache release) when the breaker engages; the purge hook+ // installed just below is what lets that drain actually lower RSS+ // under jemalloc, which otherwise keeps freed pages resident.if storage_available {+ xerj_engine::engine::set_allocator_purge_hook(std::sync::Arc::new(|| {+ // Refresh the cached stats first (the epoch mallctl is what makes+ // the stats reads in the ingest-memory ledger coherent), then+ // purge every arena's dirty pages back to the OS. 4096 is+ // MALLCTL_ARENAS_ALL. Both are best-effort: a failing mallctl+ // must never propagate out of the drain path.+ let _ = tikv_jemalloc_ctl::epoch::advance();+ // SAFETY: `arena.<i>.purge` with i = MALLCTL_ARENAS_ALL (4096)+ // is a plain "purge every arena" action mallctl; the value is an+ // unused unsigned scalar. The name is NUL-terminated and names a+ // real jemalloc ctl node, so the write cannot read out of bounds.+ let _ = unsafe { tikv_jemalloc_ctl::raw::write(b"arena.4096.purge\0", 0u64) };+ }));state.engine.spawn_resource_sampler();}diff --git a/engine/crates/xerj-storage/src/index_store.rs b/engine/crates/xerj-storage/src/index_store.rsindex 7aba2d6ad..178ce31e9 100644--- a/engine/crates/xerj-storage/src/index_store.rs+++ b/engine/crates/xerj-storage/src/index_store.rs@@ -160,6 +160,50 @@ pub struct MemEntry {/// writer uses these directly instead of re-serializing the Value —/// saving ~500ns/doc on the flush hot path.pub source_bytes: std::sync::Arc<[u8]>,+ /// Heap bytes this entry charges to `memtable_bytes` (raw bytes length,+ /// or a structural estimate of the parsed `source`). Carried ON the+ /// entry so `prune_published_memtable` can recompute the counter+ /// exactly, without re-serialising anything.+ pub charge: u64,+}++/// Fixed charge for a tombstone `MemEntry` (String doc_id + SeqNo + Arcs).+const TOMBSTONE_CHARGE: u64 = 64;++/// Structural heap estimate for a parsed source document.+///+/// `source.to_string().len()` (the pre-#948 accounting) serialises the whole+/// document on every write just to measure it — a full JSON render per doc on+/// the explicit-id bulk path. Walking the tree costs no formatting and no+/// allocation and stays within ~10 % of the serialised length on+/// mailbox-shaped documents (many medium string fields).+pub fn estimate_value_bytes(v: &serde_json::Value) -> u64 {+ match v {+ serde_json::Value::Null => 8,+ serde_json::Value::Bool(_) => 1,+ serde_json::Value::Number(n) => n.to_string().len() as u64 + 8,+ serde_json::Value::String(s) => s.len() as u64 + 16, // header + heap buf+ serde_json::Value::Array(a) => 8 + a.iter().map(estimate_value_bytes).sum::<u64>(),+ serde_json::Value::Object(m) => {+ // IndexMap bucket: key String + value + bucket overhead.+ 32 + m+ .iter()+ .map(|(k, v)| (k.len() as u64 + 16) + estimate_value_bytes(v))+ .sum::<u64>()+ }+ }+}++impl MemEntry {+ /// Charge for a live entry: raw bytes when present (the turbo-raw bulk+ /// path), else the structural estimate of the parsed source.+ fn charge_for(source: &serde_json::Value, source_bytes: &std::sync::Arc<[u8]>) -> u64 {+ if !source_bytes.is_empty() {+ source_bytes.len() as u64+ } else {+ estimate_value_bytes(source)+ }+ }}/// Opaque handle holding a drained memtable.@@ -1675,7 +1719,8 @@ impl IndexStore {wal.append(&entry)?};- let source_len = source.to_string().len();+ let source_bytes = std::sync::Arc::from(&[][..]);+ let charge = MemEntry::charge_for(&source, &source_bytes);self.version_map.set(&doc_id, seq_no, IN_MEMORY_SEGMENT_ID, false);@@ -1685,10 +1730,10 @@ impl IndexStore {seq_no,doc_id,source: Some(std::sync::Arc::new(source)),- source_bytes: std::sync::Arc::from(&[][..]),+ source_bytes,+ charge,});- self.memtable_bytes- .fetch_add(source_len as u64, Ordering::Relaxed);+ self.memtable_bytes.fetch_add(charge, Ordering::Relaxed);debug!(seq_no, "document indexed");Ok(seq_no)@@ -1731,18 +1776,19 @@ impl IndexStore {let seq_no = seq_nos[i];self.version_map.set(doc_id, seq_no, IN_MEMORY_SEGMENT_ID, false);- let source_len = source.to_string().len();+ let source_bytes = std::sync::Arc::from(&[][..]);+ let charge = MemEntry::charge_for(source, &source_bytes);let shard = self.shard_for(doc_id);let mut mem = self.memtable_shards[shard].lock().unwrap();mem.push(MemEntry {seq_no,doc_id: doc_id.clone(),source: Some(std::sync::Arc::new(source.clone())),- source_bytes: std::sync::Arc::from(&[][..]),+ source_bytes,+ charge,});drop(mem);- self.memtable_bytes- .fetch_add(source_len as u64, Ordering::Relaxed);+ self.memtable_bytes.fetch_add(charge, Ordering::Relaxed);}Ok(seq_nos)@@ -1801,7 +1847,10 @@ impl IndexStore {doc_id: doc_id.to_owned(),source: None,source_bytes: std::sync::Arc::from(&[][..]),+ charge: TOMBSTONE_CHARGE,});+ self.memtable_bytes+ .fetch_add(TOMBSTONE_CHARGE, Ordering::Relaxed);Ok(Some(seq_no))}@@ -1863,14 +1912,7 @@ impl IndexStore {}) {continue;}- restored_bytes = restored_bytes.saturating_add(if !entry.source_bytes.is_empty() {- entry.source_bytes.len() as u64- } else {- entry- .source- .as_ref()- .map_or(0, |source| source.to_string().len() as u64)- });+ restored_bytes = restored_bytes.saturating_add(entry.charge);mem.push(entry.clone());}self.memtable_bytes@@ -1924,6 +1966,13 @@ impl IndexStore {{let entries = &drained.entries;if entries.is_empty() {+ let pruned = self.prune_published_memtable();+ if pruned > 0 {+ debug!(+ pruned,+ "pruned published storage memtable entries (empty flush)"+ );+ }return Ok(FlushFinalizeOutcome::Empty);}@@ -2369,6 +2418,10 @@ impl IndexStore {segment_id,doc_count, min_seq, max_seq, "segment published with deferred maintenance");+ let pruned = self.prune_published_memtable();+ if pruned > 0 {+ debug!(pruned, "pruned published storage memtable entries");+ }return Ok(FlushFinalizeOutcome::Published {meta,maintenance_deferred: true,@@ -2397,6 +2450,12 @@ impl IndexStore {}info!(segment_id, doc_count, min_seq, max_seq, "segment flushed");+ // #948 — the segment is durable and the version map repointed:+ // drop the storage-memtable `Arc<Value>` copies these docs held.+ let pruned = self.prune_published_memtable();+ if pruned > 0 {+ debug!(pruned, "pruned published storage memtable entries");+ }Ok(FlushFinalizeOutcome::Published {meta,maintenance_deferred: false,@@ -2412,6 +2471,82 @@ impl IndexStore {}}+ /// Drop memtable entries whose durable copy no longer needs the in-memory+ /// one, returning the number of entries removed. Issue #948.+ ///+ /// An entry is retained only while the version map still resolves its+ /// `doc_id` to THIS entry — i.e. `segment_id == __memtable__` at exactly+ /// this `seq_no`. Once a flush repoints the doc at a real segment (or a+ /// newer write/delete supersedes this seq_no), the entry's+ /// `Arc<serde_json::Value>` — the full parsed document tree — is dead+ /// weight, but nothing used to remove it: the engine flush path drains+ /// the FTS memtable and builds its `DrainedMemtable` from THAT, so+ /// `memtable_shards` was never drained and one `Arc<Value>` per+ /// explicit-id write was retained for the life of the process (freed+ /// only by a DELETE of the doc). Measured: ~2.4-3.1x source bytes of+ /// un-attributed at-rest RSS on mailbox-shaped bulk loads.+ ///+ /// Called at the end of every successful+ /// [`finalize_flush_with_publisher`], which covers the engine flush+ /// path, the legacy `flush_with_publisher`, and crash-recovery replay+ /// flushes. Convergence, not exactness: entries flushed by a CONCURRENT+ /// finalize that has not yet repointed the version map simply survive+ /// until the next prune.+ pub fn prune_published_memtable(&self) -> usize {+ let mut removed = 0usize;+ let mut removed_charge = 0u64;+ for shard in &self.memtable_shards {+ let mut mem = shard.lock().unwrap();+ let before = mem.len();+ mem.retain(|entry| {+ let live = self.version_map.get(&entry.doc_id).is_some_and(|current| {+ current.seq_no == entry.seq_no+ && current.segment_id.as_ref() == IN_MEMORY_SEGMENT_ID+ });+ if !live {+ removed_charge = removed_charge.saturating_add(entry.charge);+ }+ live+ });+ removed += before - mem.len();+ }+ if removed > 0 {+ self.memtable_bytes_sub_clamped(removed_charge);+ }+ removed+ }++ /// Test/diagnostic accessor: number of entries currently resident in the+ /// storage memtable shards.+ pub fn resident_memtable_entries(&self) -> usize {+ self.memtable_shards+ .iter()+ .map(|shard| shard.lock().unwrap().len())+ .sum()+ }++ /// `memtable_bytes.fetch_sub` that clamps at zero instead of wrapping.+ ///+ /// Entries pushed by WAL replay before #948 never incremented the+ /// counter, so a prune can in principle subtract more than was added;+ /// the counter only feeds `maybe_flush`, where a wrapped (huge) value+ /// would flap the threshold forever.+ fn memtable_bytes_sub_clamped(&self, delta: u64) {+ let mut current = self.memtable_bytes.load(Ordering::Relaxed);+ loop {+ let next = current.saturating_sub(delta);+ match self.memtable_bytes.compare_exchange_weak(+ current,+ next,+ Ordering::Relaxed,+ Ordering::Relaxed,+ ) {+ Ok(_) => return,+ Err(actual) => current = actual,+ }+ }+ }+// ── Read path ─────────────────────────────────────────────────────────────/// Load the current snapshot. Lock-free.@@ -3660,14 +3795,19 @@ impl IndexStore {if !already_persisted {self.version_map.set(&doc_id, seq_no, IN_MEMORY_SEGMENT_ID, false);+ let source_bytes = std::sync::Arc::from(&[][..]);+ let charge = MemEntry::charge_for(&source, &source_bytes);let shard = self.shard_for(&doc_id);let mut mem = self.memtable_shards[shard].lock().unwrap();mem.push(MemEntry {seq_no,doc_id,source: Some(std::sync::Arc::new(source)),- source_bytes: std::sync::Arc::from(&[][..]),+ source_bytes,+ charge,});+ drop(mem);+ self.memtable_bytes.fetch_add(charge, Ordering::Relaxed);}}WalEntry::Delete { doc_id } => {@@ -3730,7 +3870,11 @@ impl IndexStore {doc_id,source: None,source_bytes: std::sync::Arc::from(&[][..]),+ charge: TOMBSTONE_CHARGE,});+ drop(mem);+ self.memtable_bytes+ .fetch_add(TOMBSTONE_CHARGE, Ordering::Relaxed);}WalEntry::UpdateMapping { .. } => {}}@@ -6619,4 +6763,92 @@ mod tests {.unwrap_err();assert!(matches!(error, MergePublicationError::Indeterminate { .. }));}++ // ── #948: storage memtable prune on flush completion ────────────────────++ fn store_with_memtable(path: &std::path::Path) -> Arc<IndexStore> {+ IndexStore::open(+ path,+ IndexStoreConfig {+ sync_mode: SyncMode::Batched,+ ..Default::default()+ },+ )+ .unwrap()+ }++ /// The engine flush path reproduces the #948 leak at its smallest:+ /// `store.index()` pushes a `MemEntry` into `memtable_shards`, the+ /// engine finalises a flush built from an EXTERNAL `DrainedMemtable`+ /// (its own FTS memtable drain) which repoints the version map at the+ /// new segment — and pre-#948 nothing ever removed the storage-side+ /// entry, retaining one `Arc<Value>` per explicit-id write for the+ /// life of the process.+ ///+ /// FAIL-BEFORE: with the `prune_published_memtable()` call in+ /// `finalize_flush_with_publisher` reverted (test and accessors kept),+ /// `resident == 0` fails — the entry survives the publish.+ #[test]+ fn flush_finalize_prunes_published_storage_memtable() {+ let dir = tempfile::tempdir().unwrap();+ let store = store_with_memtable(dir.path());+ let source = serde_json::json!({"v": 1});+ let seq_no = store.index("doc-1", source.clone()).unwrap();+ assert_eq!(store.resident_memtable_entries(), 1);++ // Exactly what `Index::do_flush_shard` does: hand finalize a+ // DrainedMemtable built from the engine-side (FTS) drain — the+ // storage shards are NOT drained and still hold the entry above.+ let drained = DrainedMemtable {+ entries: vec![MemEntry {+ seq_no,+ doc_id: "doc-1".to_string(),+ source: Some(std::sync::Arc::new(source)),+ source_bytes: std::sync::Arc::from(&[][..]),+ charge: 64,+ }],+ };+ match store+ .finalize_flush_with_publisher(&drained, |_| Ok(()))+ .unwrap()+ {+ FlushFinalizeOutcome::Published { .. } => {}+ other => panic!("expected Published, got {other:?}"),+ }++ assert_eq!(+ store.resident_memtable_entries(),+ 0,+ "#948: once the version map repoints at the published segment, \+ the storage memtable entry must be pruned"+ );+ }++ /// The prune is conservative where it must be and exact where it can:+ /// a still-live write and a memtable-resident tombstone survive, while+ /// an entry superseded by a newer write of the same doc (still in the+ /// memtable, nothing published) is stale and dropped.+ #[test]+ fn prune_keeps_unpublished_entries() {+ let dir = tempfile::tempdir().unwrap();+ let store = store_with_memtable(dir.path());+ store.index("live", serde_json::json!({"v": 1})).unwrap();+ store+ .index("overwritten", serde_json::json!({"v": 1}))+ .unwrap();+ store.delete("overwritten").unwrap();+ assert_eq!(+ store.resident_memtable_entries(),+ 3,+ "two writes + one tombstone"+ );++ let removed = store.prune_published_memtable();+ assert_eq!(+ removed, 1,+ "only the entry superseded by the newer tombstone is prunable"+ );+ let resident = store.resident_memtable_entries();+ assert_eq!(resident, 2, "the live write and the tombstone stay");+ }}diff --git a/engine/crates/xerj-storage/src/merge.rs b/engine/crates/xerj-storage/src/merge.rsindex 0bf2c932f..628bc5a6c 100644--- a/engine/crates/xerj-storage/src/merge.rs+++ b/engine/crates/xerj-storage/src/merge.rs@@ -66,6 +66,15 @@ pub struct SizeTieredMergePolicy {/// Maximum size a segment can reach before it is excluded from merges/// (already "large enough").pub max_merged_segment_bytes: u64,+ /// Upper bound on the SUM of input segment bytes in one merge batch.+ /// Issue #948: the merge executor materialises decoded + re-encoded+ /// copies of every input doc in memory (measured 5-9x the input bytes+ /// on mailbox-shaped docs), so an unbounded count-chunked batch of+ /// large segments is an unbounded heap spike. A batch may exceed the+ /// cap only when even the tier's `min_merge_count` smallest segments+ /// already exceed it (otherwise no merge in that tier could ever run).+ /// 0 disables the bound (previous behaviour).+ pub max_batch_input_bytes: u64,}impl Default for SizeTieredMergePolicy {@@ -75,6 +84,7 @@ impl Default for SizeTieredMergePolicy {max_merge_count: 10,tier_floor_bytes: 5 * 1024 * 1024, // 5 MiBmax_merged_segment_bytes: 5 * 1024 * 1024 * 1024, // 5 GiB+ max_batch_input_bytes: 512 * 1024 * 1024, // 512 MiB}}}@@ -121,15 +131,38 @@ impl MergePolicy for SizeTieredMergePolicy {// batches sequentially and the spawn_blocking hand-off keeps// the runtime responsive, so there's no reason to// artificially hold batches back.- let ids: Vec<SegmentId> = segs.into_iter().map(|s| s.id.clone()).collect();+ //+ // #948 — batches are additionally cut on cumulative INPUT+ // bytes (`max_batch_input_bytes`): the executor holds decoded+ // + re-encoded copies of every input doc, so batch heap cost+ // scales with bytes, not segment count. A batch only+ // overruns the cap when `min_merge_count` smallest segments+ // of the tier already exceed it by themselves.+ let id_sizes: Vec<(SegmentId, u64)> = segs+ .into_iter()+ .map(|s| (s.id.clone(), s.size_bytes))+ .collect();let mut start = 0usize;- while start < ids.len() {- let end = (start + self.max_merge_count).min(ids.len());- let batch: Vec<SegmentId> = ids[start..end].to_vec();+ while start < id_sizes.len() {+ let mut batch: Vec<SegmentId> = Vec::new();+ let mut batch_bytes = 0u64;+ let mut i = start;+ while i < id_sizes.len() && batch.len() < self.max_merge_count {+ let (id, size) = &id_sizes[i];+ if self.max_batch_input_bytes > 0+ && batch.len() >= self.min_merge_count+ && batch_bytes + size > self.max_batch_input_bytes+ {+ break;+ }+ batch_bytes = batch_bytes.saturating_add(*size);+ batch.push(id.clone());+ i += 1;+ }if batch.len() >= self.min_merge_count {merges.push(batch);}- start = end;+ start = i;}}merges@@ -577,4 +610,92 @@ mod tests {Err(StorageError::MergeAborted(_))));}++ // ── #948: merge batch input-byte bound ──────────────────────────────────++ fn sized_segment(id: &str, size_bytes: u64) -> SegmentMeta {+ SegmentMeta {+ id: id.to_string(),+ doc_count: 1,+ size_bytes,+ min_seq_no: 0,+ max_seq_no: 1,+ created_at_ms: 0,+ has_tombstones: false,+ seg_path: String::new(),+ sidx_path: String::new(),+ }+ }++ const MI: u64 = 1024 * 1024;++ #[test]+ fn size_tiered_batches_respect_input_byte_cap() {+ // #948 — the merge executor materialises decoded + re-encoded copies+ // of every input document (measured 5-9x input bytes on mailbox+ // docs), so batch heap cost scales with INPUT BYTES, not segment+ // count. A count-chunked batch of large segments is an unbounded+ // heap spike. The default policy caps a batch at 512 MiB.+ let policy = SizeTieredMergePolicy::default();+ let cap = policy.max_batch_input_bytes;+ assert!(cap > 0, "default policy must bound batch input bytes");++ // Ten 100 MiB segments in the same size tier: 1000 MiB of input —+ // one count-chunked batch pre-#948 (max_merge_count = 10). The cap+ // must split them into <= 512 MiB batches.+ let segments: Vec<SegmentMeta> = (0..10)+ .map(|i| sized_segment(&format!("seg-{i}"), 100 * MI))+ .collect();+ let size_of =+ |id: &str| -> u64 { segments.iter().find(|s| s.id == id).unwrap().size_bytes };++ let batches = policy.select_merges(&segments);+ assert!(+ batches.len() >= 2,+ "1000 MiB of input must not land in one batch: {:?}",+ batches+ );+ for batch in &batches {+ let input_bytes: u64 = batch.iter().map(|id| size_of(id)).sum();+ assert!(+ input_bytes <= cap || batch.len() <= policy.min_merge_count,+ "batch of {} segments carries {} MiB > {} MiB cap",+ batch.len(),+ input_bytes / MI,+ cap / MI+ );+ }+ // The bound must not stop the tier converging: every segment that+ // made it into a batch is merged exactly once.+ let merged: std::collections::HashSet<&str> = batches+ .iter()+ .flat_map(|b| b.iter().map(|id| id.as_str()))+ .collect();+ assert_eq!(merged.len(), 10, "all ten segments must still merge");+ }++ #[test]+ fn size_tiered_batch_cap_floor_is_min_merge_count() {+ // When even the tier's `min_merge_count` smallest segments exceed+ // the cap by themselves, the floor wins: a batch of exactly+ // `min_merge_count` is allowed to overrun, otherwise the tier+ // could never merge at all.+ let policy = SizeTieredMergePolicy {+ max_batch_input_bytes: 10 * MI,+ ..Default::default()+ };+ let segments: Vec<SegmentMeta> = (0..8)+ .map(|i| sized_segment(&format!("seg-{i}"), 4 * MI))+ .collect();++ let batches = policy.select_merges(&segments);+ assert!(!batches.is_empty());+ for batch in &batches {+ assert!(+ batch.len() == policy.min_merge_count,+ "cap smaller than min_merge_count inputs must yield exact-floor batches, got {:?}",+ batch+ );+ }+ }}