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
ci(hub-packs): a backfill report row for every corpus in every run (spec §12.1) (#1522)
xerj-org87ed5ff6e6c5
diff --git a/.github/workflows/hub-packs.yml b/.github/workflows/hub-packs.ymlindex b9193ca18..211e6aae6 100644--- a/.github/workflows/hub-packs.yml+++ b/.github/workflows/hub-packs.yml@@ -309,10 +309,12 @@ jobs:HUB_PUBKEY_HEX: ${{ needs.preflight.outputs.pubkey }}steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0+ id: checkoutwith:persist-credentials: false- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ id: fetch-binwith:name: xerj-binpath: bin@@ -325,8 +327,12 @@ jobs:# once with "exact read-back count 0 disagrees with sealed count 1" (the# autoindex group already exists there).- name: Start a throwaway builder node+ id: startrun: |set -euo pipefail+ # Each stage's output also goes to a log the backfill report quotes on failure.+ mkdir -p "$RUNNER_TEMP/log"+ exec > >(tee -a "$RUNNER_TEMP/log/start.log") 2>&1chmod +x bin/xerjNODE="$RUNNER_TEMP/node"mkdir -p "$NODE/data" "$RUNNER_TEMP/pack-out"@@ -345,11 +351,13 @@ jobs:echo "the builder node did not become healthy"; cat "$NODE/node.log"; exit 1- name: Build and sign the pack+ id: buildenv:HUB_SIGNING_SEED: ${{ secrets.HUB_SIGNING_SEED }}XERJ_CODE_HOME: ${{ runner.temp }}/code-homerun: |set -euo pipefail+ exec > >(tee -a "$RUNNER_TEMP/log/build.log") 2>&1umask 077printf '%s' "$HUB_SIGNING_SEED" > "$RUNNER_TEMP/pack.key"# The builder parses untrusted source trees: keep the seed out of its environment.@@ -373,8 +381,10 @@ jobs:# verifies under the key clients embed, and carries the layout `hub pull`# reads. (Clients re-verify sha256 and signature themselves.)- name: Verify the signature and the layout+ id: verifyrun: |set -euo pipefail+ exec > >(tee -a "$RUNNER_TEMP/log/verify.log") 2>&1ARCHIVE="$PACK_OUT/$SLUG-$PIN8.hubpack.tar.zst"test -s "$ARCHIVE"; test -s "$ARCHIVE.sig"bash tools/hub-packs/ed25519.sh verify "$HUB_PUBKEY_HEX" "$ARCHIVE" "$ARCHIVE.sig"@@ -393,11 +403,13 @@ jobs:# release as a DRAFT, upload to the draft, publish last. Published releases# are never deleted by a rebuild.- name: Pick an unused release tag+ id: tagif: ${{ !inputs.dry_run }}env:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |set -euo pipefail+ exec > >(tee -a "$RUNNER_TEMP/log/tag.log") 2>&1BASE="pack-$SLUG-$PIN8"TAG="$BASE"; N=1while gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1 \@@ -409,11 +421,13 @@ jobs:# --prerelease and --latest=false: a pack must never become the repository's# "latest" release, which the installer chain reads.- name: Upload the pack to a draft release+ id: uploadif: ${{ !inputs.dry_run }}env:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |set -euo pipefail+ exec > >(tee -a "$RUNNER_TEMP/log/upload.log") 2>&1ARCHIVE="$PACK_OUT/$SLUG-$PIN8.hubpack.tar.zst"zstd -dc "$ARCHIVE" | tar -xOf - pack.json > "$RUNNER_TEMP/pack.json"{@@ -436,12 +450,14 @@ jobs:# catalogue, then `--def` for a symbol from the pack's own defs.jsonl and one# question. A failure fails the job and leaves the release a draft.- name: Consumer end-to-end (pull, --def, one question)+ id: e2eenv:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}HUB_SIGNING_SEED: ${{ secrets.HUB_SIGNING_SEED }}DRY_RUN: ${{ inputs.dry_run }}run: |set -euo pipefail+ exec > >(tee -a "$RUNNER_TEMP/log/e2e.log") 2>&1FILE="$SLUG-$PIN8.hubpack.tar.zst"SRC="$RUNNER_TEMP/e2e-src"; mkdir -p "$SRC"if [ "$DRY_RUN" = "true" ]; then@@ -468,12 +484,15 @@ jobs:# "tag_name was used by an immutable release" retag this draft to the next# free -rN and publish that.- name: Publish the draft (retag past a burned tag if refused)+ id: publishif: ${{ !inputs.dry_run }}env:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}run: |set -euo pipefail+ exec > >(tee -a "$RUNNER_TEMP/log/publish.log") 2>&1if gh release edit "$PACK_TAG" --repo "$GITHUB_REPOSITORY" --draft=false; then+ echo "PUBLISHED_TAG=$PACK_TAG" >> "$GITHUB_ENV"echo "published $PACK_TAG"; exit 0fiRELID=$(gh api "repos/$GITHUB_REPOSITORY/releases?per_page=100" --paginate \@@ -487,6 +506,7 @@ jobs:N=$((N + 1)); NEW="$PACK_TAG-r$N"donegh api -X PATCH "repos/$GITHUB_REPOSITORY/releases/$RELID" -f tag_name="$NEW" -F draft=false+ echo "PUBLISHED_TAG=$NEW" >> "$GITHUB_ENV"echo "published $NEW"# Keep the newest 3 pins of THIS corpus (a client holding a slightly stale@@ -518,10 +538,107 @@ jobs:if: failure()run: tail -n 100 "$RUNNER_TEMP/node/node.log" || true+ # One row for the backfill report (spec §12.1), whatever happened above: the+ # first stage that failed and its most telling log line, or the published tag.+ - name: Record this corpus's result for the backfill report+ if: always()+ env:+ STEPS: ${{ toJSON(steps) }}+ JOB_STATUS: ${{ job.status }}+ DRY_RUN: ${{ inputs.dry_run }}+ run: |+ set -euo pipefail+ L="$RUNNER_TEMP/log"+ args=(result-row --slug "$SLUG" --pin8 "$PIN8" --steps "$STEPS" \+ --run-id "$GITHUB_RUN_ID" --build-out "$RUNNER_TEMP/build.txt" \+ --published-tag "${PUBLISHED_TAG:-}" --job-status "$JOB_STATUS" \+ --stage checkout --stage fetch-bin \+ --stage "start=$L/start.log,$RUNNER_TEMP/node/node.log" --stage "build=$L/build.log" \+ --stage "verify=$L/verify.log" --stage "tag=$L/tag.log" --stage "upload=$L/upload.log" \+ --stage "e2e=$L/e2e.log" --stage "publish=$L/publish.log")+ [ "$DRY_RUN" = "true" ] && args+=(--dry-run)+ mkdir -p "$RUNNER_TEMP/result"+ OUT="$RUNNER_TEMP/result/$SLUG.json"+ if ! python3 tools/hub-packs/hub_packs.py "${args[@]}" > "$OUT"; then+ # Never leave the report without this corpus: a minimal row naming the cause.+ jq -cn --arg slug "$SLUG" --arg pin8 "$PIN8" --arg run "$GITHUB_RUN_ID" \+ '{run: $run, slug: $slug, pin8: $pin8, bytes: null, defs: null, result: "failed",+ tag: "", stage: "record", error: "result-row failed; see this job's log"}' > "$OUT"+ fi+ cat "$OUT"++ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2+ if: always()+ with:+ name: hub-result-${{ matrix.slug }}+ path: ${{ runner.temp }}/result/+ overwrite: true # a re-run of this job replaces its row+ if-no-files-found: warn+ retention-days: 14+- name: Stop the builder nodeif: always()run: kill "${NODE_PID:-}" 2>/dev/null || true+ # ── the backfill report (spec §12.1): one row per corpus per run ───────────+ # Folds every pack job's result row into benchmarks/hub-backfill/ (REPORT.md and+ # the rows.jsonl behind it) and commits them to corpus-hub. A corpus the plan+ # scheduled that recorded nothing (its job never started, or was cut off) gets a+ # row saying so, so a failure never vanishes silently. A commit, not a PR: the+ # repository does not let GITHUB_TOKEN open PRs, and a push made with it starts+ # no workflow. A dry run only writes the job summary.+ report:+ name: backfill report+ needs: [plan, build-xerj, pack]+ if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.count != '0' }}+ runs-on: ubuntu-latest+ timeout-minutes: 10+ permissions:+ contents: write # commit the report to corpus-hub+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0+ with:+ persist-credentials: ${{ !inputs.dry_run }}++ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ continue-on-error: true # no row at all is still reported (below)+ with:+ pattern: hub-result-*+ merge-multiple: true+ path: ${{ runner.temp }}/rows++ - name: Write the report (and commit it on a real run)+ env:+ MATRIX: ${{ needs.plan.outputs.matrix }}+ WHY: "the pack job recorded no result (pack jobs: ${{ needs.pack.result }}, build xerj: ${{ needs.build-xerj.result }})"+ DRY_RUN: ${{ inputs.dry_run }}+ run: |+ set -euo pipefail+ printf '%s' "$MATRIX" > "$RUNNER_TEMP/plan.json"+ URL="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"+ # Scripts from this run's commit; the report itself from corpus-hub's tip.+ cp tools/hub-packs/hub_packs.py "$RUNNER_TEMP/hub_packs.py"+ args=(report --rows-dir "$RUNNER_TEMP/rows" --matrix "$RUNNER_TEMP/plan.json" \+ --run-id "$GITHUB_RUN_ID" --run-url "$URL" --missing-reason "$WHY")+ python3 "$RUNNER_TEMP/hub_packs.py" "${args[@]}" >> "$GITHUB_STEP_SUMMARY"+ if [ "$DRY_RUN" = "true" ]; then+ echo "dry run: the report is in the job summary only"; exit 0+ fi+ git config user.name xerj-org+ git config user.email [email protected]+ for attempt in 1 2 3 4 5; do+ git fetch -q --depth=1 origin corpus-hub || { sleep $((attempt * 5)); continue; }+ git checkout -q -B corpus-hub origin/corpus-hub+ python3 "$RUNNER_TEMP/hub_packs.py" "${args[@]}" --write > /dev/null+ git add benchmarks/hub-backfill/REPORT.md benchmarks/hub-backfill/rows.jsonl+ if git diff --cached --quiet; then echo "report unchanged"; exit 0; fi+ git commit -q -m "hub backfill report: run $GITHUB_RUN_ID" -m "$URL"+ if git push -q origin corpus-hub; then echo "report committed to corpus-hub"; exit 0; fi+ sleep $((attempt * 5))+ done+ echo "::error title=backfill report::could not push the report to corpus-hub; the rows are in this job's summary"+ exit 1+# ── rebuild, check, sign and (opt-in) deploy the catalogue ─────────────────catalogue:name: cataloguediff --git a/tools/hub-packs/hub_packs.py b/tools/hub-packs/hub_packs.pyindex 17f46285d..451168052 100644--- a/tools/hub-packs/hub_packs.py+++ b/tools/hub-packs/hub_packs.py@@ -4,7 +4,7 @@Drives `.github/workflows/hub-packs.yml` (plan §8, docs/CORPUS_HUB_V2_IMPLEMENTATION.md).Stdlib only, so the workflow needs no `pip install` and the tests run anywhere.-Two jobs, both pure functions over the registry first and thin I/O second:+Three jobs, all pure functions over the registry first and thin I/O second:plan Which live corpora need a pack built? A corpus is DUE when no publishedrelease `pack-<slug>-<pin8>` exists for its current pin (pin8 = the first@@ -18,6 +18,10 @@ Two jobs, both pure functions over the registry first and thin I/O second:PULL REQUEST that moves the pin. A human merges; the packs follow onmerge (the `plan` above sees the new, unreleased pin).+ report One row per corpus per run (`result-row` in each pack job, `report` at the+ end): REPORT.md + rows.jsonl under benchmarks/hub-backfill/ on corpus-hub,+ so a corpus whose build failed is listed with its error (spec §12.1).+Registry facts this relies on (tools/xerj-code/hub/):* `<slug>.json` is `{"corpus": slug, "cloned_at": ..., "repos": [{"repo", "url","sha", "review": {...}, ...}]}`; the catalogue pin is `repos[0].sha`.@@ -616,6 +620,195 @@ def check_catalogue(return errors+# ── backfill report: one row per corpus per run (spec §12.1) ────────────────+#+# Every pack job records what happened to its corpus (`result-row`), success or+# not; the `report` job folds those rows into benchmarks/hub-backfill/ on+# corpus-hub. A corpus the plan scheduled but which left no row (its job never+# started, was cancelled before recording, or the binary build failed) still gets+# a row saying so: a failed corpus must never vanish silently.++REPORT_ERROR_MAX = 240+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")+_ERRORISH_RE = re.compile(r"error|fail|panic|refus|cannot|denied|timed? ?out", re.I)+# "0 errors", "failed=0", "no failures": error words that report success.+_NOT_ERROR_RE = re.compile(r"\b(?:0|no|zero) (?:errors?|failures?)\b|\b(?:errors?|failed|failures?)[=:] ?0\b", re.I)+# The report is committed: GitHub masks secrets in its own log, not in these lines.+_SECRETISH_RE = re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|\b[0-9a-fA-F]{64}\b")+REPORT_RUNS_SHOWN = 30+++def _log_tail_error(paths: Iterable[pathlib.Path]) -> str:+ """The most telling line of a failed stage's log: the last `::error` annotation,+ else the last line that looks like an error, else the last non-empty line."""+ lines: list[tuple[bool, str]] = []+ for p in paths:+ try:+ text = p.read_text(errors="replace")+ except OSError:+ continue+ for ln in text.splitlines():+ ln = _ANSI_RE.sub("", ln).strip()+ annotated = ln.startswith("::error")+ ln = re.sub(r"^::(?:error|warning|notice)[^:]*::", "", ln).strip()+ if ln:+ lines.append((annotated, ln))+ if not lines:+ return ""+ def errorish(ln: str) -> bool:+ return bool(_ERRORISH_RE.search(ln)) and not _NOT_ERROR_RE.search(ln)++ chosen = lines[-1][1]+ for pick in (lambda a, ln: a, lambda a, ln: errorish(ln)):+ hit = next((ln for a, ln in reversed(lines) if pick(a, ln)), None)+ if hit is not None:+ chosen = hit+ break+ return _SECRETISH_RE.sub("[redacted]", chosen)+++def result_row(+ slug: str,+ pin8: str,+ steps: dict,+ stages: list[tuple[str, list[pathlib.Path]]],+ build_out: Optional[pathlib.Path],+ published_tag: str,+ dry_run: bool,+ run_id: str,+ date: str,+ job_status: str = "",+) -> dict:+ """What happened to one corpus in one run. `steps` is the job's+ `toJSON(steps)`; `stages` names the step ids in order with the log files that+ explain each one's failure."""+ row = {+ "run": str(run_id), "date": date, "slug": slug, "pin8": pin8,+ "bytes": None, "defs": None, "result": "", "tag": "", "stage": "", "error": "",+ }+ if build_out is not None:+ try:+ for ln in reversed(build_out.read_text(errors="replace").splitlines()):+ f = ln.split()+ if len(f) == 6 and f[0] == "pack" and f[1] == slug:+ row["bytes"], row["defs"] = int(f[3]), int(f[5])+ break+ except (OSError, ValueError):+ pass+ for sid, logs in stages:+ outcome = (steps.get(sid) or {}).get("outcome")+ if outcome in ("failure", "cancelled"):+ row["result"] = "failed" if outcome == "failure" else "cancelled"+ row["stage"] = sid+ row["error"] = _log_tail_error(logs)[:REPORT_ERROR_MAX]+ return row+ ran = [sid for sid, _ in stages if (steps.get(sid) or {}).get("outcome") == "success"]+ if not ran and job_status and job_status != "success":+ # Nothing tracked ran: the job failed or was cancelled before the first stage.+ row["result"] = "failed" if job_status == "failure" else "cancelled"+ row["stage"] = "before start"+ row["error"] = f"the job was {job_status} before its first tracked stage"+ return row+ if dry_run:+ row["result"] = "dry-run ok" if ran else "no result"+ elif published_tag:+ row["result"], row["tag"] = "published", published_tag+ else:+ # Every recorded stage passed or was skipped, yet nothing was published.+ row["result"] = "no result"+ row["error"] = "no stage failed, but no release was published"+ return row+++def missing_rows(planned: list[dict], rows: list[dict], run_id: str, date: str, why: str) -> list[dict]:+ """A row for every planned corpus that recorded nothing."""+ seen = {r.get("slug") for r in rows}+ return [+ {+ "run": str(run_id), "date": date, "slug": m["slug"], "pin8": m["pin8"],+ "bytes": None, "defs": None, "result": "no result", "tag": "", "stage": "",+ "error": why,+ }+ for m in planned+ if m["slug"] not in seen+ ]+++def _cell(v) -> str:+ if v is None or v == "":+ return ""+ s = re.sub(r"\s+", " ", str(v)).strip()+ return s.replace("\\", "\\\\").replace("|", "\\|")+++def _row_table(rows: list[dict]) -> list[str]:+ out = ["| slug | pin8 | bytes | defs | result | error |", "|---|---|---:|---:|---|---|"]+ for r in sorted(rows, key=lambda r: (r.get("result") == "published", r.get("slug", ""))):+ result = r.get("result", "")+ if r.get("tag"):+ result += f" `{r['tag']}`"+ if r.get("stage"):+ result += f" at `{r['stage']}`"+ out.append(+ f"| `{_cell(r.get('slug'))}` | `{_cell(r.get('pin8'))}` | {_cell(r.get('bytes'))} "+ f"| {_cell(r.get('defs'))} | {_cell(result)} | {_cell(r.get('error'))} |"+ )+ return out+++def render_report(history: list[dict], run_urls: Optional[dict] = None) -> str:+ """REPORT.md from every row so far: the corpora whose latest attempt did not+ publish first, then each run's rows, newest run first."""+ run_urls = run_urls or {}+ latest: dict[str, dict] = {}+ runs: dict[str, list[dict]] = {}+ order: list[str] = []+ for r in history:+ latest[r["slug"]] = r+ if r["run"] not in runs:+ runs[r["run"]] = []+ order.append(r["run"])+ runs[r["run"]].append(r)+ bad = [r for r in latest.values() if r.get("result") != "published"]+ ok = len(latest) - len(bad)+ out = [+ "# Hub backfill report",+ "",+ "Written by `.github/workflows/hub-packs.yml` (the `backfill report` job) after every",+ "publishing run; do not edit by hand. One row per corpus per run; the rows behind it",+ "are in `rows.jsonl`. Spec: docs/CORPUS_HUB_V2_IMPLEMENTATION.md §12.1.",+ "",+ "## Current state",+ "",+ f"{len(latest)} corpora attempted: {ok} published at their latest attempt, {len(bad)} not.",+ "",+ ]+ if bad:+ out += ["### Latest attempt did not publish (fix or delist on purpose)", ""]+ out += _row_table(bad)+ out.append("")+ shown = order[-REPORT_RUNS_SHOWN:]+ out += ["## Runs (newest first)", ""]+ if len(shown) < len(order):+ out += [f"The {len(shown)} newest of {len(order)} runs; every row is in `rows.jsonl`.", ""]+ for run in reversed(shown):+ rows = runs[run]+ date = rows[0].get("date", "")+ url = run_urls.get(run) or rows[0].get("url", "")+ title = f"### Run [{run}]({url})" if url else f"### Run {run}"+ n_ok = sum(1 for r in rows if r.get("result") == "published")+ out += [f"{title}, {date}: {n_ok} of {len(rows)} published", ""]+ out += _row_table(rows)+ out.append("")+ return "\n".join(out)+++def read_rows(path: pathlib.Path) -> list[dict]:+ if not path.is_file():+ return []+ return [json.loads(ln) for ln in path.read_text().splitlines() if ln.strip()]++# ── command line ────────────────────────────────────────────────────────────@@ -709,6 +902,53 @@ def cmd_repin(a: argparse.Namespace) -> int:return 1 if failures else 0+def cmd_result_row(a: argparse.Namespace) -> int:+ stages = []+ for spec in a.stage:+ sid, _, files = spec.partition("=")+ stages.append((sid, [pathlib.Path(f) for f in _split(files)]))+ steps = json.loads(a.steps or "{}")+ row = result_row(+ a.slug, a.pin8, steps, stages,+ pathlib.Path(a.build_out) if a.build_out else None,+ a.published_tag, a.dry_run, a.run_id, a.date or _today(), a.job_status,+ )+ print(json.dumps(row, separators=(",", ":")))+ return 0+++def cmd_report(a: argparse.Namespace) -> int:+ planned = json.loads(pathlib.Path(a.matrix).read_text()).get("include", []) if a.matrix else []+ date = a.date or _today()+ rows: list[dict] = []+ if a.rows_dir and pathlib.Path(a.rows_dir).is_dir():+ for f in sorted(pathlib.Path(a.rows_dir).glob("*.json")):+ try:+ r = json.loads(f.read_text())+ except json.JSONDecodeError:+ print(f"::warning::{f.name}: unreadable result row", file=sys.stderr)+ continue+ if isinstance(r, dict) and r.get("slug"):+ rows.append(r)+ rows += missing_rows(planned, rows, a.run_id, date, a.missing_reason)+ for r in rows:+ r["run"] = str(a.run_id)+ r.setdefault("date", date)+ if a.run_url:+ r["url"] = a.run_url+ history_path = pathlib.Path(a.history)+ history = [r for r in read_rows(history_path) if r.get("run") != str(a.run_id)] + rows+ if a.write:+ history_path.parent.mkdir(parents=True, exist_ok=True)+ history_path.write_text("".join(json.dumps(r, separators=(",", ":")) + "\n" for r in history))+ pathlib.Path(a.report).write_text(render_report(history))+ bad = [r for r in rows if r.get("result") != "published"]+ print(f"### backfill report: run {a.run_id}\n")+ print(f"{len(rows) - len(bad)} of {len(rows)} corpora published in this run.\n")+ print("\n".join(_row_table(rows)))+ return 0++def main(argv: Optional[list[str]] = None) -> int:ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])sub = ap.add_subparsers(dest="cmd", required=True)@@ -753,6 +993,31 @@ def main(argv: Optional[list[str]] = None) -> int:r.add_argument("--allow-file-urls", action="store_true", help=argparse.SUPPRESS)r.set_defaults(fn=cmd_repin)+ rr = sub.add_parser("result-row", help="one corpus's result in this run, as a JSON row")+ rr.add_argument("--slug", required=True)+ rr.add_argument("--pin8", required=True)+ rr.add_argument("--steps", default="{}", help="the job's toJSON(steps)")+ rr.add_argument("--stage", action="append", default=[], help="step id=log,log (in order)")+ rr.add_argument("--build-out", help="build-pack's stdout (its last line carries bytes and defs)")+ rr.add_argument("--published-tag", default="")+ rr.add_argument("--dry-run", action="store_true")+ rr.add_argument("--run-id", required=True)+ rr.add_argument("--date", default="")+ rr.add_argument("--job-status", default="", help="the job's job.status")+ rr.set_defaults(fn=cmd_result_row)++ rp = sub.add_parser("report", help="fold this run's result rows into the backfill report")+ rp.add_argument("--rows-dir", help="directory of result-row JSON files")+ rp.add_argument("--matrix", help="the plan's JSON (its `include` is every scheduled corpus)")+ rp.add_argument("--missing-reason", default="the pack job recorded no result")+ rp.add_argument("--run-id", required=True)+ rp.add_argument("--run-url", default="")+ rp.add_argument("--date", default="")+ rp.add_argument("--history", default="benchmarks/hub-backfill/rows.jsonl")+ rp.add_argument("--report", default="benchmarks/hub-backfill/REPORT.md")+ rp.add_argument("--write", action="store_true", help="update the history and REPORT.md (default: print only)")+ rp.set_defaults(fn=cmd_report)+a = ap.parse_args(argv)return a.fn(a)diff --git a/tools/hub-packs/test_hub_packs.py b/tools/hub-packs/test_hub_packs.pyindex d40a072fa..4c83ba81b 100644--- a/tools/hub-packs/test_hub_packs.py+++ b/tools/hub-packs/test_hub_packs.py@@ -11,6 +11,8 @@ allowlist is widened, on purpose), and `gh` is a stub that records its calls.from __future__ import annotations+import contextlib+import ioimport jsonimport osimport pathlib@@ -632,6 +634,118 @@ class CatalogueTests(unittest.TestCase):self.assertIn("1 of 2 live corpora", out.stderr)+class ReportTests(unittest.TestCase):+ STAGES = ["start", "build", "verify", "tag", "upload", "e2e", "publish"]++ def steps(self, **outcomes) -> dict:+ return {sid: {"outcome": outcomes.get(sid, "success")} for sid in self.STAGES}++ def stages(self, logs: dict) -> list:+ return [(sid, [logs[sid]] if sid in logs else []) for sid in self.STAGES]++ def test_a_published_pack_records_bytes_defs_and_its_tag(self):+ with tempfile.TemporaryDirectory() as t:+ out = pathlib.Path(t) / "build.txt"+ out.write_text("cloning...\npack lz4 aaaaaaaa 1234 3 56\n")+ r = hp.result_row("lz4", "aaaaaaaa", self.steps(), self.stages({}), out,+ "pack-lz4-aaaaaaaa", False, "77", "2026-10-16")+ self.assertEqual((r["result"], r["tag"], r["bytes"], r["defs"]),+ ("published", "pack-lz4-aaaaaaaa", 1234, 56))++ def test_a_failed_stage_names_itself_and_its_most_telling_log_line(self):+ with tempfile.TemporaryDirectory() as t:+ log = pathlib.Path(t) / "e2e.log"+ log.write_text("pulling\n\x1b[31m::error::def LZ4_x not answered from the local pack\x1b[0m\ncleanup\n")+ r = hp.result_row("lz4", "aaaaaaaa", self.steps(e2e="failure", publish="skipped"),+ self.stages({"e2e": log}), None, "", False, "77", "2026-10-16")+ self.assertEqual((r["result"], r["stage"]), ("failed", "e2e"))+ self.assertEqual(r["error"], "def LZ4_x not answered from the local pack")+ self.assertIsNone(r["bytes"])++ def test_the_first_failed_stage_wins_and_a_cancelled_one_is_not_a_success(self):+ r = hp.result_row("x", "aaaaaaaa", self.steps(build="cancelled", verify="skipped"),+ self.stages({}), None, "", False, "1", "d")+ self.assertEqual((r["result"], r["stage"]), ("cancelled", "build"))++ def test_nothing_failed_but_nothing_published_is_not_reported_as_success(self):+ r = hp.result_row("x", "aaaaaaaa", self.steps(), self.stages({}), None, "", False, "1", "d")+ self.assertEqual(r["result"], "no result")+ self.assertTrue(r["error"])++ def test_a_job_that_died_before_its_first_stage_is_not_called_unexplained(self):+ steps = {sid: {"outcome": "skipped"} for sid in self.STAGES}+ r = hp.result_row("x", "aaaaaaaa", steps, self.stages({}), None, "", False, "1", "d", "failure")+ self.assertEqual((r["result"], r["stage"]), ("failed", "before start"))++ def test_the_error_line_skips_success_counts_and_redacts_secrets(self):+ with tempfile.TemporaryDirectory() as t:+ log = pathlib.Path(t) / "b.log"+ log.write_text("cannot clone https://ghp_" + "A" * 36 + "@github.com/x\nsummary: 0 errors\nexit 1\n")+ line = hp._log_tail_error([log])+ self.assertTrue(line.startswith("cannot clone"), line)+ self.assertNotIn("ghp_", line)+ self.assertIn("[redacted]", line)++ def test_the_report_shows_the_newest_runs_and_says_how_many_it_hides(self):+ hist = [{"run": str(i), "date": "d", "slug": "a", "pin8": "aaaaaaaa", "result": "published"}+ for i in range(hp.REPORT_RUNS_SHOWN + 2)]+ md = hp.render_report(hist)+ self.assertIn(f"The {hp.REPORT_RUNS_SHOWN} newest of {hp.REPORT_RUNS_SHOWN + 2} runs", md)+ self.assertNotIn("### Run 0,", md)+ self.assertIn(f"### Run {hp.REPORT_RUNS_SHOWN + 1},", md)++ def test_a_dry_run_that_passed_says_so(self):+ r = hp.result_row("x", "aaaaaaaa", self.steps(tag="skipped", upload="skipped", publish="skipped"),+ self.stages({}), None, "", True, "1", "d")+ self.assertEqual(r["result"], "dry-run ok")++ def test_a_planned_corpus_without_a_row_still_gets_one(self):+ planned = [{"slug": "a", "pin8": "11111111"}, {"slug": "b", "pin8": "22222222"}]+ rows = [{"slug": "a", "result": "published"}]+ extra = hp.missing_rows(planned, rows, "9", "d", "build xerj: failure")+ self.assertEqual([(r["slug"], r["result"], r["error"]) for r in extra],+ [("b", "no result", "build xerj: failure")])++ def test_the_report_keeps_a_failure_visible_until_a_later_run_publishes_it(self):+ def r(run, slug, result, error=""):+ return {"run": run, "date": "d", "slug": slug, "pin8": "aaaaaaaa", "bytes": None,+ "defs": None, "result": result, "tag": "", "stage": "", "error": error}+ history = [r("1", "a", "failed", "boom | pipe"), r("1", "b", "published"),+ r("2", "c", "failed", "later")]+ md = hp.render_report(history)+ self.assertIn("3 corpora attempted: 1 published at their latest attempt, 2 not.", md)+ self.assertIn("boom \\| pipe", md, "a pipe in an error must not break the table")+ self.assertLess(md.index("### Run 2"), md.index("### Run 1"), "newest run first")+ md = hp.render_report(history + [r("3", "a", "published")])+ self.assertIn("3 corpora attempted: 2 published at their latest attempt, 1 not.", md)+ self.assertIn("boom", md, "the old failing row stays in run 1's table")++ def test_report_cli_appends_this_run_and_replaces_a_rerun_of_the_same_id(self):+ with tempfile.TemporaryDirectory() as t:+ root = pathlib.Path(t)+ rows = root / "rows"; rows.mkdir()+ (rows / "a.json").write_text(json.dumps(+ {"slug": "a", "pin8": "11111111", "result": "published", "tag": "pack-a-11111111",+ "bytes": 5, "defs": 2, "stage": "", "error": "", "date": "d", "run": "x"}))+ matrix = root / "plan.json"+ matrix.write_text(json.dumps({"include": [{"slug": "a", "pin8": "11111111"},+ {"slug": "b", "pin8": "22222222"}]}))+ hist, rep = root / "out" / "rows.jsonl", root / "out" / "REPORT.md"+ args = ["report", "--rows-dir", str(rows), "--matrix", str(matrix), "--run-id", "5",+ "--run-url", "https://x.test/runs/5", "--history", str(hist), "--report", str(rep),+ "--missing-reason", "pack: cancelled", "--write"]+ with contextlib.redirect_stdout(io.StringIO()) as out:+ self.assertEqual(hp.main(args), 0)+ self.assertEqual(hp.main(args), 0) # a re-run of the report job must not duplicate rows+ self.assertIn("1 of 2 corpora published in this run.", out.getvalue())+ got = hp.read_rows(hist)+ self.assertEqual([(r["slug"], r["result"], r["run"]) for r in got],+ [("a", "published", "5"), ("b", "no result", "5")])+ md = rep.read_text()+ self.assertIn("### Run [5](https://x.test/runs/5), d", md.replace(hp._today(), "d"))+ self.assertIn("| `b` | `22222222` | | | no result | pack: cancelled |", md)++class CommandLineTests(unittest.TestCase):def run_cli(self, *argv: str) -> tuple[int, str, str]:out = subprocess.run(