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(autoindex): report exact code size-limit skips (#2789)
Jarvisc7abfced269c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8ba9d4fbb..565227cda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -76,6 +76,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Code-extraction size skips now report exact file/limit byte counts and+ explain that `--max-file-gb` / `--max-file-mb` / `--max-file-bytes` do not+ raise the separate fixed 2 MiB AST source-file cap. The reason no longer+ assumes that an oversized file must be generated. Help and Perl boundary+ regressions cover this diagnostic follow-up to #2666 (Refs #2745); the cap+ and skipped-file outcomes are unchanged.+- The version map takes about 23% less memory per document (#2427). A32-character lowercase hex id (what `xerj autoindex` writes) or a lowercaseUUID is now packed into 16 bytes inside its bucket instead of paying adiff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 9e765b011..4d36da2c7 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -431,6 +431,9 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20watcher); mutually exclusive with --max-file-gb/-bytes\n\\x20\x20\x20\x20--max-file-bytes <N> same cap expressed in whole bytes; mutually exclusive\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20with --max-file-gb/--max-file-mb\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20AST source files have a separate fixed {code_cap_mib} MiB code cap\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20({code_cap_bytes} bytes); these flags do not raise it. Oversized\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20source is skipped with a size reason, including hand-written code.\n\\x20\x20\x20\x20--sample <N> records sampled per file for inference (default 500)\n\\x20\x20\x20\x20--no-semantic skip semantic_text on body fields (pure BM25+keyword)\n\\x20\x20\x20\x20--code-analyzer <A> standard (default) or code: `code` declares the built-in\n\@@ -845,6 +848,8 @@ pub fn help_text_with(feedback: bool) -> String {default_gets = crate::objwatch::cost::DEFAULT_MAX_MONTHLY_CLASS_B,max_poll = MAX_POLL_INTERVAL_SECS,max_bulk_mb = MAX_BULK_MB,+ code_cap_mib = crate::extract::code::CODE_CAP / (1 << 20),+ code_cap_bytes = crate::extract::code::CODE_CAP,fresh_help = FRESH_HELP,resume_policy_help = RESUME_POLICY_HELP,defaults = crate::ignore_rules::DEFAULT_IGNORE_PATTERNS.join(" ")@@ -2576,6 +2581,14 @@ mod tests {assert!(help.contains("calibration is #1063"), "{help}");}+ #[test]+ fn code_cap_is_documented_independently_of_the_whole_file_flags() {+ let help = super::help_text_with(false);+ assert!(help.contains("2097152 bytes"), "{help}");+ assert!(help.contains("separate fixed 2 MiB code cap"), "{help}");+ assert!(help.contains("these flags do not raise it"), "{help}");+ }+/// **The merge guard.** Four routes share one positional argument, and each/// arrived on its own branch carrying a refusal that said the others did/// not exist:diff --git a/engine/crates/xerj-autoindex/src/extract/code.rs b/engine/crates/xerj-autoindex/src/extract/code.rsindex 78edaa65f..9789efb3e 100644--- a/engine/crates/xerj-autoindex/src/extract/code.rs+++ b/engine/crates/xerj-autoindex/src/extract/code.rs@@ -28,9 +28,9 @@ use std::sync::OnceLock;use streaming_iterator::StreamingIterator;use tree_sitter::{Language, Node, Parser, Query, QueryCursor};-/// Skip machine-generated giants (minified bundles, generated parsers) — past a-/// couple MB a single "file" is not human code and only bloats the index.-const CODE_CAP: u64 = 2 << 20;+/// Whole-file AST extraction budget. Hand-written source can exceed it too;+/// size is not evidence that a file is generated.+pub(crate) const CODE_CAP: u64 = 2 << 20;/// The reason a source file over [`CODE_CAP`] is skipped (#2483). It names/// the cap and the file's size, says the run is otherwise unaffected, and@@ -38,13 +38,16 @@ const CODE_CAP: u64 = 2 << 20;fn code_cap_refusal(path: &Path) -> String {let mib = |b: u64| b as f64 / (1u64 << 20) as f64;let size = std::fs::metadata(path)- .map(|m| format!("{:.1} MiB", mib(m.len())))- .unwrap_or_else(|_| "size unknown".into());+ .map(|m| format!("{} bytes", m.len()))+ .unwrap_or_else(|_| "unavailable".into());format!(- "source file over the {:.0} MiB code cap ({size}): too large to be hand-written \- code (generated stubs, minified bundles), so it is not parsed. The rest of the \- run is unaffected. To leave it out of the plan, add its path to .xerjignore",- mib(CODE_CAP)+ "source file over the {:.0} MiB code cap ({} bytes; reported file size: {size}). \+ It was not parsed and produced no records. This is a separate fixed \+ code-extraction limit: changing --max-file-gb, --max-file-mb or --max-file-bytes \+ does not raise it. Other files can continue to index. To leave this file \+ out of the plan, add its path to .xerjignore",+ mib(CODE_CAP),+ CODE_CAP)}@@ -2581,6 +2584,58 @@ mod tests {assert!(!script.contains("color") && !script.contains("<div>"));}+ #[test]+ fn perl_code_cap_boundary_reports_exact_bytes_without_guessing_authorship() {+ let dir = tempfile::tempdir().unwrap();+ for size in [CODE_CAP - 1, CODE_CAP, CODE_CAP + 1] {+ let path = dir.path().join("handwritten.pl");+ let head = "sub boundary_probe { return 1; }\n#";+ let tail = "\nsub tail_probe { return 2; }\n";+ let source = format!(+ "{head}{}{tail}",+ "x".repeat(size as usize - head.len() - tail.len())+ );+ assert_eq!(source.len() as u64, size);+ std::fs::write(&path, &source).unwrap();+ // Exercise logical naming too: durable preparation parses a blob,+ // but language/source identity still come from the archived name.+ let blob = dir.path().join("00000000");+ std::fs::write(&blob, &source).unwrap();+ for content in [&path, &blob] {+ let sniffed = crate::sniff::sniff_with_name(content, &path).unwrap();+ let mut records = Vec::new();+ let stats = extract(content, &sniffed, &mut |record| {+ records.push(record);+ true+ })+ .unwrap();+ if size <= CODE_CAP {+ assert!(stats.refusal.is_none());+ assert!(records.iter().any(|record| record+ .fields+ .get("name")+ .and_then(Value::as_str)+ == Some("boundary_probe")));+ assert!(records.iter().any(|record| record+ .fields+ .get("name")+ .and_then(Value::as_str)+ == Some("tail_probe")));+ } else {+ assert!(records.is_empty());+ assert_eq!(stats.records, 0);+ let reason = stats.refusal.unwrap();+ assert!(reason.contains(&format!("{size} bytes")), "{reason}");+ assert!(reason.contains(&format!("{CODE_CAP} bytes")), "{reason}");+ assert!(reason.contains("--max-file-mb"), "{reason}");+ assert!(reason.contains("does not raise"), "{reason}");+ assert!(!reason.contains("too large to be hand-written"), "{reason}");+ assert!(!reason.contains("generated stubs"), "{reason}");+ }+ }+ }+ }+/// #2205: `--lang js` must filter on the stored `javascript`, not on a/// value no record carries.#[test]diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 2e1cd301a..b170c84c1 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -4385,6 +4385,23 @@ fn scan_file(mod clustering_key_tests {use super::*;+ #[test]+ fn perl_code_cap_scan_preserves_the_size_skip_with_a_larger_whole_file_allowance() {+ let dir = tempfile::tempdir().unwrap();+ let prefix = "sub important_function { return 1; }\n#";+ let size = (2 << 20) + 1;+ let body = format!("{prefix}{}\n", "x".repeat(size - prefix.len() - 1));+ let scanned = scan(dir.path(), "handwritten.pl", &body);+ assert_eq!(scanned.sniffed.unwrap().family, Family::Code);+ assert!(scanned.sketches.is_empty());+ let (status, reason) = scanned.junk.unwrap();+ assert_eq!(status, "skipped");+ assert!(reason.contains("2097153 bytes"), "{reason}");+ assert!(reason.contains("2097152 bytes"), "{reason}");+ assert!(reason.contains("--max-file-mb"), "{reason}");+ assert!(!reason.contains("no records extracted"), "{reason}");+ }+fn scan(dir: &Path, name: &str, body: &str) -> FileScan {let path = dir.join(name);std::fs::write(&path, body).unwrap();diff --git a/tools/code-size-limit/README.md b/tools/code-size-limit/README.mdnew file mode 100644index 000000000..a0f0629b8--- /dev/null+++ b/tools/code-size-limit/README.md@@ -0,0 +1,58 @@+# Source-code size skips++Source files handled by the tree-sitter extractor, including Vue/Svelte components, have+a fixed **2 MiB (2,097,152 byte)** input cap. A file exactly at the cap can be+parsed; one byte over is skipped. This is independent of the whole-file flags+`--max-file-gb`, `--max-file-mb` and `--max-file-bytes`. Setting+`--max-file-mb 6` does not make a source file above 2 MiB eligible for AST+extraction. File size alone does not establish whether source is generated.++The skip reason names both the exact limit and the reported file size, says+that no records were extracted and explains the independent limit. For example,+the synthetic boundary case reports **2,097,153 bytes** against **2,097,152**;+rounding both to `2.0 MiB` no longer hides the difference. The catalog retains+`status: skipped`, `records: 0` and the source byte count. Other files can+continue. Exit 3 is completed-with-junk, not a runtime error, but that success+does not make the skipped file searchable.++This is the diagnostic follow-up to merged+[#2666](https://github.com/xerj-org/xerj/pull/2666), which introduced explicit+size refusal reasons. It addresses the misleading reason/help aspects of+[#2745](https://github.com/xerj-org/xerj/issues/2745). It does **not** raise or+make the cap configurable, chunk large code files, or change parser behavior.+Those remain separate work under the issue. SQL source, notebook cells and+PDFs have their own extraction paths; they are not changed.+The indexed-document size limit and semantic mapping behavior are also unchanged.++To exclude an unwanted large file from future plans, add its path to the+project's `.xerjignore`; this excludes content, not indexes it. An existing+committed plan/catalog may retain the diagnostic recorded by its older build.+No migration of stored reasons is added. Use a new prefix/state+directory if you need an isolated fresh-plan check; keep old data until the+replacement has been verified, and use normal ownership-aware removal afterward.++## Reproduce with synthetic Perl++From the repository root, using a built binary and Python 3:++```sh+python3 tools/code-size-limit/smoke.py --binary engine/target/release/xerj --estimate-only+python3 tools/code-size-limit/smoke.py --binary engine/target/release/xerj+```++The script creates three ASCII Perl fixtures at cap minus one, cap and cap+plus one byte, totaling 6 MiB, outside any existing dataset. It snapshots the+executable, uses a private temporary node/data/state directory and never calls+an existing node. Each invocation dry-runs first. The full invocation checks+the catalog, `def` retrieval, completed-with-junk exit, unchanged rerun and+graceful restart. Its node is lexical with `--no-semantic` indexing. It sends+no transcript or real repository content and loads no model. It stops its own+node and removes its own temporary files when done.++Reference retrieved before writing this follow-up: implementation and rationale+at `af721040` (#2666), `engine/crates/xerj-autoindex/src/extract/code.rs:33–48`+and `384–389`; the bounded reader at baseline `e5675dec`,+`engine/crates/xerj-autoindex/src/extract/mod.rs:163–171`; and refusal-to-catalog+classification in `engine/crates/xerj-autoindex/src/lib.rs:4293–4312`.+No external implementation was copied, no cap algorithm was replaced and no+performance improvement is claimed. See [verification receipts](VERIFICATION.md).diff --git a/tools/code-size-limit/VERIFICATION.md b/tools/code-size-limit/VERIFICATION.mdnew file mode 100644index 000000000..7ac2c275e--- /dev/null+++ b/tools/code-size-limit/VERIFICATION.md@@ -0,0 +1,111 @@+# Code-cap diagnostic verification (2026-10-31)++Written and executed by OpenAI Codex, operated by Jarvis636431, on macOS arm64+with Rust 1.97.1. This is a source-built candidate reporting+`xerj v1.0.0-rc.100`, not a claim about a published release.++## Regression control++The three new tests were installed on `e5675dec` before the diagnostic/help+fix. Running `cargo +1.97.1 test --locked -p xerj-autoindex code_cap` failed+all three (0 passed, 3 failed). The extractor and scan failures printed:++```text+source file over the 2 MiB code cap (2.0 MiB): too large to be hand-written code (generated stubs, minified bundles), so it is not parsed.+```++The fixture was 2,097,153 bytes: rounding hid its one-byte excess. The help+test failed because the independent code cap was absent. After the fix the+same command passed all three. Tests cover cap minus one, cap, and cap plus+one on both source paths and extensionless snapshot blobs; scan classification+uses a larger whole-file allowance. No parser or cap admission logic changed.++## Final composed tree++The implementation commit is `469eb1b6`, based directly on upstream+`f855d39d`. Rebase retained the Vue/Svelte extraction and tests from #2735;+the only conflict was adjacent test insertion. This branch contains no+unmerged prerequisite commits. #2666 is already in the base.++Commands from `engine/`:++```sh+cargo +1.97.1 fmt --all+cargo +1.97.1 fmt --all -- --check+cargo +1.97.1 build --locked --offline --release -j 32 -p xerj-autoindex -p xerj-server -p es-yaml-runner+TMPDIR=/private/tmp cargo +1.97.1 test --locked --offline -p xerj-autoindex -- --test-threads=1 --skip content::tests::lossy_display_collisions_keep_distinct_alias_identities --skip corpus_data_skip_tests::corpus_index_summary_splits_indexed_extensions_from_ignored_data --skip inventory_delta_tests::a_non_utf8_excluded_name_is_matched_on_disk_via_path_id+cargo +1.97.1 clippy --locked --offline --no-deps -p xerj-autoindex --all-targets -- -D warnings -A dead_code+```++The three explicit filesystem filters are the existing macOS exclusions+documented in [session-import verification](../session-import/VERIFICATION.md).+They were not modified. Strict Clippy without the allowance encounters the+pre-existing `content.rs::resolve_reporting` dead-code warning; no source+allowance was added. No lockfile or dependency changes are part of this PR.++Observed on the composed tree: scoped release build and fmt check passed;+crate suite **1,976 passed, 0 failed, 5 existing ignored, 3 filtered**; scoped+Clippy passed with the allowance above. The crate command needs local test+ports: its first sandboxed attempt failed at port binding with+`PermissionDenied / Operation not permitted`; rerunning with local networking+allowed produced these results. Python compilation and the workflow timeout+guard also passed (41 jobs across 13 workflows).++## Live reproduction and scope++Run the two commands in [README.md](README.md) with the scoped release binary.+The script creates three synthetic ASCII Perl files totaling 6,291,456 bytes,+dry-runs first and uses its own temporary node, data, state and executable+snapshot. It exercises real HTTP catalog reads and CLI `def`, not mocks.+Below/at-cap files expose both leading and trailing functions. The oversized+file remains skipped with zero records and exact limit/file byte counts,+even with `--max-file-mb 6`. Repeated indexing and graceful restart must keep+the same record count and catalog outcome. Both node processes must exit 0.++Observed on the final binary: first run **1.0 s**, unchanged rerun **0.3 s**;+both `ok: true`, exit **3**, reason `completed-with-junk`, 2 indexed code files,+1 skipped code file and **6 live records**. All **4** expected definitions were+retrieved; `over_probe` had no hits. Restart preserved those results; both+nodes exited **0**. The independent `--estimate-only` invocation also passed.+Executable SHA-256 (the copied executable actually run):+`e204f8ac5f7a5c003f55a5fb4d87f68f1aa81440e8379123bf6554a56931254b`.+These are single-run correctness receipts, not performance measurements.++The scoped `es-yaml-runner` was run against a separate empty temporary node+using `--url <private-node-url> --dir engine/tests/es-compat-yaml/yaml` from+the repository root. Final composed-tree output:++```text+ES-COMPAT YAML RUNNER · 233 files+1453 passed · 0 failed · 10 skipped · 1463 total+74 cases ran catch-lenient (an expected error XERJ does not raise yet; see catch-lenient.txt)+private conformance node exit 0+```++Skip and catch-lenient policies are unchanged. This is the repository's current+suite, not a claim of complete coverage of the Elasticsearch protocol.++## Contribution-review audit++- Effective diff: diagnostic/help, three regression tests, changelog and this+ bounded reproduction. No upstream feature, workflow, skip policy, API schema,+ journal format, identity or durable transition is removed or replaced.+- The diagnostic names cause, no extracted records, independent flags and+ `.xerjignore` exclusion. Exclusion is not an indexing workaround. Larger-file+ support and configurable/chunked extraction remain outside this PR.+- First run, unchanged rerun, explicit oversized-file negative control, partial+ corpus retrieval, graceful stop and durable restart are exercised. The+ executable hash is taken from the same private copy that is run.+- Not exercised: changed-input reruns, interruption/pending-state recovery,+ old-plan upgrades, concurrent mutation, metadata-read failure, Windows/Linux,+ neural mode, all language grammars, real reporter data. Existing stored+ reasons are not migrated. There is no new recovery/state algorithm to audit.+- Optional acceleration/fallback, schema migration, destructive preflight,+ feature-gated implementation, mutable-asset identity, performance/resource+ optimization and ambiguous schema selection are not applicable: only strings+ and shared visibility of the existing cap constant change in production.+- No install/publish recipe or privileged artifact handoff is introduced.+ The smoke script owns a fresh temporary tree, starts no existing node and+ deletes only that tree. No hub corpus, model or real user content is used.+- No performance claim is made. No peer algorithm was implemented/copied;+ retrieved in-repository reference locations are listed in README.md.diff --git a/tools/code-size-limit/smoke.py b/tools/code-size-limit/smoke.pynew file mode 100644index 000000000..63fb75a67--- /dev/null+++ b/tools/code-size-limit/smoke.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+"""Synthetic Perl code-cap boundaries on a private node; no existing data is contacted."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import shutil+import socket+import subprocess+import tempfile+import time+from urllib.request import build_opener, ProxyHandler, Request++CAP = 2 << 20+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--binary', type=Path, required=True)+ parser.add_argument('--estimate-only', action='store_true')+ args = parser.parse_args()+ original = args.binary.resolve(strict=True)+ env = {k: v for k, v in os.environ.items() if not k.startswith('XERJ_')+ and k.lower() not in ('http_proxy', 'https_proxy', 'all_proxy', 'no_proxy')}+ env.update(XERJ_DISABLE_FEEDBACK='true', XERJ_NUM_CPUS='4')+ opener = build_opener(ProxyHandler({}))+ with tempfile.TemporaryDirectory(prefix='xerj-code-cap-') as temp:+ root = Path(temp)+ binary = root / ('xerj.exe' if os.name == 'nt' else 'xerj')+ shutil.copyfile(original, binary)+ binary.chmod(0o700)+ print('Executable SHA-256:', hashlib.sha256(binary.read_bytes()).hexdigest(), flush=True)+ source = root / 'source'+ source.mkdir()+ for name, size in [('below', CAP - 1), ('at', CAP), ('over', CAP + 1)]:+ head = f'sub {name}_probe {{ return 1; }}\n#'+ tail = f'\nsub {name}_tail {{ return 2; }}\n'+ body = head + 'x' * (size - len(head) - len(tail)) + tail+ assert len(body.encode()) == size+ (source / f'{name}.pl').write_bytes(body.encode())+ sockets = [socket.socket(), socket.socket()]+ for sock in sockets:+ sock.bind(('127.0.0.1', 0))+ port, rest = [sock.getsockname()[1] for sock in sockets]+ for sock in sockets:+ sock.close()+ url = f'http://127.0.0.1:{port}'+ config = root / 'node.toml'+ config.write_text(f'[server]\nes_compat_port={port}\nrest_port={rest}\ngrpc_port=0\n'+ f'data_dir={json.dumps(str(root / "data"))}\n'+ '[limits]\ndisk_flood_stage_percent=99\n')++ def run(command, expected=0):+ result = subprocess.run([str(binary), *command], cwd=root, env=env,+ capture_output=True, text=True, timeout=180)+ if result.returncode != expected:+ raise AssertionError(f'{command[0]} exit {result.returncode}: {result.stdout}\n{result.stderr}')+ return result++ def request(path, body=None):+ req = Request(url + path, None if body is None else json.dumps(body).encode(),+ headers={'Content-Type': 'application/json'})+ with opener.open(req, timeout=15) as response:+ return json.load(response)++ def verify():+ query = {'size': 10, 'query': {'bool': {'filter': [+ {'term': {'prefix': 'code-cap-test'}}, {'term': {'doc_kind': 'file'}}]}}}+ files = [hit['_source'] for hit in request('/autoindex-catalog/_search', query)['hits']['hits']]+ assert len(files) == 3, files+ skipped = next(item for item in files if item['path'].endswith('over.pl'))+ assert skipped['status'] == 'skipped' and skipped['records'] == 0, skipped+ assert skipped['bytes'] == CAP + 1, skipped+ reason = skipped['reason']+ assert f'{CAP + 1} bytes' in reason and f'{CAP} bytes' in reason, reason+ assert '--max-file-mb' in reason and 'does not raise' in reason, reason+ assert 'too large to be hand-written' not in reason, reason+ for name in ('below', 'at'):+ for suffix in ('probe', 'tail'):+ result = json.loads(run(['def', f'{name}_{suffix}', '--prefix', 'code-cap-test',+ '--url', url, '--lang', 'perl', '--json']).stdout)+ hits = result['hits']['hits']+ assert hits and hits[0]['_source']['name'] == f'{name}_{suffix}', result+ absent = json.loads(run(['def', 'over_probe', '--prefix', 'code-cap-test',+ '--url', url, '--lang', 'perl', '--json']).stdout)+ assert not absent['hits']['hits'], absent+ count = request('/code-cap-test-*/_count')['count']+ assert count > 0+ print(f'PASS catalog: over.pl skipped, 0 records, exact bytes; 4 accepted definitions; {count} live records', flush=True)+ return count++ command = ['autoindex', str(source), '--url', url, '--prefix', 'code-cap-test',+ '--state-dir', str(root / 'state'), '--no-graph', '--no-semantic',+ '--max-file-mb', '6', '--workers', '2', '--max-minutes', '0']+ initial_count = None+ for phase in ('first', 'restart'):+ with (root / f'{phase}.log').open('w') as log:+ node = subprocess.Popen([str(binary), '--insecure', '-c', str(config)],+ cwd=root, env=env, stdout=log, stderr=log)+ try:+ deadline = time.monotonic() + 60+ while True:+ assert node.poll() is None, 'private node exited before readiness'+ try:+ request('/')+ break+ except OSError:+ if time.monotonic() >= deadline:+ raise TimeoutError('private-node readiness timeout')+ time.sleep(.1)+ if phase == 'first':+ dry = run(command + ['--dry-run'])+ for line in (dry.stdout + dry.stderr).splitlines():+ if 'autoindex:' in line and 'files (' in line:+ print(line, flush=True)+ if args.estimate_only:+ return+ for generation in range(2):+ result = run(command + ['--progress', 'json'], expected=3)+ done = []+ for line in (result.stdout + result.stderr).splitlines():+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ if isinstance(event, dict) and event.get('bar'):+ print(event['bar'], flush=True)+ if isinstance(event, dict) and event.get('event') == 'done':+ done.append(event)+ print(line, flush=True)+ assert len(done) == 1 and done[0]['ok'] is True and done[0]['exit'] == 3, done+ assert done[0]['code_files'] == 3 and done[0]['code_files_indexed'] == 2 and done[0]['code_files_junked'] == 1, done+ count = verify()+ if initial_count is None:+ initial_count = count+ assert count == initial_count+ print(f'PASS index/rerun {generation + 1}: exit 3 is completed-with-junk, skipped source stays explicit', flush=True)+ else:+ assert verify() == initial_count+ print('PASS durable restart: unchanged catalog and record count', flush=True)+ finally:+ if node.poll() is None:+ node.terminate()+ try:+ node.wait(timeout=30)+ except subprocess.TimeoutExpired:+ node.kill()+ node.wait()+ raise+ assert node.returncode == 0, node.returncode+ print('private node exit 0', flush=True)+++if __name__ == '__main__':+ main()