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
feat(server): add private pprof debugging toolkit
buger18fd8961ad2d
diff --git a/demo/playbooks/README.md b/demo/playbooks/README.mdindex 3b6d6a9bd..2a8eb17f2 100644--- a/demo/playbooks/README.md+++ b/demo/playbooks/README.md@@ -31,6 +31,7 @@ deterministic.| `ES_API_AUDIT.md` | **full ES-compat surface audit** — all 162 routes live-tested + source-classified (REAL/PARTIAL/STUB), 0 broken, with the hot-path benchmark || `es_api_audit.json` | machine-readable per-endpoint verdicts + evidence || `BENCHMARK.md` | bulk-ingest throughput + read/agg/kNN latency (`bench.mjs`) |+| `debug-profiling/` | opt-in CPU/heap pprof capture, reproducibility manifest, and AI analysis prompts |## Use cases covereddiff --git a/demo/playbooks/debug-profiling/.gitignore b/demo/playbooks/debug-profiling/.gitignorenew file mode 100644index 000000000..c18dd8d83--- /dev/null+++ b/demo/playbooks/debug-profiling/.gitignore@@ -0,0 +1 @@+__pycache__/diff --git a/demo/playbooks/debug-profiling/PROMPT_COMPARE.md b/demo/playbooks/debug-profiling/PROMPT_COMPARE.mdnew file mode 100644index 000000000..d04f36579--- /dev/null+++ b/demo/playbooks/debug-profiling/PROMPT_COMPARE.md@@ -0,0 +1,23 @@+# Before/after profile comparison prompt++Compare two XERJ profiling directories as a correctness-first A/B experiment.++Before analysis:++1. Read both manifests and reject the comparison if corpus, workload, concurrency, cache state, host, capture interval, CPU Hz, build profile, or relevant feature set differs. Do not normalize across Cargo profiles.+ Treat source/profile/features as operator declarations while `source_build_binding` is `UNVERIFIED`; do not claim the binary came from that source revision without independent build attestation.+2. Verify artifact hashes and benchmark correctness. Faster-but-wrong is a regression.+3. Produce `pprof -base BEFORE AFTER` views for CPU and heap, plus absolute top/tree views for both sides.++Report:++- elapsed time, docs/s, requests/s, peak RSS, jemalloc allocated/active/resident, disk bytes, correctness/recall, and profile sample totals;+- absolute and relative deltas with units and denominators;+- stacks removed, stacks added, and stacks shifted elsewhere;+- whether retained bytes fell or merely moved from application allocations into allocator slack, mmap/file cache, or another process;+- whether CPU fell in absolute samples or only as a percentage;+- confidence level and every uncontrolled variable.++Conclude `WIN`, `LOSS`, or `INCONCLUSIVE`. A win requires unchanged correctness/durability, a reproducible resource or throughput improvement, and no unexplained regression in another north-star budget.++A hotspot or win found with the fast `profiling` profile is provisional. Require a same-profile `profiling-final` A/B confirmation before making a production-codegen performance claim.diff --git a/demo/playbooks/debug-profiling/PROMPT_CPU.md b/demo/playbooks/debug-profiling/PROMPT_CPU.mdnew file mode 100644index 000000000..9fb532284--- /dev/null+++ b/demo/playbooks/debug-profiling/PROMPT_CPU.md@@ -0,0 +1,24 @@+# CPU profile analysis prompt++You are reviewing a XERJ CPU pprof artifact from a controlled experiment.++Inputs:++- Read `manifest.json` completely.+- Inspect `cpu.pb` with `pprof -top`, `-tree`, and focused `-list` views.+- Read the exact source at the Git revision in the manifest.+- Read the benchmark's correctness and throughput output.++Report:++1. Confirm artifact hashes, capture duration/frequency, binary hash, declared revision/build, command, host, and whether the process was terminated normally. Treat source/build binding as `UNVERIFIED` unless independently attested.+2. List the top 15 flat and cumulative stacks with both samples and percentages.+3. Group costs into PDF extraction, tokenization/embedding, HTTP/JSON, indexing, flush/merge, allocator/synchronization, storage I/O, and unknown.+4. Trace each major stack to source file and function. Clearly label inference.+5. Identify parallelism bottlenecks, lock/futex waits, repeated parsing/copying, and single-threaded phases.+6. Recommend the three smallest experiments that can falsify the suspected bottlenecks.+7. Do not claim elapsed-time or throughput causality from sample percentages alone.++End with `CONFIRMED`, `LIKELY`, and `UNKNOWN` sections.++If correctness, workload results, or comparable telemetry are not attached, label any performance conclusion `INCONCLUSIVE`; a CPU profile alone identifies sampled hot stacks, not a validated optimization win.diff --git a/demo/playbooks/debug-profiling/PROMPT_HEAP.md b/demo/playbooks/debug-profiling/PROMPT_HEAP.mdnew file mode 100644index 000000000..abfc1d9ff--- /dev/null+++ b/demo/playbooks/debug-profiling/PROMPT_HEAP.md@@ -0,0 +1,23 @@+# Heap profile analysis prompt++You are reviewing a XERJ jemalloc in-use heap pprof artifact.++Inputs:++- Read `manifest.json` completely and verify `heap.pb.gz`.+- Inspect `heap.pb.gz` with `pprof -top`, `-tree`, and focused `-list` views.+- Read the exact source at the manifest Git revision.+- Correlate the capture endpoint in time with RSS, jemalloc allocated/active/resident, and XERJ logical ownership telemetry when available.++Report:++1. Confirm the binary hash and treat the declared source/build binding as `UNVERIFIED` unless independently attested. Then list the top 20 retained-byte allocation stacks with bytes and percentages.+2. Map them to raw HTTP bodies, parsed JSON, prepared documents, vectors/model scratch, memtables, flush snapshots, merge survivors/buffers, caches, mappings, and unknown.+3. Separate live allocations from allocator fragmentation/dirty pages: `RSS - jemalloc resident`, `resident - active`, and `active - allocated` are not attributable to live heap stacks.+4. Look for duplicated representations of the same corpus and unbudgeted queues.+5. State sampling limitations: this is probabilistic, in-use heap at capture time, not every allocation and not peak RSS by itself.+6. Propose deterministic small-corpus tests that reproduce each dominant owner before another full-corpus run.++End with a byte-accounting table whose rows sum to sampled in-use bytes, plus an explicit unexplained remainder.++If correctness, RSS/jemalloc time series, or workload results are unavailable, label any resource-win conclusion `INCONCLUSIVE`; an in-use heap profile alone does not explain total RSS or peak memory.diff --git a/demo/playbooks/debug-profiling/README.md b/demo/playbooks/debug-profiling/README.mdnew file mode 100644index 000000000..a3dbd45bf--- /dev/null+++ b/demo/playbooks/debug-profiling/README.md@@ -0,0 +1,104 @@+# XERJ debug profiling++This toolkit answers two different questions:++- `cpu.pb`: where the process spent sampled CPU time.+- `heap.pb.gz`: which allocation call stacks retained sampled live bytes at the end of the capture.++It is Linux-only, local, bounded, and off by default. It adds no debug HTTP endpoint. A normal XERJ build does not compile either profiler.++## Build++Build the fast, symbolized iteration binary:++```bash+(cd engine && cargo build --profile profiling -j 32 -p xerj-server \+ --no-default-features --features debug-profiling,onnx-experimental)+```++`profiling` uses thin LTO and 16 codegen units to shorten the edit/profile loop. It is not production-codegen-equivalent. Do not compare it against a `release` or `profiling-final` run.++Before making a final performance claim, repeat the winning experiment with release-equivalent fat LTO and one codegen unit:++```bash+(cd engine && cargo build --profile profiling-final -j 32 -p xerj-server \+ --no-default-features --features debug-profiling,onnx-experimental)+```++Do not use the ordinary stripped `release` profile for profiles: heap addresses will be much harder or impossible to resolve.++## Capture++Start a new artifact directory and a bounded 30-second capture:++```bash+python3 demo/playbooks/debug-profiling/capture.py \+ --output /tmp/xerj-profile-before \+ --cpu-seconds 30 \+ --heap-seconds 30 \+ --delay-seconds 5 \+ --workload financebench-fb20-v1 \+ --corpus financebench-20-sha256-example \+ --concurrency 4 \+ --cache-state cold \+ --build-features debug-profiling,onnx-experimental \+ --build-profile profiling \+ --attach correctness=/tmp/fb20-correctness.json \+ --attach telemetry=/tmp/fb20-memory.ndjson \+ -- \+ engine/target/profiling/xerj --data-dir /tmp/xerj-profile-data+```++Run the workload from a second terminal. `--delay-seconds` is process-start-relative and gives the server and workload driver a bounded synchronization window; it does not probe readiness. With delay zero, profiling starts before config loading and engine replay and therefore includes initialization. The wrapper stops the whole server process group five seconds after the delay plus longest capture. An explicit `--stop-after` must preserve the same five-second dump/publication window; exact capture-boundary termination is rejected because conversion and atomic publication happen after sampling stops.++The manifest records the exact binary hash, command, repository revision/dirty state, host shape, capture settings, exit status, and artifact hashes. The binary-to-source binding is explicitly `UNVERIFIED`: the wrapper cannot prove that the binary was built from the recorded checkout. Build profile/features and workload/corpus/concurrency/cache values are likewise **declared by the operator**, not extracted from the binary. Use repeatable `--attach LABEL=PATH` options to copy and hash correctness, throughput, RSS, jemalloc, and XERJ telemetry evidence. Without those, the supplied analysis prompts require an `INCONCLUSIVE` performance verdict.++Server output is private `server.log`; when `pprof` is installed, agent-readable `*.top.txt` reports are generated too. Validate the entire bundle:++```bash+python3 demo/playbooks/debug-profiling/inspect.py /tmp/xerj-profile-before+```++The output directory must not already exist. Profile files are mode `0600`, published atomically, and never overwritten. A per-directory lock rejects concurrent capture controllers.++If XERJ reports a stale `.xerj-debug-profile.lock`, first confirm no XERJ process is using that directory. Remove only that exact lock file after confirming the previous process was killed; the controller removes it on normal and handled shutdown. Invalid requested profiling configuration fails server startup instead of silently running without artifacts.++Direct invocation is also possible:++```bash+mkdir -m 700 /tmp/xerj-profile+XERJ_DEBUG_PROFILE_DIR=/tmp/xerj-profile \+XERJ_DEBUG_CPU_SECONDS=30 \+XERJ_DEBUG_HEAP_SECONDS=30 \+XERJ_DEBUG_CPU_HZ=100 \+XERJ_DEBUG_PROFILE_DELAY_SECONDS=5 \+engine/target/profiling/xerj+```++Durations must be 1–300 seconds, delay 0–300 seconds, and CPU frequency 1–1000 Hz. The default is 100 Hz with no delay. Shutdown interrupts delay and capture waits instead of blocking for the remaining duration.++## Inspect++Install Google's `pprof`, then:++```bash+pprof -http=localhost:0 /tmp/xerj-profile/cpu.pb+pprof -http=localhost:0 /tmp/xerj-profile/heap.pb.gz+pprof -top /tmp/xerj-profile/heap.pb.gz+```++Profiles contain function names, file paths, and workload-dependent execution structure. Treat them as private diagnostic artifacts.++The manifest also contains the full server command. Do not put passwords, API keys, or tokens directly in command-line arguments. Although the output directory is mode `0700` and artifacts are `0600`, copy the bundle only through an approved private channel.++CPU sampling uses `SIGPROF` and libgcc unwinding. Upstream `pprof-rs` explicitly documents signal-safety limitations, so this tooling is for controlled debugging builds, not an always-on production profiler. Jemalloc allocation sampling is compiled only into this feature and starts inactive; cumulative allocation profiling remains disabled to avoid retaining every unique backtrace.++Prefer separate CPU-only and heap-only repetitions. A combined capture is convenient for smoke testing but the profilers can perturb one another, so its throughput and overhead results are confounded.++## Fair A/B protocol++Use a fresh data directory and artifact directory for each side. Keep the corpus, query/workload driver, concurrency, capture duration, CPU frequency, build profile, feature set, machine, and cache state identical. Verify correctness before comparing speed. Compare both absolute samples/bytes and percentage shares: percentage-only views can make an unchanged function look better when unrelated work grows.++The validator records only the operator-declared build profile. Reject cross-profile A/B comparisons. Hotspots discovered with fast `profiling` must be reconfirmed using `profiling-final` before a final production-performance claim.++Use the prompt templates in this directory to make an AI agent produce evidence-linked conclusions rather than guesses.diff --git a/demo/playbooks/debug-profiling/capture.py b/demo/playbooks/debug-profiling/capture.pynew file mode 100644index 000000000..9bf51b52e--- /dev/null+++ b/demo/playbooks/debug-profiling/capture.py@@ -0,0 +1,320 @@+#!/usr/bin/env python3+"""Launch one bounded XERJ profiling run and write a reproducibility manifest."""++import argparse+import datetime+import hashlib+import json+import os+import pathlib+import platform+import re+import shutil+import signal+import subprocess+import sys++PUBLICATION_GRACE_SECONDS = 5+++def sha256(path):+ digest = hashlib.sha256()+ with open(path, "rb") as source:+ for block in iter(lambda: source.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def write_manifest(path, manifest):+ temporary = path.with_suffix(".json.tmp")+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "w") as target:+ target.write(json.dumps(manifest, indent=2, sort_keys=True) + "\n")+ temporary.replace(path)+++def read_optional(path):+ try:+ return pathlib.Path(path).read_text().strip()+ except OSError:+ return None+++def cgroup_v2_snapshot():+ membership = read_optional("/proc/self/cgroup")+ relative = "/"+ if membership:+ for line in membership.splitlines():+ if line.startswith("0::"):+ relative = line[3:]+ break+ root = pathlib.Path("/sys/fs/cgroup") / relative.lstrip("/")+ return {+ "path": relative,+ "memory_max": read_optional(root / "memory.max"),+ "memory_current": read_optional(root / "memory.current"),+ "cpu_max": read_optional(root / "cpu.max"),+ }+++def main():+ parser = argparse.ArgumentParser(+ description="Run a symbolized, bounded XERJ CPU/heap capture.",+ epilog=(+ "Validate with debug-profiling/inspect.py. Analysis prompts: "+ "PROMPT_CPU.md, PROMPT_HEAP.md, PROMPT_COMPARE.md."+ ),+ )+ parser.add_argument("--output", required=True, type=pathlib.Path)+ parser.add_argument("--cpu-seconds", type=int, default=0)+ parser.add_argument("--heap-seconds", type=int, default=0)+ parser.add_argument("--cpu-hz", type=int, default=100)+ parser.add_argument("--delay-seconds", type=int, default=0)+ parser.add_argument("--workload", required=True, help="stable workload/driver identifier")+ parser.add_argument("--corpus", required=True, help="stable corpus identifier or hash")+ parser.add_argument("--concurrency", required=True, help="worker/request concurrency")+ parser.add_argument(+ "--cache-state", required=True, choices=("cold", "warm", "mixed", "unknown")+ )+ parser.add_argument(+ "--build-features",+ required=True,+ help="declared comma-separated Cargo feature set used to build the binary",+ )+ parser.add_argument("--build-profile", required=True, help="declared Cargo profile")+ parser.add_argument(+ "--attach",+ action="append",+ default=[],+ metavar="LABEL=PATH",+ help="copy and hash correctness, throughput, RSS, or telemetry evidence",+ )+ parser.add_argument(+ "--stop-after",+ type=int,+ help="terminate the server after this many seconds (default: capture max + 5)",+ )+ parser.add_argument("command", nargs=argparse.REMAINDER)+ args = parser.parse_args()+ command = args.command[1:] if args.command[:1] == ["--"] else args.command+ if not command:+ parser.error("server command is required after --")+ binary = pathlib.Path(command[0]).resolve()+ if not binary.is_file() or not os.access(binary, os.X_OK):+ parser.error(f"server binary does not exist or is not executable: {binary}")+ if not 1 <= max(args.cpu_seconds, args.heap_seconds) <= 300:+ parser.error("at least one capture duration must be in 1..=300")+ if not 1 <= args.cpu_hz <= 1000:+ parser.error("--cpu-hz must be in 1..=1000")+ if not 0 <= args.delay_seconds <= 300:+ parser.error("--delay-seconds must be in 0..=300")+ capture_end = args.delay_seconds + max(args.cpu_seconds, args.heap_seconds)+ if (+ args.stop_after is not None+ and args.stop_after < capture_end + PUBLICATION_GRACE_SECONDS+ ):+ parser.error(+ f"--stop-after must allow {PUBLICATION_GRACE_SECONDS}s after capture "+ "for profile dump and atomic publication"+ )++ args.output.mkdir(mode=0o700, parents=True, exist_ok=False)+ output = args.output.resolve()+ manifest_path = output / "manifest.json"+ started = datetime.datetime.now(datetime.timezone.utc)+ manifest = {+ "schema": "xerj.debug_profile.v1",+ "status": "running",+ "started_utc": started.isoformat(),+ "command": command,+ "binary": str(binary),+ "binary_sha256": sha256(binary),+ "source_build_binding": "UNVERIFIED",+ "capture": {+ "cpu_seconds": args.cpu_seconds or None,+ "heap_seconds": args.heap_seconds or None,+ "cpu_hz": args.cpu_hz,+ "delay_seconds": args.delay_seconds,+ },+ "experiment": {+ "workload": args.workload,+ "corpus": args.corpus,+ "concurrency": args.concurrency,+ "cache_state": args.cache_state,+ },+ "declared_build_unverified": {+ "profile": args.build_profile,+ "features": [item for item in args.build_features.split(",") if item],+ },+ "host": {+ "platform": platform.platform(),+ "kernel": platform.release(),+ "machine": platform.machine(),+ "python": platform.python_version(),+ "cpu_count": os.cpu_count(),+ "page_size": os.sysconf("SC_PAGE_SIZE"),+ "cgroup_v2": cgroup_v2_snapshot(),+ },+ }+ repo = pathlib.Path(__file__).resolve().parents[3]+ try:+ manifest["source"] = {+ "repo": str(repo),+ "git_head": subprocess.check_output(+ ["git", "-C", str(repo), "rev-parse", "HEAD"],+ text=True,+ stderr=subprocess.DEVNULL,+ ).strip(),+ "git_status": subprocess.check_output(+ ["git", "-C", str(repo), "status", "--short"],+ text=True,+ stderr=subprocess.DEVNULL,+ ).splitlines(),+ }+ tracked_diff = subprocess.check_output(+ ["git", "-C", str(repo), "diff", "--binary", "HEAD"],+ stderr=subprocess.DEVNULL,+ )+ manifest["source"]["tracked_diff_sha256"] = hashlib.sha256(tracked_diff).hexdigest()+ except (OSError, subprocess.CalledProcessError):+ manifest["source"] = None+ try:+ manifest["rustc"] = subprocess.check_output(+ ["rustc", "-Vv"], text=True, stderr=subprocess.DEVNULL+ ).strip()+ except (OSError, subprocess.CalledProcessError):+ manifest["rustc"] = None+ manifest["cgroup"] = read_optional("/proc/self/cgroup")+ attachments = {}+ for specification in args.attach:+ if "=" not in specification:+ parser.error("--attach must be LABEL=PATH")+ label, source_text = specification.split("=", 1)+ if not re.fullmatch(r"[a-zA-Z0-9_.-]+", label):+ parser.error(f"unsafe attachment label: {label}")+ source = pathlib.Path(source_text)+ if not source.is_file():+ parser.error(f"attachment is not a file: {source}")+ destination = output / f"attachment-{label}{source.suffix}"+ fd = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "wb") as target, source.open("rb") as attached:+ shutil.copyfileobj(attached, target)+ attachments[label] = {+ "file": destination.name,+ "source": str(source.resolve()),+ "bytes": destination.stat().st_size,+ "sha256": sha256(destination),+ }+ manifest["attachments"] = attachments+ write_manifest(manifest_path, manifest)++ environment = os.environ.copy()+ environment["XERJ_DEBUG_PROFILE_DIR"] = str(output)+ environment["XERJ_DEBUG_CPU_HZ"] = str(args.cpu_hz)+ environment["XERJ_DEBUG_PROFILE_DELAY_SECONDS"] = str(args.delay_seconds)+ if args.cpu_seconds:+ environment["XERJ_DEBUG_CPU_SECONDS"] = str(args.cpu_seconds)+ if args.heap_seconds:+ environment["XERJ_DEBUG_HEAP_SECONDS"] = str(args.heap_seconds)++ log_path = output / "server.log"+ log_fd = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ log_file = os.fdopen(log_fd, "wb")+ process = subprocess.Popen(+ command,+ env=environment,+ stdout=log_file,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ )+ timeout = args.stop_after or capture_end + PUBLICATION_GRACE_SECONDS+ timed_out = False++ def stop_group(first_signal, grace_seconds=10):+ os.killpg(process.pid, first_signal)+ try:+ process.wait(timeout=grace_seconds)+ return+ except subprocess.TimeoutExpired:+ pass+ os.killpg(process.pid, signal.SIGTERM)+ try:+ process.wait(timeout=10)+ return+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait()++ try:+ process.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ timed_out = True+ stop_group(signal.SIGTERM)+ except KeyboardInterrupt:+ stop_group(signal.SIGINT)+ finally:+ log_file.close()++ artifacts = {}+ requested = []+ if args.cpu_seconds:+ requested.append("cpu.pb")+ if args.heap_seconds:+ requested.append("heap.pb.gz")+ for name in requested:+ path = output / name+ if path.exists():+ artifacts[name] = {"bytes": path.stat().st_size, "sha256": sha256(path)}+ if shutil.which("pprof"):+ top_path = output / f"{name}.top.txt"+ top_fd = os.open(top_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(top_fd, "w") as top:+ result = subprocess.run(+ ["pprof", "-top", str(path)],+ stdout=top,+ stderr=subprocess.STDOUT,+ text=True,+ )+ artifacts[top_path.name] = {+ "bytes": top_path.stat().st_size,+ "sha256": sha256(top_path),+ "exit_code": result.returncode,+ }+ for name in ("cpu-error.json", "heap-error.json"):+ path = output / name+ if path.exists():+ artifacts[name] = {"bytes": path.stat().st_size, "sha256": sha256(path)}+ artifacts["server.log"] = {+ "bytes": log_path.stat().st_size,+ "sha256": sha256(log_path),+ }+ missing = [name for name in requested if name not in artifacts]+ expected_termination = timed_out and process.returncode == -signal.SIGTERM+ if missing:+ status = "profile_failed"+ elif process.returncode not in (0, None) and not expected_termination:+ status = "process_failed"+ else:+ status = "complete"+ manifest.update(+ {+ "status": status,+ "ended_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),+ "elapsed_seconds": (datetime.datetime.now(datetime.timezone.utc) - started).total_seconds(),+ "exit_code": process.returncode,+ "terminated_after_capture_window": timed_out,+ "missing_requested_artifacts": missing,+ "artifacts": artifacts,+ }+ )+ write_manifest(manifest_path, manifest)+ if missing:+ print(f"missing requested profile artifacts: {', '.join(missing)}", file=sys.stderr)+ return 2+ if status == "process_failed":+ return 3+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/demo/playbooks/debug-profiling/inspect.py b/demo/playbooks/debug-profiling/inspect.pynew file mode 100644index 000000000..6b04787ff--- /dev/null+++ b/demo/playbooks/debug-profiling/inspect.py@@ -0,0 +1,88 @@+#!/usr/bin/env python3+"""Validate a XERJ profiling bundle and print an agent-readable summary."""++import argparse+import gzip+import hashlib+import json+import pathlib+import sys+++def sha256(path):+ digest = hashlib.sha256()+ with path.open("rb") as source:+ for block in iter(lambda: source.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def main():+ parser = argparse.ArgumentParser(+ description="Verify profile hashes/formats and summarize evidence gaps."+ )+ parser.add_argument("bundle", type=pathlib.Path)+ args = parser.parse_args()+ bundle = args.bundle.resolve()+ manifest = json.loads((bundle / "manifest.json").read_text())+ errors = []+ for name, metadata in manifest.get("artifacts", {}).items():+ path = bundle / name+ if not path.is_file():+ errors.append(f"missing artifact: {name}")+ elif sha256(path) != metadata["sha256"]:+ errors.append(f"hash mismatch: {name}")+ for label, metadata in manifest.get("attachments", {}).items():+ path = bundle / metadata["file"]+ if not path.is_file() or sha256(path) != metadata["sha256"]:+ errors.append(f"invalid attachment: {label}")+ heap = bundle / "heap.pb.gz"+ if heap.exists():+ try:+ with gzip.open(heap, "rb") as source:+ if not source.read(1):+ errors.append("empty heap protobuf")+ except OSError:+ errors.append("heap.pb.gz is not valid gzip")+ cpu = bundle / "cpu.pb"+ if cpu.exists() and cpu.stat().st_size == 0:+ errors.append("cpu.pb is empty")++ evidence = manifest.get("attachments", {})+ summary = {+ "schema": "xerj.debug_profile.inspect.v1",+ "valid": not errors and manifest.get("status") == "complete",+ "capture_status": manifest.get("status"),+ "errors": errors,+ "profiles": sorted(+ name+ for name in manifest.get("artifacts", {})+ if name in ("cpu.pb", "heap.pb.gz")+ ),+ "binary_sha256": manifest.get("binary_sha256"),+ "source_build_binding": manifest.get("source_build_binding", "UNVERIFIED"),+ "declared_build_unverified": manifest.get("declared_build_unverified"),+ "experiment": manifest.get("experiment"),+ "source": manifest.get("source"),+ "attached_evidence": sorted(evidence),+ "comparison_ready": any(+ token in label.lower()+ for label in evidence+ for token in ("result", "correct", "bench", "telemetry")+ ),+ "prompts": [+ str(pathlib.Path(__file__).resolve().parent / name)+ for name in ("PROMPT_CPU.md", "PROMPT_HEAP.md", "PROMPT_COMPARE.md")+ ],+ }+ if not summary["comparison_ready"]:+ summary["warning"] = (+ "No correctness/benchmark/telemetry attachment was identified; "+ "performance conclusions must be INCONCLUSIVE."+ )+ print(json.dumps(summary, indent=2, sort_keys=True))+ return 0 if summary["valid"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/demo/playbooks/debug-profiling/test_tooling.py b/demo/playbooks/debug-profiling/test_tooling.pynew file mode 100644index 000000000..b1f8de849--- /dev/null+++ b/demo/playbooks/debug-profiling/test_tooling.py@@ -0,0 +1,101 @@+import json+import pathlib+import stat+import subprocess+import sys+import tempfile+import unittest+++HERE = pathlib.Path(__file__).resolve().parent+++class CaptureToolingTests(unittest.TestCase):+ def test_missing_requested_profile_is_machine_readable_failure(self):+ with tempfile.TemporaryDirectory() as parent:+ output = pathlib.Path(parent) / "capture"+ result = subprocess.run(+ [+ sys.executable,+ str(HERE / "capture.py"),+ "--output",+ str(output),+ "--cpu-seconds",+ "1",+ "--workload",+ "negative-smoke",+ "--corpus",+ "none",+ "--concurrency",+ "1",+ "--cache-state",+ "cold",+ "--build-features",+ "debug-profiling",+ "--build-profile",+ "debug",+ "--",+ "/usr/bin/sleep",+ "0.01",+ ],+ check=False,+ )+ self.assertEqual(result.returncode, 2)+ manifest_path = output / "manifest.json"+ manifest = json.loads(manifest_path.read_text())+ self.assertEqual(manifest["status"], "profile_failed")+ self.assertEqual(manifest["missing_requested_artifacts"], ["cpu.pb"])+ self.assertIn("server.log", manifest["artifacts"])+ self.assertIn("git_head", manifest["source"])+ self.assertEqual(+ stat.S_IMODE(manifest_path.stat().st_mode),+ 0o600,+ )++ inspect = subprocess.run(+ [sys.executable, str(HERE / "inspect.py"), str(output)],+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(inspect.returncode, 1)+ self.assertFalse(json.loads(inspect.stdout)["valid"])++ def test_stop_after_requires_publication_grace(self):+ result = subprocess.run(+ [+ sys.executable,+ str(HERE / "capture.py"),+ "--output",+ "/unused",+ "--cpu-seconds",+ "10",+ "--delay-seconds",+ "5",+ "--stop-after",+ "15",+ "--workload",+ "unused",+ "--corpus",+ "unused",+ "--concurrency",+ "1",+ "--cache-state",+ "cold",+ "--build-features",+ "debug-profiling",+ "--build-profile",+ "profiling",+ "--",+ "/usr/bin/true",+ ],+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("after capture", result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/recipes/README.md b/docs/recipes/README.mdindex d506a5f0d..bb8633609 100644--- a/docs/recipes/README.md+++ b/docs/recipes/README.md@@ -20,5 +20,6 @@ These are practical "how do I actually do X" recipes, not an API reference (that| [Continuous anomaly datafeeds](./continuous-anomaly-datafeeds.md) | A live `_ml` datafeed that re-scores an index on a timer and stores new anomaly records you poll | [`datafeed_demo.py`](../examples/continuous-anomaly-datafeeds/datafeed_demo.py) || [Migrate from Elasticsearch](./migrate-from-elasticsearch.md) | Point your existing ES client at XERJ — same wire, change the URL | [`migrate_demo.sh`](../examples/migrate-from-elasticsearch/migrate_demo.sh) || [Production deployment](./production-deployment.md) | The hardened posture: in-process TLS + API-key auth, health-probe & gRPC posture, air-gapped neural-model staging, and copying data out of a live Elasticsearch (scroll + bulk) | inline `curl` + `bash` |+| [Diagnose CPU and memory with pprof](./debug-profiling.md) | A private, bounded, symbolized CPU/heap capture with reproducibility manifest, artifact validation, and AI analysis prompts | [`debug-profiling/`](../../demo/playbooks/debug-profiling/) |Every example is stdlib-only Python 3, plain `curl`, or the `xerj` binary itself — no dependencies to install. Start XERJ (`./target/release/xerj --data-dir ./data --insecure`), then run any example.diff --git a/docs/recipes/debug-profiling.md b/docs/recipes/debug-profiling.mdnew file mode 100644index 000000000..5eb755637--- /dev/null+++ b/docs/recipes/debug-profiling.md@@ -0,0 +1,53 @@+# Diagnose XERJ CPU and memory with pprof++Use this recipe when a repeatable XERJ workload is slow or consumes unexplained memory. The debug build can emit Google pprof-compatible CPU and jemalloc in-use heap profiles without exposing a network debug endpoint.++The tooling is Linux-only and off by default. It is intended for controlled experiments, not always-on production use.++## 1. Build a symbolized profiling binary++From the repository root:++```bash+(cd engine && cargo build --profile profiling -j 32 -p xerj-server \+ --no-default-features --features debug-profiling)+```++The `profiling` profile uses thin LTO and parallel code generation for iteration and retains symbols. It is not production-codegen-equivalent. Reconfirm any winning optimization with `--profile profiling-final`, which inherits release fat LTO and one codegen unit while retaining symbols.++## 2. Capture one dimension at a time++CPU example:++```bash+python3 demo/playbooks/debug-profiling/capture.py \+ --output /tmp/xerj-cpu-run \+ --cpu-seconds 30 \+ --delay-seconds 5 \+ --workload my-ingest-v1 \+ --corpus corpus-sha256-or-stable-id \+ --concurrency 4 \+ --cache-state cold \+ --build-features debug-profiling \+ --build-profile profiling \+ --attach correctness=/tmp/correctness.json \+ --attach telemetry=/tmp/memory.ndjson \+ -- \+ engine/target/profiling/xerj --insecure --data-dir /tmp/xerj-profile-data+```++Start the workload from another terminal during the five-second delay. Repeat into fresh data and output directories with `--heap-seconds 30` instead of `--cpu-seconds 30`. Separate runs avoid CPU and heap profiler interference.++Delay is relative to process start, not a readiness check. Delay zero includes configuration, TLS setup, engine replay, and router construction.++## 3. Validate before analysis++```bash+python3 demo/playbooks/debug-profiling/inspect.py /tmp/xerj-cpu-run+```++The command verifies hashes and basic formats, reports missing evidence, and points agents to the CPU, heap, and A/B prompt templates. Without attached correctness and benchmark/telemetry evidence, performance conclusions are `INCONCLUSIVE`.++The binary SHA-256 is exact, but the wrapper cannot cryptographically bind that binary to the recorded checkout or declared Cargo profile/features; the manifest labels that relationship `UNVERIFIED`.++See the complete safety, failure, stale-lock, pprof viewing, and A/B instructions in [`demo/playbooks/debug-profiling/README.md`](../../demo/playbooks/debug-profiling/README.md).diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex e45f41c80..6f0e1b58c 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -2,6 +2,15 @@# It is not intended for manual editing.version = 4+[[package]]+name = "addr2line"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b"+dependencies = [+ "gimli",+]+[[package]]name = "adler2"version = "2.0.1"@@ -42,6 +51,15 @@ dependencies = ["memchr",]+[[package]]+name = "aligned-vec"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"+dependencies = [+ "equator",+]+[[package]]name = "alloc-no-stdlib"version = "2.0.4"@@ -365,6 +383,21 @@ dependencies = ["tower-service",]+[[package]]+name = "backtrace"+version = "0.3.76"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"+dependencies = [+ "addr2line",+ "cfg-if",+ "libc",+ "miniz_oxide",+ "object",+ "rustc-demangle",+ "windows-link",+]+[[package]]name = "base64"version = "0.13.1"@@ -834,6 +867,15 @@ version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]+name = "cpp_demangle"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253"+dependencies = [+ "cfg-if",+]+[[package]]name = "cpubits"version = "0.1.1"@@ -1075,6 +1117,15 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2"+[[package]]+name = "debugid"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d"+dependencies = [+ "uuid",+]+[[package]]name = "defmt"version = "1.1.1"@@ -1298,6 +1349,26 @@ dependencies = ["log",]+[[package]]+name = "equator"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"+dependencies = [+ "equator-macro",+]++[[package]]+name = "equator-macro"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "equivalent"version = "1.0.2"@@ -1416,6 +1487,24 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+[[package]]+name = "findshlibs"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64"+dependencies = [+ "cc",+ "lazy_static",+ "libc",+ "winapi",+]++[[package]]+name = "fixedbitset"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"+[[package]]name = "fixedbitset"version = "0.5.7"@@ -1790,6 +1879,12 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "gimli"+version = "0.32.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"+[[package]]name = "glob"version = "0.3.3"@@ -2354,6 +2449,23 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]+name = "jemalloc_pprof"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a0d44c349cfe2654897fadcb9de4f0bfbf48288ec344f700b2bd59f152dd209"+dependencies = [+ "anyhow",+ "libc",+ "mappings",+ "once_cell",+ "pprof_util",+ "tempfile",+ "tikv-jemalloc-ctl",+ "tokio",+ "tracing",+]+[[package]]name = "jiff"version = "0.2.34"@@ -2574,6 +2686,19 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"+[[package]]+name = "mappings"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8bab1e61a4b76757edb59cd81fcaa7f3ba9018d43b527d9abfad877b4c6c60f2"+dependencies = [+ "anyhow",+ "libc",+ "once_cell",+ "pprof_util",+ "tracing",+]+[[package]]name = "matchers"version = "0.2.0"@@ -2725,7 +2850,7 @@ dependencies = ["httparse","memchr","mime",- "spin",+ "spin 0.9.8","version_check",]@@ -2767,6 +2892,17 @@ dependencies = ["rawpointer",]+[[package]]+name = "nix"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b"+dependencies = [+ "bitflags 1.3.2",+ "cfg-if",+ "libc",+]+[[package]]name = "nom"version = "7.1.3"@@ -2795,6 +2931,20 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "num"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"+dependencies = [+ "num-bigint",+ "num-complex",+ "num-integer",+ "num-iter",+ "num-rational",+ "num-traits",+]+[[package]]name = "num-bigint"version = "0.4.6"@@ -2830,6 +2980,27 @@ dependencies = ["num-traits",]+[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+]+[[package]]name = "num-traits"version = "0.2.19"@@ -2856,6 +3027,15 @@ version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"+[[package]]+name = "object"+version = "0.37.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe"+dependencies = [+ "memchr",+]+[[package]]name = "office_oxide"version = "0.1.8"@@ -3091,13 +3271,23 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "petgraph"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"+dependencies = [+ "fixedbitset 0.4.2",+ "indexmap 2.14.0",+]+[[package]]name = "petgraph"version = "0.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"dependencies = [- "fixedbitset",+ "fixedbitset 0.5.7","indexmap 2.14.0",]@@ -3294,6 +3484,45 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"+[[package]]+name = "pprof"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38a01da47675efa7673b032bf8efd8214f1917d89685e07e395ab125ea42b187"+dependencies = [+ "aligned-vec",+ "backtrace",+ "cfg-if",+ "findshlibs",+ "libc",+ "log",+ "nix",+ "once_cell",+ "prost 0.12.6",+ "prost-build 0.12.6",+ "prost-derive 0.12.6",+ "sha2 0.10.9",+ "smallvec",+ "spin 0.10.1",+ "symbolic-demangle",+ "tempfile",+ "thiserror 2.0.18",+]++[[package]]+name = "pprof_util"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eea0cc524de808a6d98d192a3d99fe95617031ad4a52ec0a0f987ef4432e8fe1"+dependencies = [+ "anyhow",+ "backtrace",+ "flate2",+ "num",+ "paste",+ "prost 0.14.4",+]+[[package]]name = "ppv-lite86"version = "0.2.21"@@ -3337,6 +3566,16 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "prost"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29"+dependencies = [+ "bytes",+ "prost-derive 0.12.6",+]+[[package]]name = "prost"version = "0.13.5"@@ -3344,7 +3583,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"dependencies = ["bytes",- "prost-derive",+ "prost-derive 0.13.5",+]++[[package]]+name = "prost"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"+dependencies = [+ "bytes",+ "prost-derive 0.14.4",+]++[[package]]+name = "prost-build"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"+dependencies = [+ "bytes",+ "heck",+ "itertools 0.10.5",+ "log",+ "multimap",+ "once_cell",+ "petgraph 0.6.5",+ "prettyplease",+ "prost 0.12.6",+ "prost-types 0.12.6",+ "regex",+ "syn",+ "tempfile",][[package]]@@ -3358,15 +3628,28 @@ dependencies = ["log","multimap","once_cell",- "petgraph",+ "petgraph 0.7.1","prettyplease",- "prost",- "prost-types",+ "prost 0.13.5",+ "prost-types 0.13.5","regex","syn","tempfile",]+[[package]]+name = "prost-derive"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"+dependencies = [+ "anyhow",+ "itertools 0.10.5",+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "prost-derive"version = "0.13.5"@@ -3380,6 +3663,19 @@ dependencies = ["syn",]+[[package]]+name = "prost-derive"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"+dependencies = [+ "anyhow",+ "itertools 0.14.0",+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "prost-reflect"version = "0.14.7"@@ -3389,8 +3685,17 @@ dependencies = ["logos","miette","once_cell",- "prost",- "prost-types",+ "prost 0.13.5",+ "prost-types 0.13.5",+]++[[package]]+name = "prost-types"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0"+dependencies = [+ "prost 0.12.6",][[package]]@@ -3399,7 +3704,7 @@ version = "0.13.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16"dependencies = [- "prost",+ "prost 0.13.5",][[package]]@@ -3416,9 +3721,9 @@ checksum = "6f352af331bf637b8ecc720f7c87bf903d2571fa2e14a66e9b2558846864b54a"dependencies = ["bytes","miette",- "prost",+ "prost 0.13.5","prost-reflect",- "prost-types",+ "prost-types 0.13.5","protox-parse","thiserror 1.0.69",]@@ -3431,7 +3736,7 @@ checksum = "a3a462d115462c080ae000c29a47f0b3985737e5d3a995fcdbcaa5c782068dde"dependencies = ["logos","miette",- "prost-types",+ "prost-types 0.13.5","thiserror 1.0.69",]@@ -3872,6 +4177,12 @@ dependencies = ["serde_derive",]+[[package]]+name = "rustc-demangle"+version = "0.1.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"+[[package]]name = "rustc-hash"version = "2.1.2"@@ -4283,6 +4594,15 @@ version = "0.9.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"+[[package]]+name = "spin"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3"+dependencies = [+ "lock_api",+]+[[package]]name = "spm_precompiled"version = "0.1.4"@@ -4342,6 +4662,29 @@ version = "2.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]+name = "symbolic-common"+version = "12.18.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "332615d90111d8eeaf86a84dc9bbe9f65d0d8c5cf11b4caccedc37754eb0dcfd"+dependencies = [+ "debugid",+ "memmap2",+ "stable_deref_trait",+ "uuid",+]++[[package]]+name = "symbolic-demangle"+version = "12.18.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "912017718eb4d21930546245af9a3475c9dccf15675a5c215664e76621afc471"+dependencies = [+ "cpp_demangle",+ "rustc-demangle",+ "symbolic-common",+]+[[package]]name = "syn"version = "2.0.117"@@ -4496,6 +4839,17 @@ dependencies = ["zune-jpeg",]+[[package]]+name = "tikv-jemalloc-ctl"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "661f1f6a57b3a36dc9174a2c10f19513b4866816e13425d3e418b11cc37bc24c"+dependencies = [+ "libc",+ "paste",+ "tikv-jemalloc-sys",+]+[[package]]name = "tikv-jemalloc-sys"version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"@@ -4748,7 +5102,7 @@ dependencies = ["hyper-util","percent-encoding","pin-project",- "prost",+ "prost 0.13.5","socket2 0.5.10","tokio","tokio-stream",@@ -4766,8 +5120,8 @@ checksum = "9557ce109ea773b399c9b9e5dca39294110b74f1f342cb347a80d1fce8c26a11"dependencies = ["prettyplease","proc-macro2",- "prost-build",- "prost-types",+ "prost-build 0.13.5",+ "prost-types 0.13.5","quote","syn",]@@ -6096,9 +6450,12 @@ dependencies = ["axum","axum-server","chrono",+ "flate2",+ "jemalloc_pprof","memchr","memmap2",- "prost",+ "pprof",+ "prost 0.13.5","protox","rand 0.8.5","rayon",diff --git a/engine/Cargo.toml b/engine/Cargo.tomlindex b98ac9aee..d8cc59723 100644--- a/engine/Cargo.toml+++ b/engine/Cargo.toml@@ -109,3 +109,18 @@ codegen-units = 1strip = truepanic = "abort"+# Fast iteration profile: symbolized with thin LTO and parallel codegen.+# It is intentionally not production-codegen-equivalent.+[profile.profiling]+inherits = "release"+debug = 1+strip = false+lto = "thin"+codegen-units = 16++# Final confirmation profile: identical optimizer/LTO/codegen settings to+# release, but retains symbols for pprof.+[profile.profiling-final]+inherits = "release"+debug = 1+strip = falsediff --git a/engine/crates/xerj-server/Cargo.toml b/engine/crates/xerj-server/Cargo.tomlindex 189e3aeb4..98e8fcb0c 100644--- a/engine/crates/xerj-server/Cargo.toml+++ b/engine/crates/xerj-server/Cargo.toml@@ -66,10 +66,21 @@ prost.workspace = truedefault = ["neural"]neural = ["xerj-engine/neural"]onnx-experimental = ["xerj-engine/onnx-experimental"]+# Diagnostic-only profiling. It is excluded from all shipped feature sets:+# jemalloc profiling changes allocator fast paths and pprof installs SIGPROF.+debug-profiling = [+ "dep:jemalloc_pprof",+ "dep:pprof",+ "tikv-jemallocator/profiling",+][target.'cfg(not(target_env = "msvc"))'.dependencies]tikv-jemallocator = "0.6"+[target.'cfg(all(target_os = "linux", not(target_env = "msvc")))'.dependencies]+jemalloc_pprof = { version = "0.8", features = ["symbolize"], optional = true }+pprof = { version = "0.15", features = ["prost-codec"], optional = true }+[build-dependencies]# Compile ../../proto/xerj.proto → Rust at build time. `protox` parses the# .proto in pure Rust (no host protoc); `tonic-build` turns the resulting@@ -81,3 +92,4 @@ protox = { workspace = true }# HTTPS round-trip test against the in-process rustls listener.reqwest = { workspace = true }tempfile = { workspace = true }+flate2 = "1"diff --git a/engine/crates/xerj-server/src/debug_profiling.rs b/engine/crates/xerj-server/src/debug_profiling.rsnew file mode 100644index 000000000..03b693b8a--- /dev/null+++ b/engine/crates/xerj-server/src/debug_profiling.rs@@ -0,0 +1,387 @@+//! Bounded, local profiling for controlled benchmark runs.+//!+//! Compiled only with `--features debug-profiling`. There is deliberately no+//! HTTP endpoint. The output directory must exist and captures are requested+//! before process start:+//!+//! ```text+//! XERJ_DEBUG_PROFILE_DIR=/private/run \+//! XERJ_DEBUG_CPU_SECONDS=30 XERJ_DEBUG_HEAP_SECONDS=30 xerj+//! ```++use std::fs::{File, OpenOptions};+use std::io::{self, Write};+use std::os::unix::fs::OpenOptionsExt;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Condvar, Mutex};+use std::thread::JoinHandle;+use std::time::Duration;++use anyhow::{anyhow, Context, Result};+use pprof::protos::Message;++const MAX_CAPTURE_SECONDS: u64 = 300;+const MAX_CPU_HZ: i32 = 1_000;++#[derive(Debug, Clone, PartialEq, Eq)]+struct Config {+ output_dir: PathBuf,+ cpu_seconds: Option<u64>,+ heap_seconds: Option<u64>,+ cpu_hz: i32,+ delay_seconds: u64,+}++impl Config {+ fn from_env() -> Result<Option<Self>> {+ let Some(output) = std::env::var_os("XERJ_DEBUG_PROFILE_DIR") else {+ return Ok(None);+ };+ Self::parse(+ PathBuf::from(output),+ std::env::var("XERJ_DEBUG_CPU_SECONDS").ok().as_deref(),+ std::env::var("XERJ_DEBUG_HEAP_SECONDS").ok().as_deref(),+ std::env::var("XERJ_DEBUG_CPU_HZ").ok().as_deref(),+ std::env::var("XERJ_DEBUG_PROFILE_DELAY_SECONDS")+ .ok()+ .as_deref(),+ )+ .map(Some)+ }++ fn parse(+ output_dir: PathBuf,+ cpu_seconds: Option<&str>,+ heap_seconds: Option<&str>,+ cpu_hz: Option<&str>,+ delay_seconds: Option<&str>,+ ) -> Result<Self> {+ let output_dir = output_dir.canonicalize().with_context(|| {+ format!("profile directory does not exist: {}", output_dir.display())+ })?;+ if !output_dir.is_dir() {+ return Err(anyhow!(+ "profile output is not a directory: {}",+ output_dir.display()+ ));+ }+ let cpu_seconds = parse_duration("XERJ_DEBUG_CPU_SECONDS", cpu_seconds)?;+ let heap_seconds = parse_duration("XERJ_DEBUG_HEAP_SECONDS", heap_seconds)?;+ if cpu_seconds.is_none() && heap_seconds.is_none() {+ return Err(anyhow!(+ "set XERJ_DEBUG_CPU_SECONDS and/or XERJ_DEBUG_HEAP_SECONDS"+ ));+ }+ let cpu_hz = match cpu_hz {+ Some(value) => value+ .parse::<i32>()+ .with_context(|| format!("XERJ_DEBUG_CPU_HZ is not an integer: {value}"))?,+ None => 100,+ };+ if !(1..=MAX_CPU_HZ).contains(&cpu_hz) {+ return Err(anyhow!(+ "XERJ_DEBUG_CPU_HZ must be in 1..={MAX_CPU_HZ}, got {cpu_hz}"+ ));+ }+ let delay_seconds = match delay_seconds {+ Some(value) => value.parse::<u64>().with_context(|| {+ format!("XERJ_DEBUG_PROFILE_DELAY_SECONDS is not an integer: {value}")+ })?,+ None => 0,+ };+ if delay_seconds > MAX_CAPTURE_SECONDS {+ return Err(anyhow!(+ "XERJ_DEBUG_PROFILE_DELAY_SECONDS must be in 0..={MAX_CAPTURE_SECONDS}, got {delay_seconds}"+ ));+ }+ Ok(Self {+ output_dir,+ cpu_seconds,+ heap_seconds,+ cpu_hz,+ delay_seconds,+ })+ }+}++fn parse_duration(name: &str, value: Option<&str>) -> Result<Option<u64>> {+ let Some(value) = value else {+ return Ok(None);+ };+ let seconds = value+ .parse::<u64>()+ .with_context(|| format!("{name} is not an integer: {value}"))?;+ if !(1..=MAX_CAPTURE_SECONDS).contains(&seconds) {+ return Err(anyhow!(+ "{name} must be in 1..={MAX_CAPTURE_SECONDS}, got {seconds}"+ ));+ }+ Ok(Some(seconds))+}++pub struct ProfileRuntime {+ workers: Vec<JoinHandle<()>>,+ stop: Arc<(Mutex<bool>, Condvar)>,+ lock_path: Option<PathBuf>,+ _lock: File,+}++impl Drop for ProfileRuntime {+ fn drop(&mut self) {+ *self+ .stop+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner()) = true;+ self.stop.1.notify_all();+ for worker in self.workers.drain(..) {+ let _ = worker.join();+ }+ if let Some(path) = self.lock_path.take() {+ let _ = std::fs::remove_file(path);+ }+ }+}++pub fn spawn() -> Result<Option<ProfileRuntime>> {+ let Some(config) = Config::from_env()? else {+ return Ok(None);+ };+ spawn_configured(config).map(Some)+}++fn spawn_configured(config: Config) -> Result<ProfileRuntime> {+ let lock_path = config.output_dir.join(".xerj-debug-profile.lock");+ let lock = OpenOptions::new()+ .write(true)+ .create_new(true)+ .mode(0o600)+ .open(&lock_path)+ .with_context(|| {+ format!(+ "profile directory is already in use or contains stale lock: {}",+ lock_path.display()+ )+ })?;+ let stop = Arc::new((Mutex::new(false), Condvar::new()));+ let mut runtime = ProfileRuntime {+ workers: Vec::new(),+ stop,+ lock_path: Some(lock_path),+ _lock: lock,+ };+ if let Some(seconds) = config.cpu_seconds {+ let directory = config.output_dir.clone();+ let stop = Arc::clone(&runtime.stop);+ let frequency = config.cpu_hz;+ let delay = config.delay_seconds;+ runtime.workers.push(+ std::thread::Builder::new()+ .name("xerj-debug-cpu-profile".into())+ .spawn(move || {+ if wait_for_duration_or_stop(&stop, Duration::from_secs(delay)) {+ return;+ }+ if let Err(error) = capture_cpu(&directory, seconds, frequency, &stop) {+ write_profile_error(&directory, "cpu", &error);+ tracing::error!(%error, "CPU profile capture failed");+ }+ })+ .context("spawn CPU profile worker")?,+ );+ }+ if let Some(seconds) = config.heap_seconds {+ let directory = config.output_dir.clone();+ let stop = Arc::clone(&runtime.stop);+ let delay = config.delay_seconds;+ runtime.workers.push(+ std::thread::Builder::new()+ .name("xerj-debug-heap-profile".into())+ .spawn(move || {+ if wait_for_duration_or_stop(&stop, Duration::from_secs(delay)) {+ return;+ }+ if let Err(error) = capture_heap(&directory, seconds, &stop) {+ write_profile_error(&directory, "heap", &error);+ tracing::error!(%error, "heap profile capture failed");+ }+ })+ .context("spawn heap profile worker")?,+ );+ }+ Ok(runtime)+}++fn capture_cpu(+ output_dir: &Path,+ seconds: u64,+ frequency: i32,+ stop: &(Mutex<bool>, Condvar),+) -> Result<()> {+ let guard = pprof::ProfilerGuardBuilder::default()+ .frequency(frequency)+ .blocklist(&["libc", "libgcc", "pthread", "vdso"])+ .build()+ .context("start SIGPROF CPU sampler")?;+ wait_for_duration_or_stop(stop, Duration::from_secs(seconds));+ let report = guard.report().build().context("build CPU profile")?;+ let profile = report.pprof().context("convert CPU profile to pprof")?;+ let mut bytes = Vec::new();+ profile.encode(&mut bytes).context("encode CPU profile")?;+ write_new_atomic(output_dir, "cpu.pb", &bytes)+}++fn capture_heap(output_dir: &Path, seconds: u64, stop: &(Mutex<bool>, Condvar)) -> Result<()> {+ let control = Arc::clone(+ jemalloc_pprof::PROF_CTL+ .as_ref()+ .ok_or_else(|| anyhow!("jemalloc was not compiled/configured with profiling"))?,+ );+ let mut ctl = control.blocking_lock();+ if ctl.activated() {+ return Err(anyhow!("jemalloc profiling is already active"));+ }+ ctl.activate().context("activate jemalloc profiling")?;+ drop(ctl);+ wait_for_duration_or_stop(stop, Duration::from_secs(seconds));+ let mut ctl = control.blocking_lock();+ let dump = ctl.dump_pprof().context("dump heap pprof");+ let deactivate = ctl.deactivate().context("deactivate jemalloc profiling");+ let bytes = dump?;+ deactivate?;+ write_new_atomic(output_dir, "heap.pb.gz", &bytes)+}++fn wait_for_duration_or_stop(stop: &(Mutex<bool>, Condvar), duration: Duration) -> bool {+ let guard = stop.0.lock().unwrap_or_else(|error| error.into_inner());+ let (guard, _) = stop+ .1+ .wait_timeout_while(guard, duration, |stopped| !*stopped)+ .unwrap_or_else(|error| error.into_inner());+ *guard+}++fn write_new_atomic(output_dir: &Path, name: &str, contents: &[u8]) -> Result<()> {+ let final_path = output_dir.join(name);+ let temporary = output_dir.join(format!(".{name}.{}.tmp", std::process::id()));+ let mut file = OpenOptions::new()+ .write(true)+ .create_new(true)+ .mode(0o600)+ .open(&temporary)+ .with_context(|| format!("create profile temporary file: {}", temporary.display()))?;+ let result = (|| -> io::Result<()> {+ file.write_all(contents)?;+ file.sync_all()?;+ // hard_link fails if the final name exists; rename would overwrite it.+ std::fs::hard_link(&temporary, &final_path)?;+ std::fs::remove_file(&temporary)+ })();+ if result.is_err() {+ let _ = std::fs::remove_file(&temporary);+ }+ result.with_context(|| format!("publish profile: {}", final_path.display()))+}++fn write_profile_error(output_dir: &Path, kind: &str, error: &anyhow::Error) {+ let payload = serde_json::json!({+ "schema": "xerj.debug_profile.error.v1",+ "profiler": kind,+ "error": format!("{error:#}"),+ });+ if let Ok(bytes) = serde_json::to_vec_pretty(&payload) {+ let _ = write_new_atomic(output_dir, &format!("{kind}-error.json"), &bytes);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn configuration_requires_a_bounded_capture() {+ let dir = tempfile::tempdir().unwrap();+ assert!(Config::parse(dir.path().into(), None, None, None, None).is_err());+ for invalid in ["0", "301", "garbage"] {+ assert!(Config::parse(dir.path().into(), Some(invalid), None, None, None).is_err());+ }+ }++ #[test]+ fn configuration_defaults_to_low_rate_cpu_sampling() {+ let dir = tempfile::tempdir().unwrap();+ let config = Config::parse(dir.path().into(), Some("2"), None, None, Some("3")).unwrap();+ assert_eq!(config.cpu_seconds, Some(2));+ assert_eq!(config.cpu_hz, 100);+ assert_eq!(config.delay_seconds, 3);+ }++ #[test]+ fn atomic_publication_never_overwrites_evidence() {+ let dir = tempfile::tempdir().unwrap();+ write_new_atomic(dir.path(), "profile.pb", b"first").unwrap();+ assert!(write_new_atomic(dir.path(), "profile.pb", b"second").is_err());+ assert_eq!(+ std::fs::read(dir.path().join("profile.pb")).unwrap(),+ b"first"+ );+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ std::fs::metadata(dir.path().join("profile.pb"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ }++ #[test]+ fn capture_wait_is_interruptible() {+ let stop = Arc::new((Mutex::new(false), Condvar::new()));+ let thread_stop = Arc::clone(&stop);+ let started = std::time::Instant::now();+ let worker = std::thread::spawn(move || {+ wait_for_duration_or_stop(&thread_stop, Duration::from_secs(300))+ });+ *stop.0.lock().unwrap() = true;+ stop.1.notify_all();+ worker.join().unwrap();+ assert!(started.elapsed() < Duration::from_secs(1));+ }++ #[test]+ fn heap_capture_is_a_pprof_gzip() {+ use std::io::Read;++ let dir = tempfile::tempdir().unwrap();+ let stop = (Mutex::new(false), Condvar::new());+ let allocation = std::thread::spawn(|| vec![0x5a_u8; 8 * 1024 * 1024]);+ capture_heap(dir.path(), 1, &stop).unwrap();+ let bytes = std::fs::read(dir.path().join("heap.pb.gz")).unwrap();+ assert_eq!(bytes.get(..2), Some(&[0x1f, 0x8b][..]));+ let mut protobuf = Vec::new();+ flate2::read::GzDecoder::new(bytes.as_slice())+ .read_to_end(&mut protobuf)+ .unwrap();+ pprof::protos::Profile::decode(protobuf.as_slice()).unwrap();+ drop(allocation.join().unwrap());+ }++ #[test]+ fn cpu_capture_is_a_nonempty_pprof_protobuf() {+ let dir = tempfile::tempdir().unwrap();+ let stop = (Mutex::new(false), Condvar::new());+ let work = std::thread::spawn(|| {+ let deadline = std::time::Instant::now() + Duration::from_secs(1);+ let mut value = 1_u64;+ while std::time::Instant::now() < deadline {+ value = std::hint::black_box(value.wrapping_mul(6364136223846793005));+ }+ });+ capture_cpu(dir.path(), 1, 100, &stop).unwrap();+ let bytes = std::fs::read(dir.path().join("cpu.pb")).unwrap();+ pprof::protos::Profile::decode(bytes.as_slice()).unwrap();+ work.join().unwrap();+ }+}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex fb2233afb..424e24848 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -44,11 +44,19 @@ static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;// 1 s dirty/muzzy decay purges freed pages continuously; the same load then// holds a flat working-set RSS. Ingest throughput cost measured: none// (within noise, ~36k docs/s single-index bulk either way).-#[cfg(not(target_env = "msvc"))]+#[cfg(all(not(target_env = "msvc"), not(feature = "debug-profiling")))]#[allow(non_upper_case_globals)]#[export_name = "_rjem_malloc_conf"]pub static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000\0";+// Preserve the production decay policy. Merely compiling this feature enables+// jemalloc's profiler; sampling remains inactive until the local controller+// starts a bounded capture.+#[cfg(all(not(target_env = "msvc"), feature = "debug-profiling"))]+#[allow(non_upper_case_globals)]+#[export_name = "_rjem_malloc_conf"]+pub static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000,prof:true,prof_active:false,lg_prof_sample:19\0";+use std::net::SocketAddr;use std::path::{Path, PathBuf};@@ -66,6 +74,8 @@ use xerj_common::{config::Config, metrics::Metrics};use xerj_console_api::{state::ClusterMode, ConsoleState};use xerj_engine::Engine;+#[cfg(all(target_os = "linux", feature = "debug-profiling"))]+mod debug_profiling;mod grpc;// ─────────────────────────────────────────────────────────────────────────────@@ -1257,6 +1267,11 @@ async fn async_main() -> Result<()> {std::process::exit(code);}+ // Start profiling before config loading, TLS, engine replay, and router+ // construction so delay=0 is a genuine initialization profile.+ #[cfg(all(target_os = "linux", feature = "debug-profiling"))]+ let _debug_profiles = debug_profiling::spawn()?;+// 0. Record startup time as early as possible.let startup_start = std::time::Instant::now();@@ -1449,7 +1464,6 @@ async fn async_main() -> Result<()> {// is the structural guard against the 112 GiB OOM class — writes get// a 429 circuit_breaking_exception before the kernel OOM-kills us.state.engine.spawn_resource_sampler();-// 13. Start servers concurrentlylet rest_tls = tls_config.clone();let rest = tokio::spawn(async move {