Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat: harden behavioral learning lifecycle

Rach Pradhanab7b5a5c2bb5
diff --git a/docs/hyperagents.md b/docs/hyperagents.md
index de090589..6df81372 100644
--- a/docs/hyperagents.md
+++ b/docs/hyperagents.md
@@ -274,7 +274,9 @@ Exact-answer checks deliberately reject substring false positives such as
`1391` for an expected answer of `391`. The separate
`examples/dgm_canary_eval_set.jsonl` supplies unseen boundary variants for a
final generalization check. The judge is dependency-free (speaks the
-`harness --json` protocol directly) so its pinned copy runs anywhere.
+`harness --json` protocol directly) so its pinned copy runs anywhere. Candidate
+genomes are installed through the stdin control protocol rather than command
+arguments, keeping full prompt text out of ordinary process listings.
**Custody (same model as the score key).** `--pin` installs the eval set
and the judge itself under `~/.simple-harness/evals/` — outside the
@@ -471,7 +473,10 @@ signed fields and can emit prompt-free `fleet:propose`/`fleet:submit` in
aggregate-or-higher mode. The generated SDKs have no interactive artifact
review UI, so their final emitter strips `prompt_text` even in template mode.
`pullElites(providerClass)` / `pull_elites(...)` is gated by the same learning
-mode. A future SDK content API needs an explicit preview/consent primitive.
+mode and the per-instance telemetry/fleet controls. Raw error detail is never
+serialized; event kinds and provider classes are allowlisted, while unexpected
+free-form labels are reduced to bounded fingerprints. A future SDK content API
+needs an explicit preview/consent primitive.
### Scaffolded vs TODO
diff --git a/docs/learning-privacy.md b/docs/learning-privacy.md
index 3b261c30..53ebb9d7 100644
--- a/docs/learning-privacy.md
+++ b/docs/learning-privacy.md
@@ -41,6 +41,40 @@ case-varied values fail closed to `local`.
telemetry still follows `--no-telemetry` / `GRAFF_NO_TELEMETRY` and the
behavioral upload controls documented separately.
+Generated TypeScript and Python clients resolve these controls per harness
+instance rather than mutating process-global environment state. A local/off
+instance cannot be made network-active by a different aggregate instance in the
+same process.
+
+### SDK startup prompts
+
+The local Python `system_prompt` / `append_system_prompt` and TypeScript
+`systemPrompt` / `appendSystemPrompt` options are not placed in subprocess argv.
+The SDK starts a versioned stdin-bootstrap mode, sends both values in one bounded
+JSON frame, validates a prompt-free UTF-8 byte-count acknowledgement, and only
+then permits the first user turn. Graff composes that frame at the original
+startup boundary, preserving the normal replacement → project instructions →
+append → skills/MCP ordering and the initial behavioral prompt fingerprint.
+Bootstrap failure closes and reaps the child. Raw SDK `args` remain explicitly
+caller-controlled; manually supplying CLI prompt flags there can expose them to
+same-user process inspection.
+
+Remote SDK creation sends the same fields in the authenticated HTTP request.
+`graff serve` now forwards them to its session child with that stdin bootstrap
+before publishing the session ID; it never rebuilds prompt-bearing child argv.
+Use HTTPS outside loopback and configure reverse proxies not to log request
+bodies—the bridge necessarily handles the plaintext in memory to construct the
+model request. Serve-level prompt defaults supplied manually as CLI flags remain
+visible in the server parent argv, like any explicit raw CLI prompt flag.
+Remote SDK exceptions report only HTTP status and path; arbitrary response bodies
+are discarded so a reflecting proxy cannot copy a prompt into application logs.
+
+Each local SDK serializes non-answer operations, and the HTTP bridge independently
+serializes them per session. `answer` is the deliberate exception so it can
+resolve an in-flight `ask_user`. If a local event iterator is abandoned early,
+the client drains that turn while retaining the operation gate, preventing its
+remaining events from being mistaken for a later request.
+
## Template consent
`templates` is a ceiling, not blanket content consent. Before a private inline,
@@ -66,17 +100,30 @@ content.
## Final egress boundary
All score and fleet call sites converge in `Telemetry.scoreEvent` and
-`Telemetry.fleetEvent`. Those functions enforce the current mode again.
-Template text is admitted only when its exact SHA-256 digest is on the
-session-local approval list and a second secret scan passes.
+`Telemetry.fleetEvent`. Those functions enforce the current mode again, and
+serialization rechecks the live privacy ceiling and fleet kill switch before a
+buffered event leaves the process. Template text is admitted only when its exact
+SHA-256 digest is on the session-local approval list and a second secret scan
+passes.
This double check means a missed condition at an individual mutation,
evaluation, subagent, or workflow call site cannot silently attach content.
Raw task prompts, template bindings, user messages, code, paths, child reports,
tool arguments/results, and local traces have no field in the fleet contract.
+Raw provider/tool error details are dropped rather than redacted. Event kinds
+and provider classes are allowlisted; custom niches and unexpected identifiers
+are projected to bounded fingerprints before egress. SDK fleet emitters always
+strip prompt text because they do not have an interactive review surface.
The future `examples` path must use a separate endpoint, preview hash, consent
-receipt, short retention, and deletion API before it can be enabled.
+receipt, short retention, and deletion API before it can be enabled. Aggregate
+receipts have a fixed 30-day backend retention window; the receipt status
+reports its expiry. This does not delete the local immutable evidence store.
+Users can delete a receipt sooner with `graff learn delete-remote RUN_ID`.
+The deletion token is scoped to one run, derived from that run's private nonce,
+and is neither returned by receipt lookup nor stored in plaintext. The backend
+keeps only a one-way run tombstone after deletion to reject queued or replayed
+copies; it contains no prompt, task, path, metric, or stable installation ID.
## Hashes are not anonymity
@@ -107,6 +154,13 @@ graff --learning-privacy aggregate learn submit RUN_ID
graff --learning-privacy aggregate learn run --submit
```
+Deletion is a revocation operation, not new telemetry, so it is allowed under
+Local mode and the fleet/telemetry kill switches:
+
+```sh
+graff learn delete-remote RUN_ID
+```
+
The root `learn_candidate` tool is a deliberate one-shot exception: it bundles
local evaluation, grading, and aggregate submission. In Local mode the root
shows the exact aggregate categories and requires a separate confirmation;
@@ -114,12 +168,41 @@ shows the exact aggregate categories and requires a separate confirmation;
The permit is consumed once without changing the session mode. The tool cannot
publish prompt text or promote a candidate automatically.
+The signed receipt contains fixed aggregate fields only: parent/child pass
+counts and deltas, statistical-unit counts and significance, critical and
+ordinary regression counts, measured tool/cost/latency totals, fixed gate
+settings (including economy-gate enablement), eligibility/reason codes, short
+prompt lineage fingerprints, and content-addressed run/suite/cohort/evidence
+identifiers. A second signature
+binds those metrics so the backend rejects tampering that the legacy score
+signature alone could not detect. It has no field for prompts, tasks, code,
+paths, adapter output, evaluator payloads, errors, or traces.
+Explicit learning submissions also omit the stable installation identifier,
+OS, architecture, and service version. The collector discards installation
+identifiers sent by older learning clients, and receipt lookups are marked
+`private, no-store` so capability URLs are not retained by caches.
+
+Adapter failure diagnostics follow the same boundary. Direct learning commands
+show only the adapter operation and termination status by default; raw stderr
+and executable paths require the local-only
+`graff learn run --show-adapter-stderr` opt-in. The model-facing
+`learn_candidate` tool discards all nested-process stderr even on failure.
+
## Regression contract
Tests assert that:
- local mode creates no score or fleet record;
+- lowering privacy or disabling fleet drops already buffered learning events;
- aggregate mode records grades and fleet metadata without prompt text;
+- SDK instance overrides, `--no-telemetry`, and `GRAFF_FLEET=off` prevent
+ network calls without leaking raw error or free-form metadata;
+- structured SDK startup prompts stay out of argv, finish before the first user
+ turn, validate UTF-8 byte counts, and reap the child on bootstrap failure;
+- remote session prompts also stay out of the server child argv, and concurrent
+ non-answer operations cannot steal one another's events;
+- adapter stderr canaries stay hidden by default and never enter model-facing
+ `learn_candidate` results;
- template mode still omits unapproved text;
- approval applies only to the exact template version;
- planted API keys, tokens, authorization headers, and private-key markers
diff --git a/docs/local-learning.md b/docs/local-learning.md
index c17263d8..c85b0f40 100644
--- a/docs/local-learning.md
+++ b/docs/local-learning.md
@@ -34,7 +34,7 @@ protocols.
```text
graff learn init --parent PATH --config PATH
-graff learn run [--candidates N] [--repetitions N] [--auto] [--lock-timeout-ms N]
+graff learn run [--candidates N] [--repetitions N] [--resume | --restart] [--auto] [--show-adapter-stderr] [--lock-timeout-ms N]
graff --learning-privacy aggregate learn run [--candidates N] [--repetitions N] --submit
graff --learning-privacy aggregate learn submit RUN_ID [--lock-timeout-ms N]
graff learn status [--lock-timeout-ms N]
@@ -63,6 +63,30 @@ graff learn rollback
Only one learning operation runs at a time. `--lock-timeout-ms` controls how
long a command waits for the local engine lock, up to 600,000 ms.
+Expensive tournament progress is atomically checkpointed after mutation, the
+shared parent baseline, every completed primary arm, and holdout completion. If
+an adapter fails or the process exits, rerun with `learn run --resume` using the
+same candidate/repetition/automatic-promotion options. Resume re-derives the
+trial ID and re-verifies every referenced immutable genome and evidence object
+before skipping completed work. A normal `learn run` refuses to overwrite a
+recoverable checkpoint. `--restart` explicitly discards it and starts a new
+trial; it does not unconsume a hidden suite that was already exposed.
+`learn status` reports the pending trial ID plus completed primary and holdout
+arm counts without exposing prompts, cases, or adapter output. `learn verify`
+also re-verifies any pending checkpoint and reports `pending_verified: true`;
+ordinary status leaves a present checkpoint explicitly unverified.
+For a new trial, a previously consumed holdout is detected before any mutator
+or evaluator process starts; only an exact checkpoint resume may reuse its own
+reservation.
+
+Each mutation arm gets one bounded retry after a timeout or nonzero exit. The
+retry keeps the registered candidate index and seed but uses a new private
+scratch directory, so partial files from the failed process are never reused.
+Adapter stderr and executable paths are hidden by default because failures may
+contain prompts, repository text, credentials, or usernames. A human debugging
+in a local terminal can explicitly add `--show-adapter-stderr`; the
+model-facing `learn_candidate` action never exposes nested-process stderr.
+
`run --submit` performs mutation, paired primary/holdout grading, immutable
storage, and aggregate publication in one command. `submit RUN_ID` re-verifies
and retries an already stored run. Both use `GRAFF_SCORE_KEY_FILE`, falling back
@@ -71,28 +95,44 @@ A retry is idempotent at the collector.
Neither form promotes the selected candidate; use the separate manual or
two-key automatic promotion policy described above.
+`delete-remote RUN_ID` removes that run's aggregate backend receipt without
+touching local genomes, evidence, or history. Its bearer capability is derived
+from the immutable run nonce and the score key; the nonce stays local and the
+collector stores only a verifier. Deletion remains available when
+`GRAFF_NO_TELEMETRY=1`, `GRAFF_FLEET=off`, or learning privacy is Local, so
+revoking consent never prevents removing data that was already submitted.
+
For multiple candidates, execution is a barriered tournament:
1. every mutation arm runs concurrently;
2. every unique arm runs the same primary suite concurrently with common pair
seeds and one fixed evaluator cohort;
-3. ranking minimizes critical regressions, then maximizes observed correctness,
- then minimizes measured tool calls, latency, cost, and prompt size;
+3. ranking minimizes child critical failures and critical regressions, then
+ maximizes observed child correctness, then minimizes measured tool calls,
+ cost, and prompt size;
4. only that primary winner is evaluated on the holdout; and
5. promotion remains a separate manual action unless the configured two-key
automatic policy is explicitly enabled and all statistical gates pass.
-Run records use `codegraff.learn.run.v2` and persist the primary winner even
-when evidence is underpowered. Missing tool-call instrumentation is recorded as
-unknown and cannot masquerade as zero calls. `GRAFF_NO_TELEMETRY=1` and
-`GRAFF_FLEET=off` both block explicit aggregate submission.
+Run records use `codegraff.learn.run.v3`, which stores one verified primary
+parent baseline shared by all candidate arms, and persist the primary winner
+even when evidence is underpowered. Missing tool-call instrumentation is
+recorded as unknown and cannot masquerade as zero calls. Latency remains in the
+report but is deliberately excluded from ranking and promotion evidence.
+`GRAFF_NO_TELEMETRY=1` and `GRAFF_FLEET=off` both block explicit aggregate
+submission; they deliberately do not block `delete-remote`.
The bundled model-backed example adapters fail safely around transient or
malformed model output. A mutation gets one corrective turn after deterministic
size/invariant validation; a second failure becomes an unchanged-parent
non-contender rather than aborting other arms. An evaluation turn that ends
without gradeable evidence gets one bounded retry in a newly initialized task
-directory, so partial file changes cannot leak into the retry.
+directory, so partial file changes cannot leak into the retry. Each evaluator
+side also keeps a request-bound, prompt-free attempt journal in private scratch.
+It durably records observed latency, tool calls, and cost, plus a completed side
+result. After an evaluator crash, the retry restores that usage and does not
+repeat a completed side. The journal is cleared only after paired progress is
+durably committed.
The root model also receives an approval-gated `learn_candidate` tool when it
runs in a configured workspace. The tool bundles `run --submit` into one
@@ -215,7 +255,8 @@ A suite is pinned JSON:
"schema": "codegraff.learn.suite.v1",
"suite_id": "review-v1",
"cases": [
- {"id": "case-001", "critical": true, "payload": {"fixture": "..."}},
+ {"id": "case-001a", "statistical_unit_id": "scenario-001", "critical": true, "payload": {"fixture": "..."}},
+ {"id": "case-001b", "statistical_unit_id": "scenario-001", "critical": true, "payload": {"fixture": "..."}},
{"id": "case-002", "payload": null}
]
}
@@ -225,13 +266,27 @@ Case IDs must be unique. The evaluator receives a verified private copy as
`suite.json`; the evaluation request never directs it back to the configured
suite pathname.
-`default_repetitions` controls repeated measurements of each case. Repetitions
-are **not** independent statistical samples. For the exact one-sided paired
-sign test, all repetitions of one case are collapsed into one unit by comparing
-aggregate parent and child pass counts for that case. Therefore:
+A configured holdout must have a different content digest and `suite_id`, and
+its declared statistical-unit IDs must be disjoint from the primary suite.
+Initialization and every later verification boundary enforce this before the
+hidden suite is exposed. These checks prevent accidental reuse; authors must
+still ensure differently named units are semantically independent.
-- `minimum_pairs` means the minimum number of distinct suite cases.
-- Repeating one case cannot satisfy the minimum or manufacture significance.
+`default_repetitions` controls repeated measurements of each case. Repetitions
+and semantically cloned cases are **not** independent statistical samples. Set
+the optional `statistical_unit_id` to the same value for related cases. Suites
+that omit it remain compatible: the case ID becomes the effective unit ID. For
+the exact one-sided paired sign test, all rows in one effective unit are
+collapsed by comparing aggregate parent and child results. Therefore:
+
+- `minimum_pairs` means the minimum number of independent statistical units.
+- Repeating or cloning one scenario cannot satisfy the minimum or manufacture
+ significance.
+- Initialization rejects an underpowered primary or holdout suite before any
+ adapter/model call. A trial also rechecks that even an all-win result could
+ clear the exact p-value after correction for its actual candidate count;
+ otherwise it fails with `InsufficientSignificancePower`. Stored requests bind
+ every pair to its effective unit.
- Any parent-pass/child-fail result on a critical case is a hard rejection.
- Pass-rate and mean-score deltas still use all repeated measurements.
- The significance threshold is Bonferroni-corrected by the number of planned
@@ -240,13 +295,14 @@ aggregate parent and child pass counts for that case. Therefore:
`promotion_mode` preregisters either `correctness` or `economy`; primary and
holdout cannot clear different endpoints. Economy mode also requires
-`economy_gate_enabled`, zero case-level correctness losses, no mean-score
+`economy_gate_enabled`, zero raw parent-pass/child-fail rows, no mean-score
regression, measured calls, the configured aggregate call reduction, and a
separately Bonferroni-corrected per-case tool-call sign test.
-`minimum_economy_pairs` counts only discordant cases (wins plus losses), since
-tool-call ties provide no information to that sign test.
-Latency is reported and used only as a ranking tie-breaker; it is not promotion
-evidence because wall-clock measurements are comparatively noisy.
+`minimum_economy_pairs` counts only discordant statistical units (wins plus
+losses), since tool-call ties provide no information to that sign test. The
+suite must contain at least that many possible units before evaluation starts.
+Latency is reported but is neither a ranking tie-breaker nor promotion evidence
+because wall-clock measurements are comparatively noisy.
After each run, the CLI prints a prompt-free aggregate summary for every
candidate: parent and child pass counts, effect size, paired wins/losses/ties,
@@ -267,9 +323,12 @@ Programs are invoked directly, never through a generated shell command:
The child working directory is the private scratch directory. `HOME` and temp
variables point inside it; the environment is replaced with a small baseline
plus explicitly listed `pass_env` values. Standard output/error, response size,
-and direct-child execution time are bounded. These limits are not OS resource
-isolation: they do not cap CPU, memory, process count, or reliably terminate
-descendants started by an adapter.
+and execution time are bounded. Learning adapters run in an owned POSIX process
+group or Windows Job Object, so ordinary descendants are terminated on timeout,
+orchestrator error, and parent exit. This is process-lifecycle containment, not
+OS resource isolation: it does not cap CPU, memory, or process count, prevent a
+process from deliberately escaping the owned tree, or revoke remote provider
+work that was already accepted.
### Mutation
@@ -305,16 +364,20 @@ The mutator writes `child.genome` and responds with
The engine rejects the response unless `child_sha256` matches the exact bytes it
stores as the candidate genome. Promotion rechecks that binding from immutable
-evidence.
+evidence. `description` is retained only in that local evidence for debugging;
+because it is adapter-controlled and may contain sensitive or adversarial text,
+aggregate summaries and the model-facing `learn_candidate` result never render
+it.
### Paired evaluation
The request uses `codegraff.learn.evaluation.request.v1` and includes the trial,
candidate, exact cohort ID, suite hash, `suite_path: "suite.json"`, parent and
-child IDs/relative files, repetition count, and ordered pairs:
+child IDs/relative files, repetition count, and ordered pairs. The optional
+statistical-unit field is omitted for legacy one-case-per-unit suites:
```json
-{"case_id": "case-001", "seed": "<deterministic id>", "critical": true}
+{"case_id": "case-001a", "statistical_unit_id": "scenario-001", "seed": "<deterministic id>", "critical": true}
```
The response uses `codegraff.learn.evaluation.response.v1`, repeats the envelope
@@ -335,6 +398,13 @@ IDs, and returns exactly one ordered result per requested pair:
}
```
+The pair seed is a deterministic evidence identity shared across arms. An
+adapter backed by a seed-capable model API may also use it to control sampling.
+The bundled Codex Responses evaluator cannot: the Responses API has no sampling
+seed parameter, so it uses the value for parent/child order counterbalancing and
+treats model generations as stochastic repetitions. Those repetitions remain
+inside their case's statistical unit and never increase independent power.
+
Costs and latencies are optional and default to zero. The Zig engine validates
the envelope, ordering, bounds, deterministic seeds, trial derivation, and every
stored aggregate again before promotion. The trial identifier binds the pinned
@@ -355,6 +425,7 @@ evidence/ immutable adapter requests/responses
runs/ immutable verified run records
transactions/ immutable activation history
refs/active.json mutable atomic active ref
+refs/pending.json mutable atomic in-flight tournament checkpoint
locks/engine.lock
tmp/ per-invocation private scratch
```
@@ -366,6 +437,14 @@ promotion writes and synchronizes the transaction first, then atomically
replaces `refs/active.json` and synchronizes its directory; synchronization
errors fail the command.
+The pending ref is recovery state, not promotion authority. It contains only
+lineage, immutable object IDs, and aggregate comparisons. Resume validates the
+active parent/configuration, deterministic trial derivation, mutation evidence,
+shared baseline projection, every completed primary comparison, sole winner,
+and any holdout reservation/comparison. A holdout reservation can be reused
+only by its exact original trial, so recovery cannot switch candidates or start
+a new tournament against the same exposed suite.
+
Windows synchronizes file contents and uses atomic replacement, but the Zig I/O
API does not portably flush directory handles. Graff therefore skips the
post-rename directory flush on Windows rather than failing every operation with
@@ -396,11 +475,28 @@ requires an aggregate-or-higher learning ceiling, selected with
`--learning-privacy aggregate`, `GRAFF_LEARNING_PRIVACY=aggregate`, or
`/privacy aggregate`. The root-only `learn_candidate` tool can instead request
one explicit bundled aggregate submission without changing the session mode. An explicit `--submit` or
-`learn submit` then publishes only the existing signed score envelope:
-short parent/child fingerprints, aggregate pass rate, run/suite/cohort metadata,
-and content-addressed evidence IDs. It does not publish prompt text, tasks,
-adapter input/output, repository data, or local traces. The collector exposes a
-retry-safe receipt at `GET /v1/learning/<RUN_ID>`.
+`learn submit` publishes the existing signed score plus a separately signed
+`codegraff.learn.grade.v1` receipt: fixed aggregate pass/delta/significance,
+regression, tool/cost/latency, gate (including economy-gate enablement), and
+eligibility fields; short parent/child fingerprints; run/suite/cohort metadata;
+and content-addressed evidence IDs. It
+does not publish prompt text, tasks, adapter input/output, repository data, raw
+error details, paths, or local traces.
+It also omits the ordinary telemetry installation identifier and platform
+metadata, so separate explicit submissions cannot be linked through a stable
+client identity. The collector ignores legacy learning install identifiers.
+Buffered learning events recheck the current privacy mode and fleet kill switch
+at send time, so lowering consent suppresses already queued events. SDK clients
+apply the same policy to each harness instance, honor `--no-telemetry` and
+`GRAFF_FLEET=off`, allowlist fixed event kinds/provider classes, and fingerprint
+unexpected free-form labels before egress. The collector independently validates
+field ranges and cross-field invariants after both signatures, stores learning
+comparisons outside fleet fitness, and exposes them at the retry-safe
+`GET /v1/learning/<RUN_ID>` receipt endpoint.
+
+The bundled evaluator transfers parent and child prompts to its local Graff
+process through the JSON stdin control channel, not command-line arguments, so
+the full prompt is not exposed by ordinary process listings.
Once activated, the learned prompt is used like any other agent prompt:
@@ -434,11 +530,12 @@ python3 tests/learn_graff_adapters.py
For an explicitly consented model-backed trial,
`examples/prepare_graff_tournament.py` creates an isolated workspace, a newly
-randomized five-case holdout, and pinned four-arm configuration. The shipped
+randomized 40-case/40-unit holdout, and pinned four-arm configuration. The
+primary suite contains 60 rows representing 44 independent units. The shipped
arm map uses `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, and
`gpt-5.4-mini`; all prompts are evaluated by the same pinned cohort. The
mutator intentionally sends the parent prompt to those providers, while inner
-agent telemetry is disabled and only the five signed aggregate tournament
+agent telemetry is disabled and only prompt-free signed aggregate tournament
grades are submitted. The generated config keeps automatic promotion off.
## Collective learning: aggregate receipts, not promotion authority
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
new file mode 100644
index 00000000..ba3a1691
--- /dev/null
+++ b/docs/releases/v0.0.215.md
@@ -0,0 +1,55 @@
+# Private, correctness-first prompt-policy tournaments
+
+v0.0.215 turns the experimental local learning loop into a resumable,
+privacy-bounded tournament. It generates and evaluates competing prompt
+variants in parallel, ranks correctness before measured tool economy, and
+exposes only the primary winner to the hidden holdout.
+
+## Safer evidence and promotion
+
+- Mutation arms and primary evaluations run concurrently with shared pair
+ seeds and one verified parent baseline.
+- Ranking minimizes critical failures and regressions before considering
+ correctness, tool calls, cost, and prompt size. Latency is reported but does
+ not influence selection.
+- Expensive progress is checkpointed after each barrier and can be resumed
+ without silently repeating completed work.
+- Promotion remains a separate manual action by default. Automatic promotion
+ still requires both configuration and command-line consent, a holdout, and
+ all statistical gates.
+- Adapter programs and declared inputs are hashed, copied into private scratch,
+ and executed from the verified snapshots. Timeouts clean up descendant
+ processes as well as their parent.
+
+## Explicit, revocable aggregate sharing
+
+- \`learn run --submit\` grades and publishes one signed aggregate receipt in
+ the same operation; \`learn submit RUN_ID\` retries an existing immutable run.
+- The model-facing \`learn_candidate\` tool can request that bundled operation,
+ but cannot promote a candidate. Local mode requires a one-shot interactive
+ confirmation that \`--yolo\`, saved approvals, subagents, and noninteractive
+ runs cannot bypass.
+- Receipt payloads have no fields for prompts, tasks, code, paths, adapter
+ output, errors, or traces. Learning submissions also omit stable installation
+ identity, OS, architecture, and service version.
+- Backend receipts expire after 30 days. \`graff learn delete-remote RUN_ID\`
+ removes one earlier aggregate receipt using a run-scoped capability derived
+ locally from immutable evidence. Revocation remains available even when
+ telemetry and fleet sharing are disabled.
+- Local genomes, reports, and immutable evidence are never deleted by the
+ remote deletion command.
+
+## Validation
+
+- Complete Zig test suite and native build
+- Windows cross-build
+- End-to-end local learning and hidden-holdout tournament flows
+- Adapter retry/crash recovery and process-tree cleanup
+- Aggregate receipt signature and deletion-token cross-checks
+- Privacy efficacy suite, including an API-key canary that was absent from all
+ 8/8 captured SDK egress cases
+
+This branch intentionally requires manual promotion until the evidence is
+adequately powered.
+
+**Full changelog:** https://github.com/justrach/codegraff/compare/v0.0.214...v0.0.215
diff --git a/examples/learn_graff_evaluator.py b/examples/learn_graff_evaluator.py
index 8bc809ed..10c97a87 100755
--- a/examples/learn_graff_evaluator.py
+++ b/examples/learn_graff_evaluator.py
@@ -13,7 +13,7 @@ import sys
import tempfile
import threading
import time
-from typing import Any
+from typing import Any, Callable
REQUEST_SCHEMA = "codegraff.learn.evaluation.request.v1"
@@ -23,6 +23,9 @@ BASELINE_RESPONSE_SCHEMA = "codegraff.learn.primary-baseline.response.v1"
PRIMARY_REQUEST_SCHEMA = "codegraff.learn.primary-evaluation.request.v1"
PRIMARY_RESPONSE_SCHEMA = "codegraff.learn.primary-evaluation.response.v1"
PROGRESS_SCHEMA = "codegraff.learn.evaluator-progress.v1"
+ATTEMPT_SCHEMA = "codegraff.learn.evaluator-attempt.v1"
+METRIC_FIELDS = ("latency_ms", "tool_calls", "cost_micros")
+MAX_EXACT_INTEGER = 9_007_199_254_740_991
class EvaluationAttemptError(Exception):
@@ -83,14 +86,99 @@ def load_progress(
return request_sha256, results
-def save_progress(path: Path, request_sha256: str, results: list[dict[str, Any]]) -> None:
+def save_json_atomic(path: Path, value: Any) -> None:
temporary = path.with_name(path.name + ".tmp")
- temporary.write_text(json.dumps({
+ with temporary.open("w", encoding="utf-8") as output:
+ output.write(json.dumps(value, separators=(",", ":")) + "\n")
+ output.flush()
+ os.fsync(output.fileno())
+ temporary.replace(path)
+ if hasattr(os, "O_DIRECTORY"):
+ directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+
+
+def save_progress(path: Path, request_sha256: str, results: list[dict[str, Any]]) -> None:
+ save_json_atomic(path, {
"schema": PROGRESS_SCHEMA,
"request_sha256": request_sha256,
"results": results,
- }, separators=(",", ":")) + "\n", encoding="utf-8")
- temporary.replace(path)
+ })
+
+
+def zero_metrics() -> dict[str, int]:
+ return {field: 0 for field in METRIC_FIELDS}
+
+
+def add_metrics(left: dict[str, int], right: dict[str, int]) -> dict[str, int]:
+ return {
+ field: min(MAX_EXACT_INTEGER, max(0, left[field]) + max(0, right[field]))
+ for field in METRIC_FIELDS
+ }
+
+
+def attempt_key(
+ request_sha256: str,
+ pair: dict[str, Any],
+ label: str,
+ prompt: str,
+) -> str:
+ framed = json.dumps([
+ request_sha256,
+ pair.get("case_id"),
+ pair.get("seed"),
+ label,
+ hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
+ ], separators=(",", ":")).encode("utf-8")
+ return hashlib.sha256(b"codegraff-learn/attempt/v1\0" + framed).hexdigest()
+
+
+def load_attempt(path: Path, key: str) -> tuple[dict[str, int], dict[str, Any] | None]:
+ if not path.exists():
+ return zero_metrics(), None
+ value = load_json(path)
+ if not isinstance(value, dict) or value.get("schema") != ATTEMPT_SCHEMA:
+ fail("invalid evaluator attempt journal")
+ if value.get("key") != key:
+ return zero_metrics(), None
+ metrics = value.get("metrics")
+ if (not isinstance(metrics, dict)
+ or any(not isinstance(metrics.get(field), int)
+ or not 0 <= metrics[field] <= MAX_EXACT_INTEGER
+ for field in METRIC_FIELDS)):
+ fail("invalid evaluator attempt metrics")
+ normalized = {field: metrics[field] for field in METRIC_FIELDS}
+ if value.get("complete") is not True:
+ return normalized, None
+ result = value.get("result")
+ if (not isinstance(result, dict) or not isinstance(result.get("pass"), bool)
+ or not isinstance(result.get("score_ppm"), int)
+ or not 0 <= result["score_ppm"] <= 1_000_000
+ or any(result.get(field) != normalized[field] for field in METRIC_FIELDS)):
+ fail("invalid completed evaluator attempt")
+ return normalized, dict(result)
+
+
+def save_attempt(
+ path: Path,
+ key: str,
+ metrics: dict[str, int],
+ result: dict[str, Any] | None = None,
+) -> None:
+ save_json_atomic(path, {
+ "schema": ATTEMPT_SCHEMA,
+ "key": key,
+ "complete": result is not None,
+ "metrics": metrics,
+ "result": result,
+ })
+
+
+def clear_attempt(path: Path) -> None:
+ path.unlink(missing_ok=True)
def validate_settings(value: Any) -> dict[str, Any]:
@@ -180,6 +268,7 @@ def run_variant(
prompt: str,
case: dict[str, Any],
cwd: Path,
+ observe: Callable[[dict[str, int]], None] | None = None,
) -> dict[str, Any]:
env = os.environ.copy()
env["GRAFF_NO_TELEMETRY"] = "1"
@@ -191,7 +280,6 @@ def run_variant(
str(graff), "--json", "--model", "codex", "--no-resume", "--no-telemetry", "--yolo",
"--max-model-calls", str(settings["max_model_calls"]),
"--max-tool-calls", str(settings["max_tool_calls"]),
- "--system-prompt", prompt,
]
started = time.monotonic()
proc = subprocess.Popen(
@@ -205,6 +293,9 @@ def run_variant(
attempt_error: str | None = None
cost_micros = 0
try:
+ prompt_event = send(proc, {"type": "set_system_prompt", "text": prompt}, "system_prompt")
+ if prompt_event.get("ok") is not True or prompt_event.get("chars") != len(prompt.encode("utf-8")):
+ fail("evaluator system prompt was not honored")
model = send(proc, {
"type": "set_model", "provider": settings["provider"], "model": settings["model"],
}, "model")
@@ -227,7 +318,13 @@ def run_variant(
cost_micros = reported_cost_micros(event)
if event.get("type") == "tool_call":
tool_calls += 1
- elif event.get("type") == "error":
+ if observe is not None:
+ observe({
+ "latency_ms": max(0, round((time.monotonic() - started) * 1000)),
+ "tool_calls": tool_calls,
+ "cost_micros": cost_micros,
+ })
+ if event.get("type") == "error":
attempt_error = f"evaluation turn failed: {event.get('message', 'unknown')}"
break
elif event.get("type") == "turn":
@@ -246,6 +343,12 @@ def run_variant(
proc.kill()
proc.wait()
latency_ms = max(0, round((time.monotonic() - started) * 1000))
+ if observe is not None:
+ observe({
+ "latency_ms": latency_ms,
+ "tool_calls": tool_calls,
+ "cost_micros": cost_micros,
+ })
if attempt_error is not None:
raise EvaluationAttemptError(
attempt_error,
@@ -276,22 +379,35 @@ def run_with_retries(
prompt: str,
case: dict[str, Any],
label: str,
+ key: str,
+ journal_path: Path,
) -> dict[str, Any]:
- prior = {"latency_ms": 0, "tool_calls": 0, "cost_micros": 0}
+ prior, completed = load_attempt(journal_path, key)
+ if completed is not None:
+ return completed
last_error: EvaluationAttemptError | None = None
for _attempt in range(settings["max_attempts"]):
scratch = Path(tempfile.mkdtemp(prefix=f"learn-{label}-", dir="."))
try:
safe_setup(scratch, case.get("setup_files"))
- run = run_variant(graff, settings, prompt, case, scratch)
- for metric in prior:
- run[metric] += prior[metric]
+
+ def observe(attempt: dict[str, int]) -> None:
+ save_attempt(journal_path, key, add_metrics(prior, attempt))
+
+ run = run_variant(graff, settings, prompt, case, scratch, observe)
+ total = add_metrics(prior, {field: run[field] for field in METRIC_FIELDS})
+ for field in METRIC_FIELDS:
+ run[field] = total[field]
+ save_attempt(journal_path, key, total, run)
return run
except EvaluationAttemptError as exc:
last_error = exc
- prior["latency_ms"] += exc.latency_ms
- prior["tool_calls"] += exc.tool_calls
- prior["cost_micros"] += exc.cost_micros
+ prior = add_metrics(prior, {
+ "latency_ms": exc.latency_ms,
+ "tool_calls": exc.tool_calls,
+ "cost_micros": exc.cost_micros,
+ })
+ save_attempt(journal_path, key, prior)
finally:
shutil.rmtree(scratch, ignore_errors=True)
fail(f"evaluation failed after bounded retries: {last_error}")
@@ -336,7 +452,11 @@ def evaluate(settings_path: Path, graff: Path, request_path: Path, response_path
if int(str(pair.get("seed", "0"))[-1], 16) % 2:
order = tuple(reversed(order))
for label, prompt in order:
- runs[label] = run_with_retries(graff_executable, settings, prompt, case, label)
+ journal = Path(f".attempt-{label}.json")
+ runs[label] = run_with_retries(
+ graff_executable, settings, prompt, case, label,
+ attempt_key(request_sha256, pair, label, prompt), journal,
+ )
parent_run = runs["parent"]
child_run = runs["child"]
results.append({
@@ -350,6 +470,8 @@ def evaluate(settings_path: Path, graff: Path, request_path: Path, response_path
"parent_tool_calls": parent_run["tool_calls"], "child_tool_calls": child_run["tool_calls"],
})
save_progress(progress_path, request_sha256, results)
+ clear_attempt(Path(".attempt-parent.json"))
+ clear_attempt(Path(".attempt-child.json"))
response = {
"schema": RESPONSE_SCHEMA,
"trial_id": request.get("trial_id"),
@@ -373,7 +495,11 @@ def evaluate_baseline(settings_path: Path, graff: Path, request_path: Path, resp
request_sha256, results = load_progress(progress_path, request_path, pairs)
for pair in pairs[len(results):]:
case = case_for_pair(pair, case_map)
- run = run_with_retries(graff_executable, settings, parent, case, "baseline")
+ journal = Path(".attempt-baseline.json")
+ run = run_with_retries(
+ graff_executable, settings, parent, case, "baseline",
+ attempt_key(request_sha256, pair, "baseline", parent), journal,
+ )
results.append({
"case_id": pair["case_id"], "seed": pair["seed"],
"pass": run["pass"], "score_ppm": run["score_ppm"],
@@ -382,6 +508,7 @@ def evaluate_baseline(settings_path: Path, graff: Path, request_path: Path, resp
"tool_calls": run["tool_calls"],
})
save_progress(progress_path, request_sha256, results)
+ clear_attempt(journal)
response = {
"schema": BASELINE_RESPONSE_SCHEMA,
"trial_id": request.get("trial_id"),
@@ -413,7 +540,11 @@ def evaluate_primary(settings_path: Path, graff: Path, request_path: Path, respo
or parent_run.get("case_id") != pair.get("case_id")
or parent_run.get("seed") != pair.get("seed")):
fail("primary baseline pair mismatch")
- child_run = run_with_retries(graff_executable, settings, child, case, "child")
+ journal = Path(".attempt-child.json")
+ child_run = run_with_retries(
+ graff_executable, settings, child, case, "child",
+ attempt_key(request_sha256, pair, "child", child), journal,
+ )
results.append({
"case_id": pair["case_id"], "seed": pair["seed"],
"parent_pass": parent_run.get("pass"), "child_pass": child_run["pass"],
@@ -425,6 +556,7 @@ def evaluate_primary(settings_path: Path, graff: Path, request_path: Path, respo
"parent_tool_calls": parent_run.get("tool_calls", 0), "child_tool_calls": child_run["tool_calls"],
})
save_progress(progress_path, request_sha256, results)
+ clear_attempt(journal)
response = {
"schema": PRIMARY_RESPONSE_SCHEMA,
"trial_id": request.get("trial_id"),
diff --git a/examples/learn_graff_suites.py b/examples/learn_graff_suites.py
index c13b2f24..53ff5dd7 100644
--- a/examples/learn_graff_suites.py
+++ b/examples/learn_graff_suites.py
@@ -15,6 +15,7 @@ def _case(
setup: dict[str, str] | None = None,
*,
critical: bool = False,
+ statistical_unit_id: str | None = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {"id": case_id, "task": task, "check": check}
if setup is not None:
@@ -22,6 +23,8 @@ def _case(
result: dict[str, Any] = {"id": case_id, "payload": payload}
if critical:
result["critical"] = True
+ if statistical_unit_id is not None:
+ result["statistical_unit_id"] = statistical_unit_id
return result
@@ -29,8 +32,10 @@ def _exact(case_id: str, task: str, expected: str, setup: dict[str, str] | None
return _case(case_id, task, {"exact": expected}, setup)
-def _mutation(case_id: str, task: str, command: str, setup: dict[str, str] | None = None) -> dict[str, Any]:
- return _case(case_id, task, {"cmd": command}, setup, critical=True)
+def _mutation(case_id: str, task: str, command: str, setup: dict[str, str] | None = None,
+ *, statistical_unit_id: str | None = None) -> dict[str, Any]:
+ return _case(case_id, task, {"cmd": command}, setup, critical=True,
+ statistical_unit_id=statistical_unit_id)
def primary_cases() -> list[dict[str, Any]]:
@@ -293,6 +298,7 @@ def primary_cases() -> list[dict[str, Any]]:
f"Ensure {name} contains exactly state={token}. It already does, so leave it unchanged.",
f"test \"$(cat {name})\" = state={token} && test \"$(wc -c < {name})\" -eq {len(token) + 7}",
{name: f"state={token}\n"},
+ statistical_unit_id="edit-noop",
))
for index in range(5):
cases.append(_mutation(
@@ -300,6 +306,7 @@ def primary_cases() -> list[dict[str, Any]]:
f"Remove lines beginning DROP: from filter{index}.txt without reordering the other lines.",
f"test \"$(cat filter{index}.txt)\" = 'a{index}\nb{index}\nc{index}'",
{f"filter{index}.txt": f"a{index}\nDROP:x\nb{index}\nDROP:y\nc{index}\n"},
+ statistical_unit_id="edit-filter",
))
for index in range(5):
cases.append(_mutation(
@@ -307,6 +314,7 @@ def primary_cases() -> list[dict[str, Any]]:
f"Deduplicate ids{index}.txt in place, preserving first-occurrence order.",
f"test \"$(cat ids{index}.txt)\" = 'k{index}a\nk{index}b\nk{index}c'",
{f"ids{index}.txt": f"k{index}a\nk{index}b\nk{index}a\nk{index}c\nk{index}b\n"},
+ statistical_unit_id="edit-dedupe",
))
for index in range(5):
desired_value = secrets.randbelow(8000) + 1000
@@ -318,6 +326,7 @@ def primary_cases() -> list[dict[str, Any]]:
f"desired{index}.ini": f"limit={desired_value}\n",
f"runtime{index}.ini": f"name=worker{index}\nlimit=10\n",
},
+ statistical_unit_id="edit-copy",
))
return cases
@@ -361,8 +370,16 @@ def fresh_holdout() -> list[dict[str, Any]]:
_mutation("fresh-econ-sum-write", "Sum the integers in amounts.txt and write only the total to answer.txt.", f"test \"$(cat answer.txt)\" = {sum(numbers)}", {"amounts.txt": "\n".join(map(str, numbers)) + "\n"}),
_mutation("fresh-econ-uppercase", "Read phase.txt and write its uppercase text to loud.txt with no trailing newline.", "test \"$(cat loud.txt)\" = AURORA && test \"$(wc -c < loud.txt)\" -eq 6", {"phase.txt": "aurora\n"}),
_mutation("fresh-econ-filter", "Write kept.txt from source.txt with lines beginning DROP: removed, preserving all others.", "test \"$(cat kept.txt)\" = 'one\ntwo\nthree'", {"source.txt": "one\nDROP:a\ntwo\nDROP:b\nthree\n"}),
+ _mutation("fresh-shift-reverse-block", "Reverse the line order in queue.txt in place.", "test \"$(cat queue.txt)\" = 'third\nsecond\nfirst'", {"queue.txt": "first\nsecond\nthird\n"}),
+ _mutation("fresh-shift-rename-key", "In theme.ini rename only the key colour to color without changing its value or any other line.", "test \"$(cat theme.ini)\" = 'name=night\ncolor=blue\nmode=calm'", {"theme.ini": "name=night\ncolour=blue\nmode=calm\n"}),
+ _mutation("fresh-shift-interleave", "Interleave same-position lines from left.txt and right.txt into woven.txt, starting with left.", "test \"$(cat woven.txt)\" = 'L1\nR1\nL2\nR2\nL3\nR3'", {"left.txt": "L1\nL2\nL3\n", "right.txt": "R1\nR2\nR3\n"}),
+ _mutation("fresh-shift-last-occurrence", "In flags.txt change only the final old line to new.", "test \"$(cat flags.txt)\" = 'old\nkeep\nold\nnew'", {"flags.txt": "old\nkeep\nold\nold\n"}),
+ _mutation("fresh-shift-extract-column", "Write ranks.txt containing the numeric second column of table.txt sorted ascending, one value per line.", "test \"$(cat ranks.txt)\" = '2\n7\n11'", {"table.txt": "oak 11\npine 2\ncedar 7\n"}),
+ _mutation("fresh-shift-section-update", "In service.ini change timeout to 45 only inside the worker section.", "test \"$(cat service.ini)\" = '[global]\ntimeout=10\n[worker]\ntimeout=45\nretries=2'", {"service.ini": "[global]\ntimeout=10\n[worker]\ntimeout=30\nretries=2\n"}),
+ _mutation("fresh-shift-prefix-nonblank", "Prefix every nonblank line in notes.txt with '- ' while preserving the blank line.", "test \"$(cat notes.txt)\" = '- alpha\n\n- beta'", {"notes.txt": "alpha\n\nbeta\n"}),
+ _mutation("fresh-shift-json-labels", "Read the objects in items.json and write their label values to labels.txt in array order.", "test \"$(cat labels.txt)\" = 'ember\nfrost\ngrove'", {"items.json": '[{"label":"ember"},{"label":"frost"},{"label":"grove"}]\n'}),
]
- for index in range(3):
+ for index in range(1):
fresh_token = secrets.token_hex(4)
name = f"fresh-ready{index}.cfg"
cases.append(_mutation(
@@ -371,21 +388,21 @@ def fresh_holdout() -> list[dict[str, Any]]:
f"test \"$(cat {name})\" = ready={fresh_token} && test \"$(wc -c < {name})\" -eq {len(fresh_token) + 7}",
{name: f"ready={fresh_token}\n"},
))
- for index in range(3):
+ for index in range(1):
cases.append(_mutation(
f"fresh-edit-filter-random-{index}",
f"Remove lines beginning OMIT: from fresh-filter{index}.txt without reordering other lines.",
f"test \"$(cat fresh-filter{index}.txt)\" = 'p{index}\nq{index}\nr{index}'",
{f"fresh-filter{index}.txt": f"p{index}\nOMIT:x\nq{index}\nOMIT:y\nr{index}\n"},
))
- for index in range(3):
+ for index in range(1):
cases.append(_mutation(
f"fresh-edit-dedupe-random-{index}",
f"Deduplicate fresh-ids{index}.txt in place while preserving first-occurrence order.",
f"test \"$(cat fresh-ids{index}.txt)\" = 'v{index}a\nv{index}b\nv{index}c'",
{f"fresh-ids{index}.txt": f"v{index}a\nv{index}b\nv{index}a\nv{index}c\nv{index}b\n"},
))
- for index in range(3):
+ for index in range(1):
desired_limit = secrets.randbelow(8000) + 1000
cases.append(_mutation(
f"fresh-edit-copy-random-{index}",
@@ -409,10 +426,24 @@ def validate_case_catalog(cases: list[dict[str, Any]], expected: int) -> None:
check = payload.get("check")
if not isinstance(check, dict) or len(check) != 1:
raise ValueError("every case needs exactly one check")
+ criticality: dict[str, bool] = {}
+ for case in cases:
+ unit = case.get("statistical_unit_id", case["id"])
+ critical = bool(case.get("critical", False))
+ if unit in criticality and criticality[unit] != critical:
+ raise ValueError("one statistical unit cannot mix criticality")
+ criticality[unit] = critical
+
+
+def statistical_unit_count(cases: list[dict[str, Any]]) -> int:
+ return len({case.get("statistical_unit_id", case["id"]) for case in cases})
if __name__ == "__main__":
primary, holdout = primary_cases(), fresh_holdout()
validate_case_catalog(primary, 60)
validate_case_catalog(holdout, 40)
- print(json.dumps({"primary": len(primary), "holdout": len(holdout)}))
+ print(json.dumps({
+ "primary": len(primary), "primary_units": statistical_unit_count(primary),
+ "holdout": len(holdout), "holdout_units": statistical_unit_count(holdout),
+ }))
diff --git a/examples/prepare_graff_tournament.py b/examples/prepare_graff_tournament.py
index 9325f9cf..cf43b2cb 100755
--- a/examples/prepare_graff_tournament.py
+++ b/examples/prepare_graff_tournament.py
@@ -9,7 +9,12 @@ import json
from pathlib import Path
import secrets
-from learn_graff_suites import fresh_holdout, primary_cases, validate_case_catalog
+from learn_graff_suites import (
+ fresh_holdout,
+ primary_cases,
+ statistical_unit_count,
+ validate_case_catalog,
+)
def digest(path: Path) -> str:
@@ -77,7 +82,11 @@ def main() -> None:
public_cases, hidden_cases = primary_cases(), fresh_holdout()
validate_case_catalog(public_cases, 60)
validate_case_catalog(hidden_cases, 40)
- write_json(primary, {"schema": "codegraff.learn.suite.v1", "suite_id": "graff-primary-v6", "cases": public_cases})
+ primary_units = statistical_unit_count(public_cases)
+ holdout_units = statistical_unit_count(hidden_cases)
+ if primary_units < 40 or holdout_units < 40:
+ raise ValueError("primary and holdout each require 40 independent statistical units")
+ write_json(primary, {"schema": "codegraff.learn.suite.v1", "suite_id": "graff-primary-v7", "cases": public_cases})
write_json(holdout, {"schema": "codegraff.learn.suite.v1", "suite_id": "fresh-" + secrets.token_hex(8), "cases": hidden_cases})
config = {
@@ -109,7 +118,7 @@ def main() -> None:
"default_repetitions": 1,
},
"auto": {"enabled": False},
- "cohort": {"provider": "codex", "model": "gpt-5.4-mini", "task_family": "coding-flow", "adapter_version": "graff-eval-v6", "verifier_version": "exact-v5"},
+ "cohort": {"provider": "codex", "model": "gpt-5.4-mini", "task_family": "coding-flow", "adapter_version": "graff-eval-v7", "verifier_version": "clustered-exact-v6"},
}
config_path = output / "config.json"
write_json(config_path, config)
@@ -117,6 +126,7 @@ def main() -> None:
"workspace": str(workspace), "parent": str(parent), "config": str(config_path),
"primary_sha256": digest(primary), "holdout_sha256": digest(holdout),
"primary_cases": len(public_cases), "holdout_cases": len(hidden_cases),
+ "primary_units": primary_units, "holdout_units": holdout_units,
}, indent=2))
diff --git a/examples/replay_judge.py b/examples/replay_judge.py
index f0a129d4..03662731 100644
--- a/examples/replay_judge.py
+++ b/examples/replay_judge.py
@@ -72,13 +72,30 @@ def load_eval_set():
return tasks, digest
+def send_control(proc, value, expected):
+ proc.stdin.write(json.dumps(value, separators=(",", ":")) + "\n")
+ proc.stdin.flush()
+ for line in proc.stdout:
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(event, dict):
+ continue
+ if event.get("type") == "error":
+ return None
+ if event.get("type") == expected:
+ return event
+ return None
+
+
def run_variant(system_prompt, task_text, cwd):
"""One harness conversation under the candidate genome, confined to a
scratch dir. Returns {"text", "tool_calls", "cost"}: the final assistant
text ('' on timeout/error), how many tools it called, and the turn cost in
USD. tool_calls/cost are the raw material for the efficiency gradient that
discriminates genomes once they all pass (see dgm_loop.judge)."""
- argv = [HARNESS_BIN, "--json", "--yolo", "--system-prompt", system_prompt]
+ argv = [HARNESS_BIN, "--json", "--yolo"]
model = os.environ.get("GRAFF_EVAL_MODEL")
if model:
argv += ["--model", model]
@@ -93,6 +110,12 @@ def run_variant(system_prompt, task_text, cwd):
tool_calls = 0
cost = 0.0
try:
+ prompt_event = send_control(proc, {
+ "type": "set_system_prompt", "text": system_prompt,
+ }, "system_prompt")
+ if (not prompt_event or prompt_event.get("ok") is not True
+ or prompt_event.get("chars") != len(system_prompt.encode("utf-8"))):
+ return {"text": "", "tool_calls": 0, "cost": 0.0}
proc.stdin.write(json.dumps({"type": "user", "text": task_text}) + "\n")
proc.stdin.flush()
for line in proc.stdout:
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index 9f988df8..cb1fb030 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -199,7 +199,8 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
try w.writeAll(
" ⚠ learn_candidate will run the pinned adapters, then send signed aggregate grades once\n" ++
" Adapter egress: a configured model adapter may send prompt/genome text to its model provider.\n" ++
- " Sends: pass rates, prompt/parent fingerprints, run/suite/cohort and evidence IDs.\n" ++
+ " Sends: pass counts/deltas, significance, critical regressions, tool/cost/latency totals, gate settings, eligibility, fingerprints, and evidence IDs.\n" ++
+ " No stable install ID, OS, architecture, or service version is sent.\n" ++
" Excludes: prompt/genome text, tasks, code, paths, evaluator input/output, and traces.\n" ++
" [y] run + send once · [n] cancel › ",
);
diff --git a/src/cli.zig b/src/cli.zig
index d78edd1a..19772c8a 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -21,6 +21,11 @@ const harness_version = root.harness_version;
pub const changelog_text =
\\What's new
\\──────────
+ \\0.0.215
+ \\ • Local learning can race multiple prompt variants, rank correctness before tool economy, and expose only the winner to a hidden holdout
+ \\ • Runs checkpoint safely, keep promotion manual by default, and can bundle an aggregate-only signed grade submission
+ \\ • Aggregate receipts expire after 30 days and can be deleted remotely without deleting local evidence or requiring telemetry consent
+ \\
\\0.0.209
\\ • Kimi Code now follows each live catalog model's native or Anthropic beta protocol, auth style, context, and thinking metadata
\\ • Native Kimi tool schemas are normalized to Moonshot's stricter validator; OAuth requests carry the current Kimi Code identity headers
diff --git a/src/jobs.zig b/src/jobs.zig
index 64d542f8..e8c7be60 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -14,6 +14,12 @@ const root = @import("main.zig");
const agent_mod = @import("agent.zig");
const tools_mod = @import("tools.zig");
const ToolOutput = tools_mod.ToolOutput;
+const process_runner = @import("process_runner.zig");
+pub const CappedRun = process_runner.CappedRun;
+pub const CappedRunOptions = process_runner.CappedRunOptions;
+pub const runCapped = process_runner.runCapped;
+pub const runCappedWithOptions = process_runner.runCappedWithOptions;
+const ranOk = process_runner.ranOk;
/// Commit-message trailer that credits the harness assist. The commit AUTHOR
/// stays the user's own git identity (their GitHub account) — graff never
@@ -22,111 +28,6 @@ const ToolOutput = tools_mod.ToolOutput;
const codegraff_coauthor = "Co-Authored-By: Codegraff <[email protected]>";
const Agent = agent_mod.Agent;
-pub const CappedRun = struct {
- term: std.process.Child.Term,
- stdout: []u8,
- stderr: []u8,
- stdout_truncated: bool,
- stderr_truncated: bool,
- timed_out: bool,
-};
-
-/// Optional process isolation knobs for trusted orchestrators. Supplying an
-/// explicit environment replaces (rather than augments) the parent process
-/// environment; argv is always executed directly, never through a shell.
-pub const CappedRunOptions = struct {
- cwd: std.process.Child.Cwd = .inherit,
- environ_map: ?*const std.process.Environ.Map = null,
-};
-
-/// Like `std.process.run`, but hitting an output cap *truncates* instead of
-/// failing the call: the first `cap` bytes are kept, the rest is discarded
-/// as it streams (retained memory never exceeds the caps), and the child
-/// still runs to completion so its exit code is real. A chatty `python`
-/// (or an accidental `cat` of something huge) costs the child's own
-/// process memory, never the harness's.
-///
-/// `deadline_ms` is a wall-clock kill switch: 0 means "no deadline" (the
-/// root's Esc is the only stop), non-zero kills the child once it has run
-/// that long and reports `timed_out`. Subagents pass a real deadline since
-/// they have no Esc (#93).
-pub fn runCapped(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64) !CappedRun {
- return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{});
-}
-
-pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, options: CappedRunOptions) !CappedRun {
- var child = try std.process.spawn(io, .{
- .argv = argv,
- .cwd = options.cwd,
- .environ_map = options.environ_map,
- .stdin = .ignore,
- .stdout = .pipe,
- .stderr = .pipe,
- });
- defer child.kill(io);
-
- var multi_reader_buffer: Io.File.MultiReader.Buffer(2) = undefined;
- var multi_reader: Io.File.MultiReader = undefined;
- multi_reader.init(gpa, io, multi_reader_buffer.toStreams(), &.{ child.stdout.?, child.stderr.? });
- defer multi_reader.deinit();
-
- const readers = [2]*Io.Reader{ multi_reader.reader(0), multi_reader.reader(1) };
- const caps = [2]usize{ stdout_cap, stderr_cap };
- var saved: [2]?[]u8 = .{ null, null };
- errdefer for (saved) |s| if (s) |b| gpa.free(b);
-
- // Fill in 200ms ticks so a root Esc (Agent.esc_cancel, set by the
- // tool-join watcher) kills a long-running child instead of waiting it
- // out — this is where a hung `sleep`-style command actually dies. A
- // non-zero deadline_ms is the same kill switch on a wall clock, for
- // subagents that have no Esc to press (#93).
- var esc_killed = false;
- var timed_out = false;
- const t0: Io.Timestamp = .now(io, .awake);
- loop: while (true) {
- multi_reader.fill(64, .{ .duration = .{ .raw = .fromMilliseconds(200), .clock = .awake } }) catch |err| switch (err) {
- error.EndOfStream => break :loop,
- error.Timeout => {}, // poll tick: no data, just check for cancel
- else => |e| return e,
- };
- for (readers, caps, &saved) |r, cap, *s| {
- const buf = r.buffered();
- if (s.* == null and buf.len > cap) s.* = try gpa.dupe(u8, buf[0..cap]);
- if (s.* != null) r.toss(buf.len); // past the cap: discard as it streams
- }
- if (Agent.esc_cancel.load(.acquire)) {
- esc_killed = true;
- child.kill(io);
- break :loop;
- }
- if (deadline_ms > 0 and t0.untilNow(io, .awake).toMilliseconds() >= deadline_ms) {
- timed_out = true;
- child.kill(io);
- break :loop;
- }
- }
- if (!esc_killed and !timed_out) try multi_reader.checkAnyError(); // killed streams error by design
-
- // kill() already reaped the child (wait would assert on id == null).
- const term: std.process.Child.Term = if (esc_killed or timed_out) .{ .signal = .TERM } else try child.wait(io);
- const stdout = if (saved[0]) |b| b else try gpa.dupe(u8, readers[0].buffered());
- errdefer gpa.free(stdout);
- const stderr = if (saved[1]) |b| b else try gpa.dupe(u8, readers[1].buffered());
- return .{
- .term = term,
- .stdout = stdout,
- .stderr = stderr,
- .stdout_truncated = saved[0] != null,
- .stderr_truncated = saved[1] != null,
- .timed_out = timed_out,
- };
-}
-
-/// True if a CappedRun child exited cleanly (status 0).
-fn ranOk(r: CappedRun) bool {
- return r.term == .exited and r.term.exited == 0;
-}
-
/// True if the current git working tree has uncommitted *tracked* changes
/// (staged or unstaged). Untracked files (`?? …`) don't count — `git reset
/// --hard` leaves them alone, so they're safe around a worktree land.
@@ -575,3 +476,43 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {
gpa.free(jobs);
g_jobs.list.deinit(gpa);
}
+
+test "isolated capped runs clean descendants after timeout and normal exit" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ const timed = try runCappedWithOptions(
+ std.testing.allocator,
+ io,
+ &.{ "/bin/sh", "-c", "(sleep 0.8; printf survived > timeout-marker) >/dev/null 2>&1 & sleep 30" },
+ 1024,
+ 1024,
+ 50,
+ .{ .cwd = .{ .dir = tmp.dir }, .kill_process_tree = true },
+ );
+ defer {
+ std.testing.allocator.free(timed.stdout);
+ std.testing.allocator.free(timed.stderr);
+ }
+ try std.testing.expect(timed.timed_out);
+
+ const completed = try runCappedWithOptions(
+ std.testing.allocator,
+ io,
+ &.{ "/bin/sh", "-c", "(sleep 0.8; printf survived > completed-marker) >/dev/null 2>&1 & exit 0" },
+ 1024,
+ 1024,
+ 2_000,
+ .{ .cwd = .{ .dir = tmp.dir }, .kill_process_tree = true },
+ );
+ defer {
+ std.testing.allocator.free(completed.stdout);
+ std.testing.allocator.free(completed.stderr);
+ }
+ try std.testing.expect(ranOk(completed));
+ io.sleep(.fromMilliseconds(1_000), .awake) catch {};
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "timeout-marker", .{}));
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "completed-marker", .{}));
+}
diff --git a/src/learn_checkpoint.zig b/src/learn_checkpoint.zig
new file mode 100644
index 00000000..1a769f3d
--- /dev/null
+++ b/src/learn_checkpoint.zig
@@ -0,0 +1,86 @@
+//! Crash-durable progress for an in-flight local learning tournament.
+//!
+//! This mutable ref contains only IDs and verified aggregates. Resume never
+//! trusts it directly: every referenced immutable genome/evidence object is
+//! revalidated by the normal mutation/evaluation verifiers before reuse.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const eval = @import("learn_eval.zig");
+const store_mod = @import("learn_store.zig");
+
+pub const schema = "codegraff.learn.pending.v1";
+pub const file_name = "pending.json";
+
+pub const Record = struct {
+ schema: []const u8 = schema,
+ trial_id: []const u8,
+ nonce: []const u8,
+ created_unix_ms: i64,
+ harness_version: []const u8,
+ config_id: []const u8,
+ parent_genome_id: []const u8,
+ parent_generation: u64,
+ parent_transaction_id: []const u8,
+ planned_candidates: usize,
+ repetitions: usize,
+ auto_requested: bool,
+ primary_baseline: ?eval.PrimaryBaselineRecord = null,
+ candidates: []const eval.CandidateRecord,
+};
+
+fn validCandidate(candidate: eval.CandidateRecord) bool {
+ return store_mod.validId(candidate.genome_id) and
+ store_mod.validId(candidate.mutation.seed) and
+ store_mod.validId(candidate.mutation.request_evidence_id) and
+ store_mod.validId(candidate.mutation.response_evidence_id) and
+ candidate.mutation.description.len <= 512 and
+ std.unicode.utf8ValidateSlice(candidate.mutation.description) and
+ std.mem.indexOfScalar(u8, candidate.mutation.description, 0) == null and
+ !candidate.eligible;
+}
+
+pub fn validate(record: Record) !void {
+ if (!std.mem.eql(u8, record.schema, schema) or
+ !store_mod.validId(record.trial_id) or
+ !store_mod.validId(record.nonce) or
+ !store_mod.validId(record.config_id) or
+ !store_mod.validId(record.parent_genome_id) or
+ !store_mod.validId(record.parent_transaction_id)) return error.InvalidPendingRun;
+ if (record.harness_version.len == 0 or record.harness_version.len > 128 or
+ record.planned_candidates == 0 or record.planned_candidates > 16 or
+ record.candidates.len != record.planned_candidates or
+ record.repetitions == 0 or record.repetitions > 100) return error.InvalidPendingRun;
+ if (record.primary_baseline) |baseline| {
+ if (!store_mod.validId(baseline.suite_sha256) or
+ !store_mod.validId(baseline.request_evidence_id) or
+ !store_mod.validId(baseline.response_evidence_id)) return error.InvalidPendingRun;
+ }
+ for (record.candidates) |candidate| if (!validCandidate(candidate)) return error.InvalidPendingRun;
+}
+
+pub fn load(arena: Allocator, store: *store_mod.Store) !?Record {
+ const bytes = store_mod.readFileNoFollow(store.io, store.refs, file_name, arena, store_mod.max_record_bytes) catch |err| switch (err) {
+ error.FileNotFound => return null,
+ else => return err,
+ };
+ const record = try std.json.parseFromSliceLeaky(Record, arena, bytes, .{});
+ try validate(record);
+ return record;
+}
+
+pub fn write(gpa: Allocator, store: *store_mod.Store, record: Record) !void {
+ try validate(record);
+ const bytes = try store_mod.jsonBytes(gpa, record);
+ defer gpa.free(bytes);
+ if (bytes.len > store_mod.max_record_bytes) return error.PendingRunTooLarge;
+ try store.writeAtomicReplace(store.refs, file_name, bytes);
+}
+
+pub fn clear(store: *store_mod.Store) !void {
+ store.refs.deleteFile(store.io, file_name) catch |err| switch (err) {
+ error.FileNotFound => return,
+ else => return err,
+ };
+ try store_mod.syncDirectory(store.io, store.refs);
+}
diff --git a/src/learn_cli.zig b/src/learn_cli.zig
index 01f0b126..c1f5cd5a 100644
--- a/src/learn_cli.zig
+++ b/src/learn_cli.zig
@@ -8,10 +8,14 @@ const Allocator = std.mem.Allocator;
const build_options = @import("build_options");
const store_mod = @import("learn_store.zig");
+const checkpoint = @import("learn_checkpoint.zig");
const eval = @import("learn_eval.zig");
const holdout = @import("learn_holdout.zig");
+const diagnostics = @import("learn_diagnostics.zig");
+const mutation_verify = @import("learn_mutation_verify.zig");
const primary = @import("learn_primary.zig");
const learn_run = @import("learn_run.zig");
+const learn_delete = @import("learn_delete.zig");
const submit = @import("learn_submit.zig");
const tournament = @import("learn_tournament.zig");
const util = @import("util.zig");
@@ -21,8 +25,9 @@ pub const usage =
\\
\\usage:
\\ graff learn init --parent PATH --config PATH
- \\ graff learn run [--candidates N] [--repetitions N] [--submit] [--auto] [--lock-timeout-ms N]
+ \\ graff learn run [--candidates N] [--repetitions N] [--resume | --restart] [--submit] [--auto] [--show-adapter-stderr] [--lock-timeout-ms N]
\\ graff learn submit RUN_ID [--lock-timeout-ms N]
+ \\ graff learn delete-remote RUN_ID [--lock-timeout-ms N]
\\ graff learn status [--lock-timeout-ms N]
\\ graff learn promote RUN_ID [--lock-timeout-ms N]
\\ graff learn rollback [--to GENOME_ID] [--lock-timeout-ms N]
@@ -36,7 +41,16 @@ pub const usage =
;
const InitArgs = struct { parent: []const u8, config: []const u8 };
-const RunArgs = struct { candidates: ?usize = null, repetitions: ?usize = null, submit: bool = false, auto: bool = false, lock_timeout_ms: u64 = 0 };
+const RunArgs = struct {
+ candidates: ?usize = null,
+ repetitions: ?usize = null,
+ submit: bool = false,
+ auto: bool = false,
+ resume_run: bool = false,
+ restart: bool = false,
+ show_adapter_stderr: bool = false,
+ lock_timeout_ms: u64 = 0,
+};
const StatusArgs = struct { lock_timeout_ms: u64 = 0 };
const PromoteArgs = struct { run_id: []const u8, lock_timeout_ms: u64 = 0 };
const SubmitArgs = struct { run_id: []const u8, lock_timeout_ms: u64 = 0 };
@@ -49,6 +63,7 @@ pub const Parsed = union(enum) {
run: RunArgs,
status: StatusArgs,
submit: SubmitArgs,
+ delete_remote: SubmitArgs,
promote: PromoteArgs,
rollback: RollbackArgs,
verify: StatusArgs,
@@ -100,6 +115,9 @@ pub fn parse(args: []const []const u8) !Parsed {
var seen_repetitions = false;
var seen_auto = false;
var seen_submit = false;
+ var seen_resume = false;
+ var seen_restart = false;
+ var seen_adapter_stderr = false;
var seen_lock = false;
var index: usize = 1;
while (index < args.len) : (index += 1) {
@@ -126,8 +144,21 @@ pub fn parse(args: []const []const u8) !Parsed {
if (seen_submit) return error.DuplicateOption;
seen_submit = true;
result.submit = true;
+ } else if (std.mem.eql(u8, arg, "--resume")) {
+ if (seen_resume) return error.DuplicateOption;
+ seen_resume = true;
+ result.resume_run = true;
+ } else if (std.mem.eql(u8, arg, "--restart")) {
+ if (seen_restart) return error.DuplicateOption;
+ seen_restart = true;
+ result.restart = true;
+ } else if (std.mem.eql(u8, arg, "--show-adapter-stderr")) {
+ if (seen_adapter_stderr) return error.DuplicateOption;
+ seen_adapter_stderr = true;
+ result.show_adapter_stderr = true;
} else if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
}
+ if (result.resume_run and result.restart) return error.ConflictingOptions;
return .{ .run = result };
}
if (std.mem.eql(u8, command_name, "status") or std.mem.eql(u8, command_name, "verify")) {
@@ -145,13 +176,16 @@ pub fn parse(args: []const []const u8) !Parsed {
while (index < args.len) : (index += 1) if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
return .{ .promote = result };
}
- if (std.mem.eql(u8, command_name, "submit")) {
+ if (std.mem.eql(u8, command_name, "submit") or std.mem.eql(u8, command_name, "delete-remote")) {
if (args.len < 2 or !store_mod.validId(args[1])) return error.InvalidId;
var result: SubmitArgs = .{ .run_id = args[1] };
var seen_lock = false;
var index: usize = 2;
while (index < args.len) : (index += 1) if (!try parseLockOption(args, &index, &seen_lock, &result.lock_timeout_ms)) return error.UnknownOption;
- return .{ .submit = result };
+ return if (std.mem.eql(u8, command_name, "submit"))
+ .{ .submit = result }
+ else
+ .{ .delete_remote = result };
}
if (std.mem.eql(u8, command_name, "rollback")) {
var result: RollbackArgs = .{};
@@ -179,32 +213,18 @@ pub fn parse(args: []const []const u8) !Parsed {
fn verifyPins(io: Io, arena: Allocator, config: store_mod.Config) !void {
try store_mod.verifyProgram(io, config.mutator);
try store_mod.verifyProgram(io, config.evaluator);
- _ = try store_mod.loadSuite(io, arena, config.evaluation_suite);
- if (config.holdout_suite) |suite| _ = try store_mod.loadSuite(io, arena, suite);
-}
-
-fn verifyMutationEvidence(arena: Allocator, store: *store_mod.Store, config: store_mod.Config, run: eval.RunRecord, index: usize, candidate: eval.CandidateRecord) !void {
- const expected_seed = eval.candidateSeed(run.trial_id, index);
- if (!std.mem.eql(u8, candidate.mutation.seed, &expected_seed)) return error.MutationMismatch;
- const request_bytes = try store.readEvidence(arena, candidate.mutation.request_evidence_id, config.limits.request_bytes);
- const response_bytes = try store.readEvidence(arena, candidate.mutation.response_evidence_id, config.limits.response_bytes);
- const request = try std.json.parseFromSliceLeaky(eval.MutationRequest, arena, request_bytes, .{});
- const response = try std.json.parseFromSliceLeaky(eval.MutationResponse, arena, response_bytes, .{});
- if (!std.mem.eql(u8, request.schema, eval.mutation_request_schema) or
- !std.mem.eql(u8, request.trial_id, run.trial_id) or request.candidate_index != index or
- !std.mem.eql(u8, request.seed, &expected_seed) or !std.mem.eql(u8, request.parent.id, run.parent_genome_id) or
- !std.mem.eql(u8, request.parent.path, "parent.genome") or !std.mem.eql(u8, request.child_path, "child.genome") or
- request.maximum_bytes != config.limits.genome_bytes or !std.mem.eql(u8, request.instruction, config.mutation_instruction)) return error.MutationMismatch;
- if (!std.mem.eql(u8, response.schema, eval.mutation_response_schema) or
- !std.mem.eql(u8, response.trial_id, run.trial_id) or response.candidate_index != index or
- !std.mem.eql(u8, response.parent_id, run.parent_genome_id) or !std.mem.eql(u8, response.child_path, "child.genome") or
- !store_mod.validId(response.child_sha256) or response.description.len > 512 or
- !std.unicode.utf8ValidateSlice(response.description) or std.mem.indexOfScalar(u8, response.description, 0) != null or
- !std.mem.eql(u8, response.description, candidate.mutation.description)) return error.MutationMismatch;
- const child = try store.readGenome(arena, candidate.genome_id, config.limits.genome_bytes);
- if (candidate.mutation.genome_bytes != child.len) return error.MutationOutputMismatch;
- const child_sha256 = store_mod.rawSha256(child);
- if (!std.mem.eql(u8, response.child_sha256, &child_sha256)) return error.MutationOutputMismatch;
+ const primary_suite = try store_mod.loadSuite(io, arena, config.evaluation_suite);
+ try store_mod.validateSuitePower(primary_suite.manifest, config.gate);
+ if (config.holdout_suite) |suite| {
+ const holdout_suite = try store_mod.loadSuite(io, arena, suite);
+ try store_mod.validateHoldoutIndependence(
+ config.evaluation_suite.sha256,
+ primary_suite.manifest,
+ suite.sha256,
+ holdout_suite.manifest,
+ );
+ try store_mod.validateSuitePower(holdout_suite.manifest, config.gate);
+ }
}
fn verifyRun(
@@ -217,6 +237,7 @@ fn verifyRun(
const bytes = try store.readRun(arena, run_id);
const run = try std.json.parseFromSliceLeaky(eval.RunRecord, arena, bytes, .{});
try eval.validateRun(run);
+ try learn_run.verifyTrialPower(io, arena, config.value, run.planned_candidates);
if (!std.mem.eql(u8, run.config_id, &config.id) or !std.mem.eql(u8, run.harness_version, build_options.version)) return error.CohortMismatch;
const expected_trial_id = learn_run.trialId(run.config_id, run.parent_genome_id, run.parent_generation, run.parent_transaction_id, run.nonce);
if (!std.mem.eql(u8, run.trial_id, &expected_trial_id)) return error.TrialMismatch;
@@ -249,7 +270,7 @@ fn verifyRun(
var primary_count: usize = 0;
for (run.candidates, computed, 0..) |candidate, *recomputed_candidate, index| {
_ = try store.readGenome(arena, candidate.genome_id, config.value.limits.genome_bytes);
- try verifyMutationEvidence(arena, store, config.value, run, index, candidate);
+ try mutation_verify.verify(arena, store, config.value, run.trial_id, run.parent_genome_id, index, candidate);
var excluded = false;
if (std.mem.eql(u8, candidate.genome_id, run.parent_genome_id)) {
excluded = true;
@@ -324,6 +345,7 @@ fn initCommand(gpa: Allocator, arena: Allocator, io: Io, args: InitArgs, out: *I
const config = try std.json.parseFromSliceLeaky(store_mod.Config, arena, config_bytes, .{});
try store_mod.validateConfig(config);
try verifyPins(io, arena, config);
+ try learn_run.verifyTrialPower(io, arena, config, config.gate.default_candidates);
const parent = try store_mod.readFileNoFollow(io, Io.Dir.cwd(), args.parent, arena, config.limits.genome_bytes);
// Validate the genome BEFORE creating the store tree: a rejected parent
// must not leave a half-initialized .graff/learn behind (which used to
@@ -341,6 +363,8 @@ fn initCommand(gpa: Allocator, arena: Allocator, io: Io, args: InitArgs, out: *I
}
fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.process.Environ.Map, args: RunArgs, out: *Io.Writer) !void {
+ diagnostics.setDetailed(args.show_adapter_stderr);
+ defer diagnostics.setDetailed(false);
var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
defer store.deinit();
var lock = try store.acquireLock(args.lock_timeout_ms);
@@ -359,6 +383,8 @@ fn runCommand(gpa: Allocator, arena: Allocator, io: Io, environ: *const std.proc
.repetitions = args.repetitions,
.submit = args.submit,
.auto = args.auto,
+ .resume_run = args.resume_run,
+ .restart = args.restart,
}, out);
if (result.selected_genome_id) |genome_id| {
try out.print("selected {s}\n", .{genome_id});
@@ -382,7 +408,11 @@ fn statusCommand(arena: Allocator, io: Io, timeout_ms: u64, out: *Io.Writer, ver
defer lock.deinit();
const config = try store.loadConfig(arena);
const active = try store.loadActive(arena, config);
- if (verify_all) try verifyPins(io, arena, config.value);
+ const pending = try checkpoint.load(arena, &store);
+ if (verify_all) {
+ try verifyPins(io, arena, config.value);
+ if (pending) |item| _ = try learn_run.restorePending(arena, io, &store, config, active, item);
+ }
const Status = struct {
schema: []const u8 = "codegraff.learn.status.v1",
integrity: []const u8 = "ok",
@@ -392,6 +422,10 @@ fn statusCommand(arena: Allocator, io: Io, timeout_ms: u64, out: *Io.Writer, ver
transaction_id: []const u8,
config_id: []const u8,
pins_verified: bool,
+ pending_trial_id: ?[]const u8,
+ pending_primary_arms: usize,
+ pending_holdout_arms: usize,
+ pending_verified: bool,
};
const value: Status = .{
.agent_name = config.value.agent_name,
@@ -400,12 +434,24 @@ fn statusCommand(arena: Allocator, io: Io, timeout_ms: u64, out: *Io.Writer, ver
.transaction_id = active.ref.transaction_id,
.config_id = &config.id,
.pins_verified = verify_all,
+ .pending_trial_id = if (pending) |item| item.trial_id else null,
+ .pending_primary_arms = if (pending) |item| countCompleted(item.candidates, false) else 0,
+ .pending_holdout_arms = if (pending) |item| countCompleted(item.candidates, true) else 0,
+ .pending_verified = pending == null or verify_all,
};
var stringify: std.json.Stringify = .{ .writer = out };
try stringify.write(value);
try out.writeByte('\n');
}
+fn countCompleted(candidates: []const eval.CandidateRecord, holdouts: bool) usize {
+ var count: usize = 0;
+ for (candidates) |candidate| if (if (holdouts) candidate.holdout != null else candidate.primary != null) {
+ count += 1;
+ };
+ return count;
+}
+
fn promoteCommand(gpa: Allocator, arena: Allocator, io: Io, args: PromoteArgs, out: *Io.Writer) !void {
var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
defer store.deinit();
@@ -479,6 +525,7 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init,
.run => |args| try runCommand(gpa, arena, io, init.environ_map, args, out),
.status => |args| try statusCommand(arena, io, args.lock_timeout_ms, out, false),
.submit => |args| try submitCommand(gpa, arena, io, init.environ_map, args, out),
+ .delete_remote => |args| try learn_delete.command(io, gpa, arena, init.environ_map, args.run_id, args.lock_timeout_ms, out),
.verify => |args| try statusCommand(arena, io, args.lock_timeout_ms, out, true),
.promote => |args| try promoteCommand(gpa, arena, io, args, out),
.rollback => |args| try rollbackCommand(gpa, arena, io, args, out),
@@ -491,13 +538,17 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init,
}
test "learn parser preserves strict command-local options" {
- const parsed = try parse(&.{ "run", "--candidates", "4", "--repetitions", "2", "--submit", "--auto", "--lock-timeout-ms", "50" });
+ const parsed = try parse(&.{ "run", "--candidates", "4", "--repetitions", "2", "--resume", "--submit", "--auto", "--show-adapter-stderr", "--lock-timeout-ms", "50" });
try std.testing.expectEqual(@as(usize, 4), parsed.run.candidates.?);
try std.testing.expectEqual(@as(usize, 2), parsed.run.repetitions.?);
try std.testing.expect(parsed.run.auto);
try std.testing.expect(parsed.run.submit);
+ try std.testing.expect(parsed.run.resume_run);
+ try std.testing.expect(parsed.run.show_adapter_stderr);
try std.testing.expectEqual(@as(u64, 50), parsed.run.lock_timeout_ms);
try std.testing.expectError(error.DuplicateOption, parse(&.{ "run", "--auto", "--auto" }));
+ try std.testing.expectError(error.DuplicateOption, parse(&.{ "run", "--show-adapter-stderr", "--show-adapter-stderr" }));
try std.testing.expectError(error.UnknownOption, parse(&.{ "run", "--mystery" }));
+ try std.testing.expectError(error.ConflictingOptions, parse(&.{ "run", "--resume", "--restart" }));
try std.testing.expectError(error.InvalidId, parse(&.{ "promote", "abcd" }));
}
diff --git a/src/learn_comparison.zig b/src/learn_comparison.zig
index 8bd677e2..02068b21 100644
--- a/src/learn_comparison.zig
+++ b/src/learn_comparison.zig
@@ -8,7 +8,17 @@ const stats = @import("learn_stats.zig");
fn reductionPpm(parent: u64, child: u64) i64 {
if (parent == 0) return if (child == 0) 0 else -1_000_000;
const delta = @as(i128, parent) - @as(i128, child);
- return @intCast(@divTrunc(delta * 1_000_000, @as(i128, parent)));
+ const raw = @divTrunc(delta * 1_000_000, @as(i128, parent));
+ // Economy promotion only distinguishes reductions from non-reductions.
+ // Bound regressions at -100% so hostile-but-valid aggregate counters can
+ // neither overflow i64 nor escape the signed receipt's fixed range.
+ return @intCast(@max(-1_000_000, raw));
+}
+
+test "tool-call reduction is bounded for extreme regressions" {
+ try std.testing.expectEqual(@as(i64, -1_000_000), reductionPpm(1, std.math.maxInt(u64)));
+ try std.testing.expectEqual(@as(i64, 0), reductionPpm(0, 0));
+ try std.testing.expectEqual(@as(i64, 500_000), reductionPpm(10, 5));
}
pub fn computeComparison(
@@ -30,6 +40,7 @@ pub fn computeComparison(
var tool_losses: usize = 0;
var child_critical_failures: usize = 0;
var critical_regressions: usize = 0;
+ var correctness_regressions: usize = 0;
var score_delta: i128 = 0;
var parent_cost: u64 = 0;
var child_cost: u64 = 0;
@@ -46,7 +57,10 @@ pub fn computeComparison(
if (result.parent_pass) parent_passes += 1;
if (result.child_pass) child_passes += 1;
if (!result.child_pass and pair.critical) child_critical_failures += 1;
- if (result.parent_pass and !result.child_pass and pair.critical) critical_regressions += 1;
+ if (result.parent_pass and !result.child_pass) {
+ correctness_regressions += 1;
+ if (pair.critical) critical_regressions += 1;
+ }
score_delta += @as(i128, result.child_score_ppm) - @as(i128, result.parent_score_ppm);
parent_cost = try stats.checkedMetricAdd(parent_cost, result.parent_cost_micros);
child_cost = try stats.checkedMetricAdd(child_cost, result.child_cost_micros);
@@ -58,11 +72,12 @@ pub fn computeComparison(
latency_measured = latency_measured and result.latency_measured;
}
- // Repetitions of one case are one statistical unit. Aggregate correctness
- // and calls per case before comparing directions.
+ // Repetitions and explicitly related clone IDs are one statistical unit.
+ // Aggregate correctness and calls within that unit before directions.
for (requested, 0..) |pair, index| {
+ const unit_id = protocol.statisticalUnitId(pair);
var seen = false;
- for (requested[0..index]) |prior| if (std.mem.eql(u8, prior.case_id, pair.case_id)) {
+ for (requested[0..index]) |prior| if (std.mem.eql(u8, protocol.statisticalUnitId(prior), unit_id)) {
seen = true;
break;
};
@@ -73,7 +88,7 @@ pub fn computeComparison(
var parent_case_calls: u64 = 0;
var child_case_calls: u64 = 0;
for (response.pairs, requested) |result, grouped_pair| {
- if (!std.mem.eql(u8, grouped_pair.case_id, pair.case_id)) continue;
+ if (!std.mem.eql(u8, protocol.statisticalUnitId(grouped_pair), unit_id)) continue;
if (result.parent_pass) parent_case_passes += 1;
if (result.child_pass) child_case_passes += 1;
parent_case_calls = try stats.checkedMetricAdd(parent_case_calls, result.parent_tool_calls);
@@ -99,7 +114,8 @@ pub fn computeComparison(
const tool_discordant = tool_wins + tool_losses;
const economy_eligible = config.gate.economy_gate_enabled and
child_critical_failures == 0 and statistical_units >= config.gate.minimum_pairs and
- child_passes >= parent_passes and losses == 0 and mean_score_delta >= 0 and
+ correctness_regressions == 0 and child_passes >= parent_passes and
+ losses == 0 and mean_score_delta >= 0 and
tool_calls_measured and
tool_discordant >= config.gate.minimum_economy_pairs and
tool_delta >= config.gate.minimum_tool_reduction_ppm and tool_significant;
@@ -118,7 +134,7 @@ pub fn computeComparison(
reason = "economy_eligible";
} else {
eligible = false;
- reason = if (config.gate.promotion_mode == .economy and (child_passes < parent_passes or losses > 0 or mean_score_delta < 0))
+ reason = if (config.gate.promotion_mode == .economy and (correctness_regressions > 0 or child_passes < parent_passes or losses > 0 or mean_score_delta < 0))
"correctness_regression"
else if (config.gate.promotion_mode == .economy and !tool_calls_measured)
"tool_calls_unmeasured"
@@ -146,6 +162,7 @@ pub fn computeComparison(
.ties = statistical_units - wins - losses,
.child_critical_failures = child_critical_failures,
.critical_regressions = critical_regressions,
+ .correctness_regressions = correctness_regressions,
.delta_ppm = delta_ppm,
.mean_score_delta_ppm = mean_score_delta,
.p_value_ppb = stats.toPpb(correctness_p),
diff --git a/src/learn_delete.zig b/src/learn_delete.zig
new file mode 100644
index 00000000..f36b2d74
--- /dev/null
+++ b/src/learn_delete.zig
@@ -0,0 +1,112 @@
+//! User-controlled deletion of one remote aggregate learning receipt.
+//! Local genomes, evidence, and immutable run history are never changed.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const eval = @import("learn_eval.zig");
+const learn_run = @import("learn_run.zig");
+const receipt = @import("learn_receipt.zig");
+const scoring = @import("scoring.zig");
+const store_mod = @import("learn_store.zig");
+const submit = @import("learn_submit.zig");
+const telemetry = @import("telemetry.zig");
+const telemetry_net = @import("telemetry_net.zig");
+
+fn learningUrl(gpa: Allocator, endpoint: []const u8, run_id: []const u8) ![]u8 {
+ const logs_url = (try telemetry_net.otlpLogsUrl(gpa, endpoint)) orelse
+ return error.InvalidTelemetryEndpoint;
+ defer gpa.free(logs_url);
+ const query_at = std.mem.indexOfScalar(u8, logs_url, '?') orelse logs_url.len;
+ const path = logs_url[0..query_at];
+ if (!std.mem.endsWith(u8, path, "/v1/logs")) return error.InvalidTelemetryEndpoint;
+ const base = path[0 .. path.len - "/v1/logs".len];
+ return std.fmt.allocPrint(gpa, "{s}/v1/learning/{s}{s}", .{ base, run_id, logs_url[query_at..] });
+}
+
+fn deleteRequest(client: *std.http.Client, url: []const u8, token: []const u8) u16 {
+ const headers = [_]std.http.Header{.{ .name = "x-learning-delete-token", .value = token }};
+ const response = client.fetch(.{
+ .location = .{ .url = url },
+ .method = .DELETE,
+ .extra_headers = &headers,
+ }) catch return 0;
+ return @intFromEnum(response.status);
+}
+
+fn deleteWithDeadline(io: Io, client: *std.http.Client, url: []const u8, token: []const u8) u16 {
+ const Done = union(enum) { status: u16, deadline: void };
+ var done_buf: [2]Done = undefined;
+ var select: Io.Select(Done) = .init(io, &done_buf);
+ select.concurrent(.deadline, telemetry.Telemetry.flushDeadline, .{ io, Io.Duration.fromSeconds(10) }) catch return 0;
+ select.concurrent(.status, deleteRequest, .{ client, url, token }) catch {
+ select.cancelDiscard();
+ return 0;
+ };
+ const first = select.await() catch {
+ select.cancelDiscard();
+ return 0;
+ };
+ select.cancelDiscard();
+ return switch (first) {
+ .status => |status| status,
+ .deadline => 0,
+ };
+}
+
+pub fn command(
+ io: Io,
+ gpa: Allocator,
+ arena: Allocator,
+ environ: *const std.process.Environ.Map,
+ run_id: []const u8,
+ lock_timeout_ms: u64,
+ out: *Io.Writer,
+) !void {
+ var store = try store_mod.Store.openAt(io, Io.Dir.cwd());
+ defer store.deinit();
+ var lock = try store.acquireLock(lock_timeout_ms);
+ defer lock.deinit();
+ const bytes = try store.readRun(arena, run_id);
+ const run = try std.json.parseFromSliceLeaky(eval.RunRecord, arena, bytes, .{});
+ try eval.validateRun(run);
+ const expected_trial = learn_run.trialId(
+ run.config_id,
+ run.parent_genome_id,
+ run.parent_generation,
+ run.parent_transaction_id,
+ run.nonce,
+ );
+ if (!std.mem.eql(u8, run.trial_id, &expected_trial)) return error.TrialMismatch;
+
+ scoring.g_score_key = scoring.loadScoreKey(io, arena, environ) orelse
+ return error.ScoreSigningKeyRequired;
+ const token = receipt.deletionToken(run_id, run.nonce);
+ if (token[0] == 0) return error.ScoreSigningKeyRequired;
+ const endpoint = try submit.deletionEndpoint(environ);
+ const url = try learningUrl(gpa, endpoint, run_id);
+ defer gpa.free(url);
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ switch (deleteWithDeadline(io, &client, url, &token)) {
+ 200, 202, 204 => try out.print(
+ "deleted remote aggregate receipt for run {s}; local evidence was not changed\n",
+ .{run_id},
+ ),
+ 404 => return error.RemoteReceiptNotFoundOrUnauthorized,
+ 409 => return error.RemoteReceiptPredatesDeletion,
+ else => return error.RemoteReceiptDeletionFailed,
+ }
+}
+
+test "learning receipt URL preserves endpoint query parameters" {
+ const gpa = std.testing.allocator;
+ const run_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const url = try learningUrl(gpa, "https://collector.example/base?token=x#drop", run_id);
+ defer gpa.free(url);
+ try std.testing.expectEqualStrings(
+ "https://collector.example/base/v1/learning/" ++ run_id ++ "?token=x",
+ url,
+ );
+}
diff --git a/src/learn_diagnostics.zig b/src/learn_diagnostics.zig
new file mode 100644
index 00000000..66d11150
--- /dev/null
+++ b/src/learn_diagnostics.zig
@@ -0,0 +1,39 @@
+//! Privacy boundary for diagnostics emitted by pinned learning adapters.
+//!
+//! Raw stderr and executable paths may contain prompts, repository text,
+//! credentials, or usernames. They are hidden unless the human explicitly
+//! opts in on the local `graff learn run` command line.
+
+const std = @import("std");
+
+var detailed_value: std.atomic.Value(bool) = .init(false);
+
+pub fn setDetailed(enabled: bool) void {
+ detailed_value.store(enabled, .release);
+}
+
+pub fn detailed() bool {
+ return detailed_value.load(.acquire);
+}
+
+fn excerpt(stderr: []const u8) []const u8 {
+ return stderr[0..@min(stderr.len, 4096)];
+}
+
+pub fn reportTimeout(operation: []const u8, program: []const u8, timeout_ms: u64, stderr: []const u8) void {
+ if (!detailed()) {
+ std.debug.print("learn: {s} adapter timed out after {d} ms; private diagnostics hidden (rerun locally with --show-adapter-stderr)\n", .{ operation, timeout_ms });
+ return;
+ }
+ const shown = excerpt(stderr);
+ std.debug.print("learn: {s} adapter {s} timed out after {d} ms; raw stderr explicitly enabled ({d} of {d} bytes):\n{s}\n", .{ operation, program, timeout_ms, shown.len, stderr.len, shown });
+}
+
+pub fn reportFailure(operation: []const u8, program: []const u8, term: std.process.Child.Term, stderr: []const u8) void {
+ if (!detailed()) {
+ std.debug.print("learn: {s} adapter failed ({any}); private diagnostics hidden (rerun locally with --show-adapter-stderr)\n", .{ operation, term });
+ return;
+ }
+ const shown = excerpt(stderr);
+ std.debug.print("learn: {s} adapter {s} failed ({any}); raw stderr explicitly enabled ({d} of {d} bytes):\n{s}\n", .{ operation, program, term, shown.len, stderr.len, shown });
+}
diff --git a/src/learn_eval.zig b/src/learn_eval.zig
index 5770ebd9..bc952d8d 100644
--- a/src/learn_eval.zig
+++ b/src/learn_eval.zig
@@ -11,6 +11,7 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const jobs = @import("jobs.zig");
+const diagnostics = @import("learn_diagnostics.zig");
const store_mod = @import("learn_store.zig");
const protocol = @import("learn_eval_types.zig");
@@ -28,6 +29,7 @@ pub const GenomeRef = protocol.GenomeRef;
pub const MutationRequest = protocol.MutationRequest;
pub const MutationResponse = protocol.MutationResponse;
pub const PairRequest = protocol.PairRequest;
+pub const statisticalUnitId = protocol.statisticalUnitId;
pub const EvaluationRequest = protocol.EvaluationRequest;
pub const PairResult = protocol.PairResult;
pub const EvaluationResponse = protocol.EvaluationResponse;
@@ -222,21 +224,18 @@ pub fn invoke(
const run = try jobs.runCappedWithOptions(gpa, io, argv.items, stdout_cap, stderr_cap, timeout_ms, .{
.cwd = .{ .dir = scratch },
.environ_map = &env,
+ .kill_process_tree = true,
});
defer {
gpa.free(run.stdout);
gpa.free(run.stderr);
}
if (run.timed_out) {
- std.debug.print("learn: {s} timed out after {d} ms\n", .{ program.program, timeout_ms });
+ diagnostics.reportTimeout(operation, program.program, timeout_ms, run.stderr);
return error.ProcessTimedOut;
}
if (run.term != .exited or run.term.exited != 0) {
- // The bare error alone cost real debugging time: surface which tool
- // failed and a bounded stderr excerpt before the scratch dir (and the
- // request/response evidence in it) is deleted by the caller.
- const excerpt = run.stderr[0..@min(run.stderr.len, 4096)];
- std.debug.print("learn: {s} failed ({any}); stderr (first {d} of {d} bytes):\n{s}\n", .{ program.program, run.term, excerpt.len, run.stderr.len, excerpt });
+ diagnostics.reportFailure(operation, program.program, run.term, run.stderr);
return error.ProcessFailed;
}
}
@@ -359,13 +358,14 @@ pub fn buildPairs(gpa: Allocator, trial_id: []const u8, suite: store_mod.Suite,
}
for (0..repetitions) |repetition| {
for (manifest.cases) |case| {
- // Common random numbers: every arm receives identical primary
- // seeds for the same case/repetition, so generator identity is the
- // only intended source of between-arm variation.
+ // Stable pair identity: every arm receives the same primary seed
+ // for a case/repetition. Seed-capable adapters may use it for
+ // sampling; others can still counterbalance execution order.
const seed = pairSeed(trial_id, suite.sha256, case.id, repetition);
const seed_copy = try gpa.dupe(u8, &seed);
pairs[initialized] = .{
.case_id = case.id,
+ .statistical_unit_id = case.statistical_unit_id,
.seed = seed_copy,
.critical = case.critical,
};
@@ -479,6 +479,7 @@ pub fn comparisonEqual(a: ComparisonRecord, b: ComparisonRecord) bool {
a.parent_passes == b.parent_passes and a.child_passes == b.child_passes and
a.wins == b.wins and a.losses == b.losses and a.ties == b.ties and
a.child_critical_failures == b.child_critical_failures and a.critical_regressions == b.critical_regressions and
+ a.correctness_regressions == b.correctness_regressions and
a.delta_ppm == b.delta_ppm and a.mean_score_delta_ppm == b.mean_score_delta_ppm and a.p_value_ppb == b.p_value_ppb and
a.parent_cost_micros == b.parent_cost_micros and a.child_cost_micros == b.child_cost_micros and
a.tool_calls_measured == b.tool_calls_measured and
@@ -517,7 +518,9 @@ pub fn verifyComparison(
try validateEvaluationEnvelope(request, response, trial_id, candidate_index, &cohort, suite, parent_id, child_id, repetitions);
if (request.pairs.len != expected_pairs.len) return error.PairMismatch;
for (request.pairs, expected_pairs) |actual, expected| {
- if (!std.mem.eql(u8, actual.case_id, expected.case_id) or !std.mem.eql(u8, actual.seed, expected.seed) or actual.critical != expected.critical) return error.PairMismatch;
+ if (!std.mem.eql(u8, actual.case_id, expected.case_id) or
+ !std.mem.eql(u8, statisticalUnitId(actual), statisticalUnitId(expected)) or
+ !std.mem.eql(u8, actual.seed, expected.seed) or actual.critical != expected.critical) return error.PairMismatch;
}
const recomputed = try computeComparison(config, suite.sha256, recorded.request_evidence_id, recorded.response_evidence_id, request.pairs, response, planned_candidates);
if (!comparisonEqual(recomputed, recorded)) return error.ComparisonMismatch;
diff --git a/src/learn_eval_tests.zig b/src/learn_eval_tests.zig
index e1ffe385..0c32a963 100644
--- a/src/learn_eval_tests.zig
+++ b/src/learn_eval_tests.zig
@@ -14,6 +14,8 @@ const EvaluationResponse = learn_eval.EvaluationResponse;
const ComparisonRecord = learn_eval.ComparisonRecord;
const pairedTail = learn_eval.pairedTail;
const computeComparison = learn_eval.computeComparison;
+const buildPairs = learn_eval.buildPairs;
+const freePairs = learn_eval.freePairs;
const createScratch = learn_eval.createScratch;
const writePrivate = learn_eval.writePrivate;
const invoke = learn_eval.invoke;
@@ -82,6 +84,102 @@ test "paired gate rejects critical regressions and requires corrected significan
try std.testing.expectEqualStrings("critical_failure", jointly_failed_critical.reason);
}
+test "statistical units group repetitions and cloned case ids once" {
+ const config: store_mod.Config = .{
+ .schema = store_mod.config_schema,
+ .agent_name = "test",
+ .mutation_instruction = "change",
+ .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },
+ .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
+ .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },
+ .gate = .{ .minimum_pairs = 1 },
+ .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },
+ };
+ const requested = [_]PairRequest{
+ .{ .case_id = "clone-a", .statistical_unit_id = "edit-filter", .seed = "seed-a1", .critical = false },
+ .{ .case_id = "clone-a", .statistical_unit_id = "edit-filter", .seed = "seed-a2", .critical = false },
+ .{ .case_id = "clone-b", .statistical_unit_id = "edit-filter", .seed = "seed-b1", .critical = false },
+ .{ .case_id = "clone-b", .statistical_unit_id = "edit-filter", .seed = "seed-b2", .critical = false },
+ .{ .case_id = "independent", .seed = "seed-i1", .critical = false },
+ };
+ const results = [_]PairResult{
+ .{ .case_id = "clone-a", .seed = "seed-a1", .parent_pass = true, .child_pass = false, .parent_score_ppm = 1_000_000, .child_score_ppm = 0, .tool_calls_measured = true, .parent_tool_calls = 3, .child_tool_calls = 2 },
+ .{ .case_id = "clone-a", .seed = "seed-a2", .parent_pass = false, .child_pass = true, .parent_score_ppm = 0, .child_score_ppm = 1_000_000, .tool_calls_measured = true, .parent_tool_calls = 3, .child_tool_calls = 2 },
+ .{ .case_id = "clone-b", .seed = "seed-b1", .parent_pass = true, .child_pass = true, .parent_score_ppm = 1_000_000, .child_score_ppm = 1_000_000, .tool_calls_measured = true, .parent_tool_calls = 3, .child_tool_calls = 2 },
+ .{ .case_id = "clone-b", .seed = "seed-b2", .parent_pass = false, .child_pass = true, .parent_score_ppm = 0, .child_score_ppm = 1_000_000, .tool_calls_measured = true, .parent_tool_calls = 3, .child_tool_calls = 2 },
+ .{ .case_id = "independent", .seed = "seed-i1", .parent_pass = true, .child_pass = true, .parent_score_ppm = 1_000_000, .child_score_ppm = 1_000_000, .tool_calls_measured = true, .parent_tool_calls = 1, .child_tool_calls = 2 },
+ };
+ const response: EvaluationResponse = .{ .schema = evaluation_response_schema, .trial_id = "trial", .candidate_index = 0, .cohort_id = "cohort", .suite_sha256 = config.evaluation_suite.sha256, .parent_id = "parent", .child_id = "child", .pairs = &results };
+ const comparison = try computeComparison(config, config.evaluation_suite.sha256, "request", "response", &requested, response, 1);
+ try std.testing.expectEqual(@as(usize, 5), comparison.pairs);
+ try std.testing.expectEqual(@as(usize, 2), comparison.statistical_units);
+ try std.testing.expectEqual(@as(usize, 1), comparison.wins);
+ try std.testing.expectEqual(@as(usize, 0), comparison.losses);
+ try std.testing.expectEqual(@as(usize, 1), comparison.ties);
+ try std.testing.expectEqual(@as(usize, 1), comparison.tool_wins);
+ try std.testing.expectEqual(@as(usize, 1), comparison.tool_losses);
+ try std.testing.expectEqual(@as(usize, 0), comparison.tool_ties);
+}
+
+test "clone rows cannot satisfy minimum statistical-unit gate" {
+ var config: store_mod.Config = .{
+ .schema = store_mod.config_schema,
+ .agent_name = "test",
+ .mutation_instruction = "change",
+ .mutator = .{ .program = "/bin/a", .sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },
+ .evaluator = .{ .program = "/bin/b", .sha256 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
+ .evaluation_suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" },
+ .gate = .{ .minimum_pairs = 2 },
+ .cohort = .{ .provider = "p", .model = "m", .task_family = "t", .adapter_version = "a", .verifier_version = "v" },
+ };
+ const ids = [_][]const u8{ "clone-0", "clone-1", "clone-2", "clone-3", "clone-4", "clone-5", "clone-6", "clone-7", "clone-8", "clone-9" };
+ var requested: [10]PairRequest = undefined;
+ var results: [10]PairResult = undefined;
+ for (ids, 0..) |id, i| {
+ requested[i] = .{ .case_id = id, .statistical_unit_id = "one-scenario", .seed = "seed", .critical = false };
+ results[i] = .{ .case_id = id, .seed = "seed", .parent_pass = false, .child_pass = true, .parent_score_ppm = 0, .child_score_ppm = 1_000_000 };
+ }
+ const response: EvaluationResponse = .{ .schema = evaluation_response_schema, .trial_id = "trial", .candidate_index = 0, .cohort_id = "cohort", .suite_sha256 = config.evaluation_suite.sha256, .parent_id = "parent", .child_id = "child", .pairs = &results };
+ const comparison = try computeComparison(config, config.evaluation_suite.sha256, "request", "response", &requested, response, 1);
+ try std.testing.expectEqual(@as(usize, 1), comparison.statistical_units);
+ try std.testing.expect(!comparison.eligible);
+ try std.testing.expectEqualStrings("minimum_pairs", comparison.reason);
+
+ config.gate.minimum_pairs = 1;
+ config.gate.economy_gate_enabled = true;
+ config.gate.promotion_mode = .economy;
+ config.gate.minimum_economy_pairs = 2;
+ for (&results) |*result| {
+ result.parent_pass = true;
+ result.child_pass = true;
+ result.parent_score_ppm = 1_000_000;
+ result.tool_calls_measured = true;
+ result.parent_tool_calls = 2;
+ result.child_tool_calls = 1;
+ }
+ const economy = try computeComparison(config, config.evaluation_suite.sha256, "request", "response", &requested, response, 1);
+ try std.testing.expectEqualStrings("minimum_economy_pairs", economy.reason);
+}
+
+test "buildPairs preserves statistical units while repetition seeds stay distinct" {
+ const cases = [_]store_mod.SuiteCase{
+ .{ .id = "clone-a", .statistical_unit_id = "scenario" },
+ .{ .id = "clone-b", .statistical_unit_id = "scenario" },
+ };
+ const manifest: store_mod.SuiteManifest = .{
+ .schema = store_mod.suite_schema,
+ .suite_id = "suite",
+ .cases = &cases,
+ };
+ const suite: store_mod.Suite = .{ .path = "/suite", .sha256 = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" };
+ const pairs = try buildPairs(std.testing.allocator, "trial", suite, manifest, 0, 2);
+ defer freePairs(std.testing.allocator, pairs);
+ try std.testing.expectEqual(@as(usize, 4), pairs.len);
+ for (pairs) |pair| try std.testing.expectEqualStrings("scenario", learn_eval.statisticalUnitId(pair));
+ try std.testing.expect(!std.mem.eql(u8, pairs[0].seed, pairs[2].seed));
+ try std.testing.expect(!std.mem.eql(u8, pairs[1].seed, pairs[3].seed));
+}
+
test "economy gate requires corrected per-case evidence without correctness loss" {
const config: store_mod.Config = .{
.schema = store_mod.config_schema,
@@ -125,6 +223,7 @@ test "economy gate requires corrected per-case evidence without correctness loss
const strong = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);
try std.testing.expect(strong.eligible);
try std.testing.expect(strong.economy_eligible);
+ try std.testing.expectEqual(@as(usize, 0), strong.correctness_regressions);
try std.testing.expectEqualStrings("economy_eligible", strong.reason);
try std.testing.expectEqual(@as(usize, 8), strong.tool_wins);
try std.testing.expectEqual(@as(u64, 40), strong.parent_latency_ms);
@@ -177,6 +276,35 @@ test "economy gate requires corrected per-case evidence without correctness loss
const noncritical_trade = try computeComparison(config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);
try std.testing.expect(!noncritical_trade.eligible);
try std.testing.expectEqualStrings("correctness_regression", noncritical_trade.reason);
+
+ // A regression and improvement inside one repeated/related unit cancel in
+ // the unit-level sign test, but economy mode must still reject the raw
+ // regression rather than trading correctness for lower tool use.
+ var grouped_config = config;
+ grouped_config.gate.minimum_pairs = 7;
+ for (&requested, &results) |*pair, *result| {
+ pair.critical = false;
+ pair.statistical_unit_id = null;
+ result.parent_pass = true;
+ result.child_pass = true;
+ result.parent_score_ppm = 1_000_000;
+ result.child_score_ppm = 1_000_000;
+ result.tool_calls_measured = true;
+ result.parent_tool_calls = 2;
+ result.child_tool_calls = 1;
+ }
+ requested[0].statistical_unit_id = "traded-unit";
+ requested[1].statistical_unit_id = "traded-unit";
+ results[0].child_pass = false;
+ results[0].child_score_ppm = 0;
+ results[1].parent_pass = false;
+ results[1].parent_score_ppm = 0;
+ const hidden_trade = try computeComparison(grouped_config, config.evaluation_suite.sha256, "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "1111111111111111111111111111111111111111111111111111111111111111", &requested, response, 4);
+ try std.testing.expectEqual(@as(usize, 7), hidden_trade.statistical_units);
+ try std.testing.expectEqual(@as(usize, 0), hidden_trade.losses);
+ try std.testing.expectEqual(@as(usize, 1), hidden_trade.correctness_regressions);
+ try std.testing.expect(!hidden_trade.economy_eligible);
+ try std.testing.expectEqualStrings("correctness_regression", hidden_trade.reason);
}
test "tool invocation executes verified private program and input snapshots" {
diff --git a/src/learn_eval_types.zig b/src/learn_eval_types.zig
index a1f9d84d..54af0338 100644
--- a/src/learn_eval_types.zig
+++ b/src/learn_eval_types.zig
@@ -39,10 +39,15 @@ pub const MutationResponse = struct {
pub const PairRequest = struct {
case_id: []const u8,
+ statistical_unit_id: ?[]const u8 = null,
seed: []const u8,
critical: bool,
};
+pub fn statisticalUnitId(pair: PairRequest) []const u8 {
+ return pair.statistical_unit_id orelse pair.case_id;
+}
+
pub const EvaluationRequest = struct {
schema: []const u8,
trial_id: []const u8,
@@ -177,6 +182,9 @@ pub const ComparisonRecord = struct {
ties: usize,
child_critical_failures: usize = 0,
critical_regressions: usize,
+ /// Raw parent-pass/child-fail rows before repetitions or related cases are
+ /// collapsed into statistical units. Economy promotion requires zero.
+ correctness_regressions: usize = 0,
delta_ppm: i64,
mean_score_delta_ppm: i64,
p_value_ppb: u64,
diff --git a/src/learn_holdout.zig b/src/learn_holdout.zig
index 33f69c71..3cef21e8 100644
--- a/src/learn_holdout.zig
+++ b/src/learn_holdout.zig
@@ -1,8 +1,8 @@
//! One-use reservations for hidden learning suites.
//!
//! The marker is created before evaluator invocation. A crash after exposure
-//! therefore leaves the suite consumed, which is safer than silently reusing a
-//! holdout until it passes.
+//! may resume only the same checkpointed trial; every different trial sees the
+//! suite as consumed.
const std = @import("std");
const builtin = @import("builtin");
@@ -53,6 +53,22 @@ pub fn reserve(io: Io, root: Io.Dir, suite_sha256: []const u8, trial_id: []const
try store.syncDirectory(io, root);
}
+/// New trials fail before invoking a mutator or evaluator when their hidden
+/// suite was already exposed. The engine lock makes this check race-free with
+/// reserve() inside one learning store. Resumes deliberately skip it and
+/// verify the existing reservation against their original trial instead.
+pub fn ensureUnused(io: Io, root: Io.Dir, suite_sha256: []const u8) !void {
+ var name_buffer: [69]u8 = undefined;
+ const name = try markerName(suite_sha256, &name_buffer);
+ const reservations = try openReservations(io, root);
+ defer reservations.close(io);
+ reservations.access(io, name, .{}) catch |err| switch (err) {
+ error.FileNotFound => return,
+ else => return err,
+ };
+ return error.HoldoutConsumed;
+}
+
pub fn verify(io: Io, root: Io.Dir, allocator: Allocator, suite_sha256: []const u8, trial_id: []const u8) !void {
if (!store.validId(trial_id)) return error.InvalidId;
var name_buffer: [69]u8 = undefined;
@@ -65,14 +81,30 @@ pub fn verify(io: Io, root: Io.Dir, allocator: Allocator, suite_sha256: []const
return error.HoldoutReservationMismatch;
}
+/// Resume may revisit an already exposed holdout only for the exact trial that
+/// created its durable reservation. A different trial still fails closed.
+pub fn reserveOrVerify(io: Io, root: Io.Dir, allocator: Allocator, suite_sha256: []const u8, trial_id: []const u8) !void {
+ reserve(io, root, suite_sha256, trial_id) catch |err| switch (err) {
+ error.HoldoutConsumed => verify(io, root, allocator, suite_sha256, trial_id) catch |verify_err| switch (verify_err) {
+ error.HoldoutReservationMismatch => return error.HoldoutConsumed,
+ else => return verify_err,
+ },
+ else => return err,
+ };
+}
+
test "hidden suite reservations are durable and one-use" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const suite = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const trial = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
+ try ensureUnused(io, tmp.dir, suite);
try reserve(io, tmp.dir, suite, trial);
+ try std.testing.expectError(error.HoldoutConsumed, ensureUnused(io, tmp.dir, suite));
try verify(io, tmp.dir, std.testing.allocator, suite, trial);
+ try reserveOrVerify(io, tmp.dir, std.testing.allocator, suite, trial);
try std.testing.expectError(error.HoldoutConsumed, reserve(io, tmp.dir, suite, trial));
+ try std.testing.expectError(error.HoldoutConsumed, reserveOrVerify(io, tmp.dir, std.testing.allocator, suite, "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"));
try std.testing.expectError(error.HoldoutReservationMismatch, verify(io, tmp.dir, std.testing.allocator, suite, "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"));
}
diff --git a/src/learn_mutation_verify.zig b/src/learn_mutation_verify.zig
new file mode 100644
index 00000000..6fd638fe
--- /dev/null
+++ b/src/learn_mutation_verify.zig
@@ -0,0 +1,39 @@
+//! Re-verification of immutable mutation evidence shared by final-run and
+//! pending-checkpoint validation.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const eval = @import("learn_eval.zig");
+const store_mod = @import("learn_store.zig");
+
+pub fn verify(
+ arena: Allocator,
+ store: *store_mod.Store,
+ config: store_mod.Config,
+ trial_id: []const u8,
+ parent_genome_id: []const u8,
+ index: usize,
+ candidate: eval.CandidateRecord,
+) !void {
+ const expected_seed = eval.candidateSeed(trial_id, index);
+ if (!std.mem.eql(u8, candidate.mutation.seed, &expected_seed)) return error.MutationMismatch;
+ const request_bytes = try store.readEvidence(arena, candidate.mutation.request_evidence_id, config.limits.request_bytes);
+ const response_bytes = try store.readEvidence(arena, candidate.mutation.response_evidence_id, config.limits.response_bytes);
+ const request = try std.json.parseFromSliceLeaky(eval.MutationRequest, arena, request_bytes, .{});
+ const response = try std.json.parseFromSliceLeaky(eval.MutationResponse, arena, response_bytes, .{});
+ if (!std.mem.eql(u8, request.schema, eval.mutation_request_schema) or
+ !std.mem.eql(u8, request.trial_id, trial_id) or request.candidate_index != index or
+ !std.mem.eql(u8, request.seed, &expected_seed) or !std.mem.eql(u8, request.parent.id, parent_genome_id) or
+ !std.mem.eql(u8, request.parent.path, "parent.genome") or !std.mem.eql(u8, request.child_path, "child.genome") or
+ request.maximum_bytes != config.limits.genome_bytes or !std.mem.eql(u8, request.instruction, config.mutation_instruction)) return error.MutationMismatch;
+ if (!std.mem.eql(u8, response.schema, eval.mutation_response_schema) or
+ !std.mem.eql(u8, response.trial_id, trial_id) or response.candidate_index != index or
+ !std.mem.eql(u8, response.parent_id, parent_genome_id) or !std.mem.eql(u8, response.child_path, "child.genome") or
+ !store_mod.validId(response.child_sha256) or response.description.len > 512 or
+ !std.unicode.utf8ValidateSlice(response.description) or std.mem.indexOfScalar(u8, response.description, 0) != null or
+ !std.mem.eql(u8, response.description, candidate.mutation.description)) return error.MutationMismatch;
+ const child = try store.readGenome(arena, candidate.genome_id, config.limits.genome_bytes);
+ if (candidate.mutation.genome_bytes != child.len) return error.MutationOutputMismatch;
+ const child_sha256 = store_mod.rawSha256(child);
+ if (!std.mem.eql(u8, response.child_sha256, &child_sha256)) return error.MutationOutputMismatch;
+}
diff --git a/src/learn_primary.zig b/src/learn_primary.zig
index 4bd6e737..a412f51b 100644
--- a/src/learn_primary.zig
+++ b/src/learn_primary.zig
@@ -17,6 +17,7 @@ fn validateRequestedPairs(actual: []const eval.PairRequest, expected: []const ev
if (actual.len != expected.len) return error.PairMismatch;
for (actual, expected) |got, want| {
if (!std.mem.eql(u8, got.case_id, want.case_id) or
+ !std.mem.eql(u8, eval.statisticalUnitId(got), eval.statisticalUnitId(want)) or
!std.mem.eql(u8, got.seed, want.seed) or got.critical != want.critical) return error.PairMismatch;
}
}
diff --git a/src/learn_receipt.zig b/src/learn_receipt.zig
new file mode 100644
index 00000000..b8a2864e
--- /dev/null
+++ b/src/learn_receipt.zig
@@ -0,0 +1,249 @@
+//! Versioned, signed aggregate receipt for one verified learning comparison.
+//! The contract intentionally has no fields for prompts, paths, task payloads,
+//! adapter output, or arbitrary metadata.
+
+const std = @import("std");
+const eval = @import("learn_eval.zig");
+const scoring = @import("scoring.zig");
+const store = @import("learn_store.zig");
+
+pub const schema = "codegraff.learn.grade.v2";
+pub const delete_token_domain = "codegraff.learn.delete.v1\n";
+
+pub const Grade = struct {
+ pairs: usize,
+ statistical_units: usize,
+ parent_passes: usize,
+ child_passes: usize,
+ child_critical_failures: usize,
+ critical_regressions: usize,
+ correctness_regressions: usize,
+ delta_ppm: i64,
+ mean_score_delta_ppm: i64,
+ p_value_ppb: u64,
+ tool_calls_measured: bool,
+ parent_tool_calls: u64,
+ child_tool_calls: u64,
+ tool_wins: usize,
+ tool_losses: usize,
+ tool_ties: usize,
+ tool_delta_ppm: i64,
+ tool_p_value_ppb: u64,
+ parent_cost_micros: u64,
+ child_cost_micros: u64,
+ latency_measured: bool,
+ parent_latency_ms: u64,
+ child_latency_ms: u64,
+ economy_eligible: bool,
+ eligible: bool,
+ economy_gate_enabled: bool,
+ alpha_ppm: u32,
+ minimum_delta_ppm: u32,
+ minimum_pairs: usize,
+ minimum_tool_reduction_ppm: u32,
+ minimum_economy_pairs: usize,
+ multiplicity: usize,
+ reason: []const u8,
+ promotion_mode: []const u8,
+};
+
+pub fn fromComparison(gate: store.Gate, comparison: eval.ComparisonRecord, multiplicity: usize) Grade {
+ return .{
+ .pairs = comparison.pairs,
+ .statistical_units = comparison.statistical_units,
+ .parent_passes = comparison.parent_passes,
+ .child_passes = comparison.child_passes,
+ .child_critical_failures = comparison.child_critical_failures,
+ .critical_regressions = comparison.critical_regressions,
+ .correctness_regressions = comparison.correctness_regressions,
+ .delta_ppm = comparison.delta_ppm,
+ .mean_score_delta_ppm = comparison.mean_score_delta_ppm,
+ .p_value_ppb = comparison.p_value_ppb,
+ .tool_calls_measured = comparison.tool_calls_measured,
+ .parent_tool_calls = comparison.parent_tool_calls,
+ .child_tool_calls = comparison.child_tool_calls,
+ .tool_wins = comparison.tool_wins,
+ .tool_losses = comparison.tool_losses,
+ .tool_ties = comparison.tool_ties,
+ .tool_delta_ppm = comparison.tool_delta_ppm,
+ .tool_p_value_ppb = comparison.tool_p_value_ppb,
+ .parent_cost_micros = comparison.parent_cost_micros,
+ .child_cost_micros = comparison.child_cost_micros,
+ .latency_measured = comparison.latency_measured,
+ .parent_latency_ms = comparison.parent_latency_ms,
+ .child_latency_ms = comparison.child_latency_ms,
+ .economy_eligible = comparison.economy_eligible,
+ .eligible = comparison.eligible,
+ .economy_gate_enabled = gate.economy_gate_enabled,
+ .alpha_ppm = gate.alpha_ppm,
+ .minimum_delta_ppm = gate.minimum_delta_ppm,
+ .minimum_pairs = gate.minimum_pairs,
+ .minimum_tool_reduction_ppm = gate.minimum_tool_reduction_ppm,
+ .minimum_economy_pairs = gate.minimum_economy_pairs,
+ .multiplicity = multiplicity,
+ .reason = comparison.reason,
+ .promotion_mode = @tagName(gate.promotion_mode),
+ };
+}
+
+fn format(
+ buffer: []u8,
+ separator: u8,
+ prefix: []const u8,
+ prompt_sha: []const u8,
+ parent_sha: []const u8,
+ value: f64,
+ run_id: []const u8,
+ judge_id: []const u8,
+ artifact_sha: []const u8,
+ eval_set_hash: []const u8,
+ niche: []const u8,
+ provider_class: []const u8,
+ delete_token: []const u8,
+ run_created_unix_ms: i64,
+ grade: Grade,
+) ?[]const u8 {
+ var writer = std.Io.Writer.fixed(buffer);
+ writer.print("{s}{c}{s}{c}{s}{c}{d:.6}{c}{s}{c}{s}{c}{s}{c}{s}{c}{s}{c}{s}", .{
+ prefix, separator, prompt_sha, separator, parent_sha, separator, value,
+ separator, run_id, separator, judge_id, separator, artifact_sha, separator,
+ eval_set_hash, separator, niche, separator, provider_class,
+ }) catch return null;
+ writer.print("{c}{s}{c}{d}", .{ separator, delete_token, separator, run_created_unix_ms }) catch return null;
+ const metrics = [_]i64{
+ @intCast(grade.pairs),
+ @intCast(grade.statistical_units),
+ @intCast(grade.parent_passes),
+ @intCast(grade.child_passes),
+ @intCast(grade.child_critical_failures),
+ @intCast(grade.critical_regressions),
+ @intCast(grade.correctness_regressions),
+ grade.delta_ppm,
+ grade.mean_score_delta_ppm,
+ @intCast(grade.p_value_ppb),
+ @intFromBool(grade.tool_calls_measured),
+ @intCast(grade.parent_tool_calls),
+ @intCast(grade.child_tool_calls),
+ @intCast(grade.tool_wins),
+ @intCast(grade.tool_losses),
+ @intCast(grade.tool_ties),
+ grade.tool_delta_ppm,
+ @intCast(grade.tool_p_value_ppb),
+ @intCast(grade.parent_cost_micros),
+ @intCast(grade.child_cost_micros),
+ @intFromBool(grade.latency_measured),
+ @intCast(grade.parent_latency_ms),
+ @intCast(grade.child_latency_ms),
+ @intFromBool(grade.economy_eligible),
+ @intFromBool(grade.eligible),
+ @intFromBool(grade.economy_gate_enabled),
+ grade.alpha_ppm,
+ grade.minimum_delta_ppm,
+ @intCast(grade.minimum_pairs),
+ grade.minimum_tool_reduction_ppm,
+ @intCast(grade.minimum_economy_pairs),
+ @intCast(grade.multiplicity),
+ };
+ for (metrics) |metric| writer.print("{c}{d}", .{ separator, metric }) catch return null;
+ writer.print("{c}{s}{c}{s}", .{ separator, grade.reason, separator, grade.promotion_mode }) catch return null;
+ return writer.buffered();
+}
+
+pub fn message(buffer: []u8, prompt_sha: []const u8, parent_sha: []const u8, value: f64, run_id: []const u8, judge_id: []const u8, artifact_sha: []const u8, eval_set_hash: []const u8, niche: []const u8, provider_class: []const u8, delete_token: []const u8, run_created_unix_ms: i64, grade: Grade) ?[]const u8 {
+ return format(buffer, '\n', schema, prompt_sha, parent_sha, value, run_id, judge_id, artifact_sha, eval_set_hash, niche, provider_class, delete_token, run_created_unix_ms, grade);
+}
+
+pub fn sign(prompt_sha: []const u8, parent_sha: []const u8, value: f64, run_id: []const u8, judge_id: []const u8, artifact_sha: []const u8, eval_set_hash: []const u8, niche: []const u8, provider_class: []const u8, delete_token: []const u8, run_created_unix_ms: i64, grade: Grade) [64]u8 {
+ const key = scoring.g_score_key orelse return @splat(0);
+ var buffer: [2304]u8 = undefined;
+ const bytes = message(&buffer, prompt_sha, parent_sha, value, run_id, judge_id, artifact_sha, eval_set_hash, niche, provider_class, delete_token, run_created_unix_ms, grade) orelse return @splat(0);
+ var mac: [std.crypto.auth.hmac.sha2.HmacSha256.mac_length]u8 = undefined;
+ std.crypto.auth.hmac.sha2.HmacSha256.create(&mac, bytes, key);
+ return std.fmt.bytesToHex(mac, .lower);
+}
+
+/// Run-scoped bearer capability. The immutable run nonce never leaves the
+/// machine, so possession of the shared score key plus a leaked run id is not
+/// enough to delete a receipt.
+pub fn deletionToken(run_id: []const u8, nonce: []const u8) [64]u8 {
+ const key = scoring.g_score_key orelse return @splat(0);
+ var buffer: [192]u8 = undefined;
+ const bytes = std.fmt.bufPrint(&buffer, delete_token_domain ++ "{s}\n{s}", .{ run_id, nonce }) catch return @splat(0);
+ var mac: [std.crypto.auth.hmac.sha2.HmacSha256.mac_length]u8 = undefined;
+ std.crypto.auth.hmac.sha2.HmacSha256.create(&mac, bytes, key);
+ return std.fmt.bytesToHex(mac, .lower);
+}
+
+pub fn provenance(buffer: []u8, judge_id: []const u8, artifact_sha: []const u8, eval_set_hash: []const u8, provider_class: []const u8, niche: []const u8, grade_signature: []const u8, delete_token: []const u8, run_created_unix_ms: i64, grade: Grade) ?[]const u8 {
+ var detail_buffer: [1792]u8 = undefined;
+ const detail = format(&detail_buffer, '\t', schema, "", "", 0, "", "", "", "", "", "", delete_token, run_created_unix_ms, grade) orelse return null;
+ // Drop the empty core fields and fixed 0.000000 value; the ordinary score
+ // transport already carries them. Keep the schema and all signed metrics.
+ var parts = std.mem.splitScalar(u8, detail, '\t');
+ const receipt_schema = parts.next() orelse return null;
+ var skipped: usize = 0;
+ while (skipped < 9) : (skipped += 1) _ = parts.next() orelse return null;
+ const metrics = parts.rest();
+ return std.fmt.bufPrint(buffer, "{s}\t{s}\t{s}\t{s}\t{s}\t{s}\t{s}\t{s}", .{
+ judge_id, artifact_sha, eval_set_hash, provider_class, niche, receipt_schema, grade_signature, metrics,
+ }) catch null;
+}
+
+test "learning grade message is deterministic and prompt-free" {
+ const grade: Grade = .{
+ .pairs = 20,
+ .statistical_units = 20,
+ .parent_passes = 10,
+ .child_passes = 15,
+ .child_critical_failures = 0,
+ .critical_regressions = 0,
+ .correctness_regressions = 0,
+ .delta_ppm = 250_000,
+ .mean_score_delta_ppm = 100_000,
+ .p_value_ppb = 7_812_500,
+ .tool_calls_measured = true,
+ .parent_tool_calls = 100,
+ .child_tool_calls = 80,
+ .tool_wins = 8,
+ .tool_losses = 1,
+ .tool_ties = 11,
+ .tool_delta_ppm = 200_000,
+ .tool_p_value_ppb = 19_531_250,
+ .parent_cost_micros = 200,
+ .child_cost_micros = 180,
+ .latency_measured = true,
+ .parent_latency_ms = 400,
+ .child_latency_ms = 350,
+ .economy_eligible = false,
+ .eligible = true,
+ .economy_gate_enabled = false,
+ .alpha_ppm = 50_000,
+ .minimum_delta_ppm = 50_000,
+ .minimum_pairs = 20,
+ .minimum_tool_reduction_ppm = 100_000,
+ .minimum_economy_pairs = 8,
+ .multiplicity = 4,
+ .reason = "eligible",
+ .promotion_mode = "correctness",
+ };
+ var buffer: [2048]u8 = undefined;
+ const prompt = "aaaaaaaaaaaaaaaa";
+ const parent = "bbbbbbbbbbbbbbbb";
+ const run = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
+ const artifact = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
+ const suite = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
+ const niche = "ffffffffffffffff";
+ const delete_token = "1111111111111111111111111111111111111111111111111111111111111111";
+ const created_unix_ms: i64 = 1_784_700_000_000;
+ const bytes = message(&buffer, prompt, parent, 0.75, run, "learn-primary-v2", artifact, suite, niche, "frontier", delete_token, created_unix_ms, grade).?;
+ try std.testing.expect(std.mem.startsWith(u8, bytes, schema ++ "\naaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbb\n0.750000\n"));
+ try std.testing.expect(std.mem.indexOf(u8, bytes, "private prompt") == null);
+ const saved_key = scoring.g_score_key;
+ defer scoring.g_score_key = saved_key;
+ scoring.g_score_key = "test-key";
+ const signature = sign(prompt, parent, 0.75, run, "learn-primary-v2", artifact, suite, niche, "frontier", delete_token, created_unix_ms, grade);
+ try std.testing.expectEqualStrings("e4d78b0a0236fb9719272a016f41685a10d93a4f488cb704e0f7f8c963b546bb", &signature);
+
+ const token = deletionToken(run, "2222222222222222222222222222222222222222222222222222222222222222");
+ try std.testing.expectEqualStrings("5abd1867608b678b6679e00f24f7f457eccef7977a4df149f03c002a1885f5d9", &token);
+}
diff --git a/src/learn_report.zig b/src/learn_report.zig
index c2443aa6..e2cd9d23 100644
--- a/src/learn_report.zig
+++ b/src/learn_report.zig
@@ -7,10 +7,12 @@ const eval = @import("learn_eval.zig");
fn writeComparison(out: *Io.Writer, label: []const u8, comparison: eval.ComparisonRecord) !void {
try out.print(
- " {s}: pass {d}/{d} -> {d}/{d}; delta {d} ppm; " ++
- "wins/losses/ties {d}/{d}/{d}; p {d} ppb; ",
+ " {s}: {d} pairs; {d} independent units; pass {d}/{d} -> {d}/{d}; delta {d} ppm; " ++
+ "wins/losses/ties {d}/{d}/{d}; regressions {d}; p {d} ppb; ",
.{
label,
+ comparison.pairs,
+ comparison.statistical_units,
comparison.parent_passes,
comparison.pairs,
comparison.child_passes,
@@ -19,6 +21,7 @@ fn writeComparison(out: *Io.Writer, label: []const u8, comparison: eval.Comparis
comparison.wins,
comparison.losses,
comparison.ties,
+ comparison.correctness_regressions,
comparison.p_value_ppb,
},
);
@@ -48,7 +51,6 @@ fn writeComparison(out: *Io.Writer, label: []const u8, comparison: eval.Comparis
pub fn writeCandidateSummary(out: *Io.Writer, candidates: []const eval.CandidateRecord) !void {
for (candidates, 0..) |candidate, index| {
try out.print("candidate {d} {s}", .{ index + 1, candidate.genome_id });
- if (candidate.mutation.description.len > 0) try out.print(" ({s})", .{candidate.mutation.description});
if (candidate.mutation.genome_bytes > 0) try out.print(" [{d} bytes]", .{candidate.mutation.genome_bytes});
try out.writeByte('\n');
if (candidate.primary) |primary|
@@ -76,6 +78,7 @@ test "candidate summary reports actionable aggregate evidence without content" {
.losses = 0,
.ties = 14,
.critical_regressions = 0,
+ .correctness_regressions = 1,
.delta_ppm = 66_666,
.mean_score_delta_ppm = 66_666,
.p_value_ppb = 500_000_000,
@@ -97,7 +100,12 @@ test "candidate summary reports actionable aggregate evidence without content" {
};
const candidates = [_]eval.CandidateRecord{.{
.genome_id = "child-fingerprint",
- .mutation = .{ .seed = "seed", .request_evidence_id = "mutation-request", .response_evidence_id = "mutation-response" },
+ .mutation = .{
+ .seed = "seed",
+ .request_evidence_id = "mutation-request",
+ .response_evidence_id = "mutation-response",
+ .description = "PRIVATE_MUTATOR_OUTPUT_DO_NOT_RENDER",
+ },
.primary = comparison,
.holdout = null,
.eligible = false,
@@ -107,10 +115,13 @@ test "candidate summary reports actionable aggregate evidence without content" {
defer allocating.deinit();
try writeCandidateSummary(&allocating.writer, &candidates);
const rendered = allocating.written();
+ try std.testing.expect(std.mem.indexOf(u8, rendered, "15 pairs; 15 independent units") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "pass 14/15 -> 15/15") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "wins/losses/ties 1/0/14") != null);
+ try std.testing.expect(std.mem.indexOf(u8, rendered, "regressions 1") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "calls 23 -> 29") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "latency 100 -> 80 ms") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "decision: not_significant") != null);
try std.testing.expect(std.mem.indexOf(u8, rendered, "suite") == null);
+ try std.testing.expect(std.mem.indexOf(u8, rendered, "PRIVATE_MUTATOR_OUTPUT_DO_NOT_RENDER") == null);
}
diff --git a/src/learn_run.zig b/src/learn_run.zig
index beccf0ba..de5c19a2 100644
--- a/src/learn_run.zig
+++ b/src/learn_run.zig
@@ -5,8 +5,10 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const build_options = @import("build_options");
+const checkpoint = @import("learn_checkpoint.zig");
const eval = @import("learn_eval.zig");
const holdout = @import("learn_holdout.zig");
+const mutation_verify = @import("learn_mutation_verify.zig");
const primary = @import("learn_primary.zig");
const report = @import("learn_report.zig");
const store_mod = @import("learn_store.zig");
@@ -19,6 +21,8 @@ pub const Options = struct {
repetitions: ?usize,
submit: bool,
auto: bool,
+ resume_run: bool,
+ restart: bool,
};
pub const Result = struct {
@@ -68,8 +72,17 @@ fn mutationTask(
) anyerror!MutationTaskResult {
var task_arena = std.heap.ArenaAllocator.init(gpa);
errdefer task_arena.deinit();
- const outcome = try eval.mutate(gpa, task_arena.allocator(), io, environ, store, config, trial_id, index, parent_id, parent_prompt);
- return .{ .arena = task_arena, .outcome = outcome };
+ var attempt: usize = 0;
+ while (true) : (attempt += 1) {
+ const outcome = eval.mutate(gpa, task_arena.allocator(), io, environ, store, config, trial_id, index, parent_id, parent_prompt) catch |err| switch (err) {
+ // A new mutate call creates a new private scratch directory. Keep
+ // the registered arm identity and seed, but trust none of the
+ // failed process's partial files.
+ error.ProcessFailed, error.ProcessTimedOut => if (attempt == 0) continue else return err,
+ else => return err,
+ };
+ return .{ .arena = task_arena, .outcome = outcome };
+ }
}
const EvaluationTaskResult = struct {
@@ -129,14 +142,193 @@ fn mutationIsDuplicate(parent_id: []const u8, candidates: []const eval.Candidate
fn verifyPins(io: Io, arena: Allocator, config: store_mod.Config) !void {
try store_mod.verifyProgram(io, config.mutator);
try store_mod.verifyProgram(io, config.evaluator);
- _ = try store_mod.loadSuite(io, arena, config.evaluation_suite);
- if (config.holdout_suite) |suite| _ = try store_mod.loadSuite(io, arena, suite);
+ const primary_suite = try store_mod.loadSuite(io, arena, config.evaluation_suite);
+ try store_mod.validateSuitePower(primary_suite.manifest, config.gate);
+ if (config.holdout_suite) |suite| {
+ const holdout_suite = try store_mod.loadSuite(io, arena, suite);
+ try store_mod.validateHoldoutIndependence(config.evaluation_suite.sha256, primary_suite.manifest, suite.sha256, holdout_suite.manifest);
+ try store_mod.validateSuitePower(holdout_suite.manifest, config.gate);
+ }
+}
+
+pub fn verifyTrialPower(io: Io, arena: Allocator, config: store_mod.Config, planned_candidates: usize) !void {
+ const primary_suite = try store_mod.loadSuite(io, arena, config.evaluation_suite);
+ try store_mod.validateSuiteTrialPower(primary_suite.manifest, config.gate, planned_candidates);
+ if (config.holdout_suite) |suite| {
+ const holdout_suite = try store_mod.loadSuite(io, arena, suite);
+ try store_mod.validateHoldoutIndependence(config.evaluation_suite.sha256, primary_suite.manifest, suite.sha256, holdout_suite.manifest);
+ try store_mod.validateSuiteTrialPower(holdout_suite.manifest, config.gate, 1);
+ }
}
fn requireCompleteCandidateSet(required: bool, planned: usize, actual: usize) !void {
if (required and actual != planned) return error.IncompleteCandidateSet;
}
+fn copyMutationCandidate(arena: Allocator, outcome: eval.MutationOutcome) !eval.CandidateRecord {
+ return .{
+ .genome_id = try arena.dupe(u8, &outcome.genome_id),
+ .mutation = .{
+ .seed = try arena.dupe(u8, outcome.record.seed),
+ .request_evidence_id = try arena.dupe(u8, outcome.record.request_evidence_id),
+ .response_evidence_id = try arena.dupe(u8, outcome.record.response_evidence_id),
+ .description = try arena.dupe(u8, outcome.record.description),
+ .genome_bytes = outcome.record.genome_bytes,
+ },
+ .primary = null,
+ .holdout = null,
+ .eligible = false,
+ .reason = "unevaluated",
+ };
+}
+
+fn progressRecord(
+ config: store_mod.LoadedConfig,
+ active: store_mod.LoadedActive,
+ nonce: []const u8,
+ trial_id: []const u8,
+ created_unix_ms: i64,
+ candidate_count: usize,
+ repetitions: usize,
+ auto_requested: bool,
+ primary_baseline: ?eval.PrimaryBaselineRecord,
+ candidates: []const eval.CandidateRecord,
+) checkpoint.Record {
+ return .{
+ .trial_id = trial_id,
+ .nonce = nonce,
+ .created_unix_ms = created_unix_ms,
+ .harness_version = build_options.version,
+ .config_id = &config.id,
+ .parent_genome_id = active.ref.genome_id,
+ .parent_generation = active.ref.generation,
+ .parent_transaction_id = active.ref.transaction_id,
+ .planned_candidates = candidate_count,
+ .repetitions = repetitions,
+ .auto_requested = auto_requested,
+ .primary_baseline = primary_baseline,
+ .candidates = candidates,
+ };
+}
+
+fn verifyRestoredProgress(
+ arena: Allocator,
+ io: Io,
+ store: *store_mod.Store,
+ config: store_mod.LoadedConfig,
+ active: store_mod.LoadedActive,
+ record: checkpoint.Record,
+ candidates: []eval.CandidateRecord,
+) !void {
+ var baseline_response: ?eval.PrimaryBaselineResponse = null;
+ if (record.primary_baseline) |baseline| baseline_response = try primary.verifyBaseline(
+ arena,
+ io,
+ store,
+ config.value,
+ &config.id,
+ build_options.version,
+ record.trial_id,
+ active.ref.genome_id,
+ config.value.evaluation_suite,
+ record.repetitions,
+ baseline,
+ );
+
+ var unique_count: usize = 0;
+ var completed_primary: usize = 0;
+ for (candidates, 0..) |*candidate, index| {
+ try mutation_verify.verify(arena, store, config.value, record.trial_id, active.ref.genome_id, index, candidate.*);
+ if (mutationIsDuplicate(active.ref.genome_id, candidates, index)) |reason| {
+ if (candidate.primary != null or candidate.holdout != null) return error.InvalidPendingTopology;
+ candidate.reason = reason;
+ continue;
+ }
+ unique_count += 1;
+ if (candidate.primary) |comparison| {
+ const baseline = record.primary_baseline orelse return error.MissingPrimaryBaseline;
+ candidate.primary = try primary.verifyCandidate(
+ arena,
+ io,
+ store,
+ config.value,
+ &config.id,
+ build_options.version,
+ record.trial_id,
+ index,
+ active.ref.genome_id,
+ candidate.genome_id,
+ config.value.evaluation_suite,
+ record.repetitions,
+ record.planned_candidates,
+ baseline,
+ baseline_response orelse return error.MissingPrimaryBaseline,
+ comparison,
+ );
+ completed_primary += 1;
+ candidate.reason = candidate.primary.?.reason;
+ } else candidate.reason = "unevaluated";
+ }
+ if (unique_count == 0 and record.primary_baseline != null) return error.PrimaryBaselineTopologyMismatch;
+
+ var holdout_count: usize = 0;
+ for (candidates) |candidate| if (candidate.holdout != null) {
+ holdout_count += 1;
+ };
+ if (record.primary_baseline == null) {
+ if (completed_primary != 0 or holdout_count != 0) return error.PrimaryBaselineTopologyMismatch;
+ return;
+ }
+ if (holdout_count == 0) return;
+ if (holdout_count != 1 or completed_primary != unique_count) return error.InvalidPendingTopology;
+ const winner_index = tournament.primaryWinnerIndex(active.ref.genome_id, candidates) orelse return error.InvalidPendingTopology;
+ if (!candidates[winner_index].primary.?.eligible or candidates[winner_index].holdout == null) return error.InvalidPendingTopology;
+ for (candidates, 0..) |*candidate, index| {
+ if (candidate.holdout) |comparison| {
+ if (index != winner_index) return error.InvalidPendingTopology;
+ const suite = config.value.holdout_suite orelse return error.InvalidPendingTopology;
+ try holdout.verify(io, store.root, arena, suite.sha256, record.trial_id);
+ candidate.holdout = try eval.verifyComparison(
+ arena,
+ io,
+ store,
+ config.value,
+ &config.id,
+ build_options.version,
+ record.trial_id,
+ index,
+ active.ref.genome_id,
+ candidate.genome_id,
+ suite,
+ record.repetitions,
+ 1,
+ comparison,
+ );
+ }
+ }
+}
+
+pub fn restorePending(
+ arena: Allocator,
+ io: Io,
+ store: *store_mod.Store,
+ config: store_mod.LoadedConfig,
+ active: store_mod.LoadedActive,
+ record: checkpoint.Record,
+) ![]eval.CandidateRecord {
+ try checkpoint.validate(record);
+ if (!std.mem.eql(u8, record.config_id, &config.id) or
+ !std.mem.eql(u8, record.harness_version, build_options.version) or
+ record.parent_generation != active.ref.generation or
+ !std.mem.eql(u8, record.parent_genome_id, active.ref.genome_id) or
+ !std.mem.eql(u8, record.parent_transaction_id, active.ref.transaction_id)) return error.PendingContextMismatch;
+ const expected_trial = trialId(record.config_id, record.parent_genome_id, record.parent_generation, record.parent_transaction_id, record.nonce);
+ if (!std.mem.eql(u8, record.trial_id, &expected_trial)) return error.TrialMismatch;
+ const candidates = try arena.dupe(eval.CandidateRecord, record.candidates);
+ try verifyRestoredProgress(arena, io, store, config, active, record, candidates);
+ return candidates;
+}
+
/// Runs mutations and primary comparisons behind separate barriers. The
/// holdout adapter is invoked only after every primary result has joined and
/// the sole winner has been selected.
@@ -151,40 +343,86 @@ pub fn execute(
options: Options,
out: *Io.Writer,
) !Result {
- const candidate_count = options.candidates orelse config.value.gate.default_candidates;
- const repetitions = options.repetitions orelse config.value.gate.default_repetitions;
- if (candidate_count == 0 or candidate_count > 16 or repetitions == 0 or repetitions > 100) return error.InvalidNumber;
-
- const nonce = try store_mod.randomId(io);
- const trial_id = trialId(&config.id, active.ref.genome_id, active.ref.generation, active.ref.transaction_id, &nonce);
- const candidates = try arena.alloc(eval.CandidateRecord, candidate_count);
-
- const mutation_futures = try arena.alloc(Io.Future(anyerror!MutationTaskResult), candidate_count);
- const mutation_results = try arena.alloc(anyerror!MutationTaskResult, candidate_count);
- for (mutation_futures, 0..) |*future, index| {
- future.* = io.async(mutationTask, .{ gpa, io, environ, store, config.value, &trial_id, index, active.ref.genome_id, active.genome });
- }
- for (mutation_futures, mutation_results) |*future, *result| result.* = future.await(io);
- defer for (mutation_results) |*result| {
- if (result.*) |*task_result| {
- gpa.free(task_result.outcome.prompt);
- task_result.arena.deinit();
- } else |_| {}
- };
+ if (options.resume_run and options.restart) return error.ConflictingOptions;
+ if (options.restart) try checkpoint.clear(store);
+ const pending = try checkpoint.load(arena, store);
+
+ var nonce_buffer: [64]u8 = undefined;
+ var trial_buffer: [64]u8 = undefined;
+ var nonce: []const u8 = undefined;
+ var trial_id: []const u8 = undefined;
+ var created_unix_ms: i64 = undefined;
+ var candidate_count: usize = undefined;
+ var repetitions: usize = undefined;
+ var primary_baseline: ?eval.PrimaryBaselineRecord = null;
+ var candidates: []eval.CandidateRecord = undefined;
+
+ if (options.resume_run) {
+ const saved = pending orelse return error.NoPendingRun;
+ if ((options.candidates != null and options.candidates.? != saved.planned_candidates) or
+ (options.repetitions != null and options.repetitions.? != saved.repetitions) or
+ options.auto != saved.auto_requested) return error.ResumeOptionMismatch;
+ nonce = saved.nonce;
+ trial_id = saved.trial_id;
+ created_unix_ms = saved.created_unix_ms;
+ candidate_count = saved.planned_candidates;
+ repetitions = saved.repetitions;
+ try verifyTrialPower(io, arena, config.value, candidate_count);
+ primary_baseline = saved.primary_baseline;
+ candidates = try restorePending(arena, io, store, config, active, saved);
+ try out.print("resuming checkpointed trial {s}\n", .{trial_id});
+ } else {
+ if (pending != null) {
+ try out.writeAll("a recoverable tournament exists; use `graff learn run --resume` or explicitly discard it with `--restart`\n");
+ return error.PendingRunExists;
+ }
+ if (config.value.holdout_suite) |suite|
+ try holdout.ensureUnused(io, store.root, suite.sha256);
+ candidate_count = options.candidates orelse config.value.gate.default_candidates;
+ repetitions = options.repetitions orelse config.value.gate.default_repetitions;
+ if (candidate_count == 0 or candidate_count > 16 or repetitions == 0 or repetitions > 100) return error.InvalidNumber;
+ try verifyTrialPower(io, arena, config.value, candidate_count);
+ nonce_buffer = try store_mod.randomId(io);
+ trial_buffer = trialId(&config.id, active.ref.genome_id, active.ref.generation, active.ref.transaction_id, &nonce_buffer);
+ nonce = &nonce_buffer;
+ trial_id = &trial_buffer;
+ created_unix_ms = util.unixMs(io);
+ candidates = try arena.alloc(eval.CandidateRecord, candidate_count);
- for (mutation_results, candidates) |result, *candidate| {
- const completed = result catch |err| {
- if (config.value.gate.require_all_candidates) return error.IncompleteCandidateSet;
- return err;
+ const mutation_futures = try arena.alloc(Io.Future(anyerror!MutationTaskResult), candidate_count);
+ const mutation_results = try arena.alloc(anyerror!MutationTaskResult, candidate_count);
+ for (mutation_futures, 0..) |*future, index| {
+ future.* = io.async(mutationTask, .{ gpa, io, environ, store, config.value, trial_id, index, active.ref.genome_id, active.genome });
+ }
+ for (mutation_futures, mutation_results) |*future, *result| result.* = future.await(io);
+ defer for (mutation_results) |*result| {
+ if (result.*) |*task_result| {
+ gpa.free(task_result.outcome.prompt);
+ task_result.arena.deinit();
+ } else |_| {}
};
- candidate.* = .{
- .genome_id = try arena.dupe(u8, &completed.outcome.genome_id),
- .mutation = completed.outcome.record,
- .primary = null,
- .holdout = null,
- .eligible = false,
- .reason = "unevaluated",
+ for (mutation_results, candidates) |result, *candidate| {
+ const completed = result catch |err| {
+ if (config.value.gate.require_all_candidates) return error.IncompleteCandidateSet;
+ return err;
+ };
+ candidate.* = try copyMutationCandidate(arena, completed.outcome);
+ }
+ for (candidates, 0..) |*candidate, index| if (mutationIsDuplicate(active.ref.genome_id, candidates, index)) |reason| {
+ candidate.reason = reason;
};
+ try checkpoint.write(gpa, store, progressRecord(
+ config,
+ active,
+ nonce,
+ trial_id,
+ created_unix_ms,
+ candidate_count,
+ repetitions,
+ options.auto,
+ null,
+ candidates,
+ ));
}
var primary_indices: std.ArrayList(usize) = .empty;
@@ -196,8 +434,8 @@ pub fn execute(
}
try requireCompleteCandidateSet(config.value.gate.require_all_candidates, candidate_count, primary_indices.items.len);
- const primary_baseline: ?eval.PrimaryBaselineRecord = if (primary_indices.items.len > 0)
- try primary.evaluateBaseline(
+ if (primary_indices.items.len > 0 and primary_baseline == null) {
+ primary_baseline = try primary.evaluateBaseline(
gpa,
arena,
io,
@@ -206,22 +444,28 @@ pub fn execute(
config.value,
&config.id,
build_options.version,
- &trial_id,
+ trial_id,
active.ref.genome_id,
active.genome,
config.value.evaluation_suite,
repetitions,
- )
- else
- null;
-
- const primary_futures = try arena.alloc(Io.Future(anyerror!EvaluationTaskResult), primary_indices.items.len);
- const primary_results = try arena.alloc(anyerror!EvaluationTaskResult, primary_indices.items.len);
- for (primary_indices.items, primary_futures) |index, *future| {
- const mutation = try mutation_results[index];
+ );
+ try checkpoint.write(gpa, store, progressRecord(config, active, nonce, trial_id, created_unix_ms, candidate_count, repetitions, options.auto, primary_baseline, candidates));
+ }
+
+ var missing_primary: std.ArrayList(usize) = .empty;
+ defer missing_primary.deinit(gpa);
+ for (primary_indices.items) |index| if (candidates[index].primary == null) try missing_primary.append(gpa, index);
+ const primary_futures = try arena.alloc(Io.Future(anyerror!EvaluationTaskResult), missing_primary.items.len);
+ const primary_results = try arena.alloc(anyerror!EvaluationTaskResult, missing_primary.items.len);
+ const child_prompts = try arena.alloc([]const u8, missing_primary.items.len);
+ for (missing_primary.items, child_prompts) |index, *prompt| {
+ prompt.* = try store.readGenome(arena, candidates[index].genome_id, config.value.limits.genome_bytes);
+ }
+ for (missing_primary.items, child_prompts, primary_futures) |index, child_prompt, *future| {
future.* = io.async(primaryTask, .{
- gpa, io, environ, store, config.value, &config.id,
- &trial_id, index, active.ref.genome_id, candidates[index].genome_id, mutation.outcome.prompt, config.value.evaluation_suite,
+ gpa, io, environ, store, config.value, &config.id,
+ trial_id, index, active.ref.genome_id, candidates[index].genome_id, child_prompt, config.value.evaluation_suite,
repetitions, candidate_count, primary_baseline.?,
});
}
@@ -229,34 +473,45 @@ pub fn execute(
defer for (primary_results) |*result| {
if (result.*) |*task_result| task_result.arena.deinit() else |_| {}
};
- for (primary_indices.items, primary_results) |index, result| {
- candidates[index].primary = (try result).comparison;
+ var primary_failure: ?anyerror = null;
+ for (missing_primary.items, primary_results) |index, result| {
+ if (result) |completed| {
+ candidates[index].primary = completed.comparison;
+ candidates[index].reason = candidates[index].primary.?.reason;
+ try checkpoint.write(gpa, store, progressRecord(config, active, nonce, trial_id, created_unix_ms, candidate_count, repetitions, options.auto, primary_baseline, candidates));
+ } else |err| if (primary_failure == null) {
+ primary_failure = err;
+ }
}
+ if (primary_failure) |err| return err;
const primary_winner_index = tournament.primaryWinnerIndex(active.ref.genome_id, candidates);
if (primary_winner_index) |winner_index| {
if (candidates[winner_index].primary.?.eligible) if (config.value.holdout_suite) |holdout_suite| {
- const mutation = try mutation_results[winner_index];
- try holdout.reserve(io, store.root, holdout_suite.sha256, &trial_id);
- candidates[winner_index].holdout = try eval.evaluate(
- gpa,
- arena,
- io,
- environ,
- store,
- config.value,
- &config.id,
- build_options.version,
- &trial_id,
- winner_index,
- active.ref.genome_id,
- active.genome,
- candidates[winner_index].genome_id,
- mutation.outcome.prompt,
- holdout_suite,
- repetitions,
- 1,
- );
+ if (candidates[winner_index].holdout == null) {
+ try holdout.reserveOrVerify(io, store.root, arena, holdout_suite.sha256, trial_id);
+ const child_prompt = try store.readGenome(arena, candidates[winner_index].genome_id, config.value.limits.genome_bytes);
+ candidates[winner_index].holdout = try eval.evaluate(
+ gpa,
+ arena,
+ io,
+ environ,
+ store,
+ config.value,
+ &config.id,
+ build_options.version,
+ trial_id,
+ winner_index,
+ active.ref.genome_id,
+ active.genome,
+ candidates[winner_index].genome_id,
+ child_prompt,
+ holdout_suite,
+ repetitions,
+ 1,
+ );
+ try checkpoint.write(gpa, store, progressRecord(config, active, nonce, trial_id, created_unix_ms, candidate_count, repetitions, options.auto, primary_baseline, candidates));
+ }
};
}
const finalized = try tournament.finalize(active.ref.genome_id, candidates, config.value.holdout_suite != null);
@@ -265,12 +520,13 @@ pub fn execute(
// Re-check every externally controlled executable and suite after use and
// before committing the immutable run record.
try verifyPins(io, arena, config.value);
+ try verifyTrialPower(io, arena, config.value, candidate_count);
const record: eval.RunRecord = .{
.schema = eval.run_schema,
- .trial_id = &trial_id,
- .nonce = &nonce,
- .created_unix_ms = util.unixMs(io),
+ .trial_id = trial_id,
+ .nonce = nonce,
+ .created_unix_ms = created_unix_ms,
.harness_version = build_options.version,
.config_id = &config.id,
.parent_genome_id = active.ref.genome_id,
@@ -296,6 +552,8 @@ pub fn execute(
const sent = try submit.submitVerifiedRun(io, gpa, arena, environ, config.value, &run_id, record);
try out.print("submitted {d} signed aggregate grade(s); prompt text stayed local\n", .{sent.grades});
}
+ try out.flush();
+ try checkpoint.clear(store);
return .{
.run_id = run_id,
.primary_winner_genome_id = primary_winner,
diff --git a/src/learn_store.zig b/src/learn_store.zig
index 3d604769..9f8a5759 100644
--- a/src/learn_store.zig
+++ b/src/learn_store.zig
@@ -76,7 +76,12 @@ fn openFileNoFollow(io: Io, dir: Io.Dir, path: []const u8, options: Io.Dir.OpenF
const validate_mod = @import("learn_store_validate.zig");
pub const validId = validate_mod.validId;
pub const validateConfig = validate_mod.validateConfig;
-const validateSuite = validate_mod.validateSuite;
+pub const validateSuite = validate_mod.validateSuite;
+pub const statisticalUnitCount = validate_mod.statisticalUnitCount;
+pub const validateHoldoutIndependence = validate_mod.validateHoldoutIndependence;
+pub const validateSuitePower = validate_mod.validateSuitePower;
+pub const minimumSignificantUnits = validate_mod.minimumSignificantUnits;
+pub const validateSuiteTrialPower = validate_mod.validateSuiteTrialPower;
pub const validateTransaction = validate_mod.validateTransaction;
const hash_mod = @import("learn_store_hash.zig");
pub const rawSha256 = hash_mod.rawSha256;
diff --git a/src/learn_store_tests.zig b/src/learn_store_tests.zig
index 83edc060..206e4eda 100644
--- a/src/learn_store_tests.zig
+++ b/src/learn_store_tests.zig
@@ -19,6 +19,14 @@ const Config = store_mod.Config;
const validId = store_mod.validId;
const syncDirectory = store_mod.syncDirectory;
const validateConfig = store_mod.validateConfig;
+const validateSuite = store_mod.validateSuite;
+const statisticalUnitCount = store_mod.statisticalUnitCount;
+const validateHoldoutIndependence = store_mod.validateHoldoutIndependence;
+const minimumSignificantUnits = store_mod.minimumSignificantUnits;
+const validateSuitePower = store_mod.validateSuitePower;
+const validateSuiteTrialPower = store_mod.validateSuiteTrialPower;
+const SuiteManifest = store_mod.SuiteManifest;
+const SuiteCase = store_mod.SuiteCase;
const transaction_schema = store_mod.transaction_schema;
test "learning IDs are full, domain-separated, and byte exact" {
@@ -42,6 +50,69 @@ test "learning config parser rejects unknown fields and unsafe auto" {
try std.testing.expectError(error.UnknownField, std.json.parseFromSlice(Config, std.testing.allocator, unknown, .{}));
}
+test "suite statistical units are additive, validated, and criticality-consistent" {
+ const legacy =
+ \\{"schema":"codegraff.learn.suite.v1","suite_id":"legacy","cases":[{"id":"one"},{"id":"two"}]}
+ ;
+ var parsed = try std.json.parseFromSlice(SuiteManifest, std.testing.allocator, legacy, .{});
+ defer parsed.deinit();
+ try validateSuite(parsed.value);
+ try std.testing.expectEqual(@as(usize, 2), statisticalUnitCount(parsed.value));
+
+ const grouped_cases = [_]SuiteCase{
+ .{ .id = "clone-a", .statistical_unit_id = "scenario", .critical = true },
+ .{ .id = "clone-b", .statistical_unit_id = "scenario", .critical = true },
+ .{ .id = "independent" },
+ };
+ const grouped: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "grouped", .cases = &grouped_cases };
+ try validateSuite(grouped);
+ try std.testing.expectEqual(@as(usize, 2), statisticalUnitCount(grouped));
+
+ const invalid_cases = [_]SuiteCase{.{ .id = "clone", .statistical_unit_id = "" }};
+ const invalid: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "invalid", .cases = &invalid_cases };
+ try std.testing.expectError(error.InvalidStatisticalUnitId, validateSuite(invalid));
+ const mixed_cases = [_]SuiteCase{
+ .{ .id = "safe", .statistical_unit_id = "scenario" },
+ .{ .id = "critical", .statistical_unit_id = "scenario", .critical = true },
+ };
+ const mixed: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "mixed", .cases = &mixed_cases };
+ try std.testing.expectError(error.MixedStatisticalUnitCriticality, validateSuite(mixed));
+}
+
+test "holdout suites must be distinct and statistically disjoint" {
+ const primary_cases = [_]SuiteCase{
+ .{ .id = "primary-a", .statistical_unit_id = "shared-scenario" },
+ .{ .id = "primary-b" },
+ };
+ const fresh_cases = [_]SuiteCase{.{ .id = "holdout-a" }};
+ const overlap_cases = [_]SuiteCase{.{ .id = "holdout-copy", .statistical_unit_id = "shared-scenario" }};
+ const primary: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "primary", .cases = &primary_cases };
+ const fresh: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "holdout", .cases = &fresh_cases };
+ const same_id: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "primary", .cases = &fresh_cases };
+ const overlap: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "holdout", .cases = &overlap_cases };
+ const primary_sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ const holdout_sha = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
+
+ try validateHoldoutIndependence(primary_sha, primary, holdout_sha, fresh);
+ try std.testing.expectError(error.HoldoutMatchesPrimary, validateHoldoutIndependence(primary_sha, primary, primary_sha, fresh));
+ try std.testing.expectError(error.HoldoutSuiteIdOverlap, validateHoldoutIndependence(primary_sha, primary, holdout_sha, same_id));
+ try std.testing.expectError(error.HoldoutStatisticalUnitOverlap, validateHoldoutIndependence(primary_sha, primary, holdout_sha, overlap));
+}
+
+test "suite power accounts for exact significance and planned arms" {
+ const cases = [_]SuiteCase{
+ .{ .id = "one" }, .{ .id = "two" }, .{ .id = "three" },
+ .{ .id = "four" }, .{ .id = "five" },
+ };
+ const manifest: SuiteManifest = .{ .schema = store_mod.suite_schema, .suite_id = "power", .cases = &cases };
+ const gate: store_mod.Gate = .{ .alpha_ppm = 50_000, .minimum_pairs = 5 };
+ try validateSuitePower(manifest, gate);
+ try std.testing.expectEqual(@as(usize, 5), try minimumSignificantUnits(gate, 1));
+ try std.testing.expectEqual(@as(usize, 7), try minimumSignificantUnits(gate, 4));
+ try validateSuiteTrialPower(manifest, gate, 1);
+ try std.testing.expectError(error.InsufficientSignificancePower, validateSuiteTrialPower(manifest, gate, 4));
+}
+
test "directory synchronization reopens path-only handles" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
diff --git a/src/learn_store_types.zig b/src/learn_store_types.zig
index 35a8ba19..516cb8d3 100644
--- a/src/learn_store_types.zig
+++ b/src/learn_store_types.zig
@@ -58,8 +58,8 @@ pub const Gate = struct {
/// remain mandatory in either mode.
promotion_mode: PromotionMode = .correctness,
minimum_tool_reduction_ppm: u32 = 100_000,
- /// Minimum number of case-level tool-call wins plus losses. Ties carry no
- /// information for the exact directional economy test.
+ /// Minimum number of statistical-unit tool-call wins plus losses. Ties
+ /// carry no information for the exact directional economy test.
minimum_economy_pairs: usize = 8,
/// Fail the run before any evaluation unless every requested arm produced
/// a unique genome distinct from the parent.
@@ -97,6 +97,9 @@ pub const Config = struct {
pub const SuiteCase = struct {
id: []const u8,
+ /// Optional scenario-family key. Repetitions and structurally cloned case
+ /// IDs sharing this key count as one independent statistical unit.
+ statistical_unit_id: ?[]const u8 = null,
critical: bool = false,
payload: std.json.Value = .null,
};
diff --git a/src/learn_store_validate.zig b/src/learn_store_validate.zig
index 8976aa4d..fc48f08b 100644
--- a/src/learn_store_validate.zig
+++ b/src/learn_store_validate.zig
@@ -112,10 +112,81 @@ pub fn validateSuite(manifest: SuiteManifest) !void {
if (manifest.cases.len == 0 or manifest.cases.len > max_pairs) return error.InvalidSuiteCases;
for (manifest.cases, 0..) |case, i| {
if (!validName(case.id, 128)) return error.InvalidCaseId;
+ if (case.statistical_unit_id) |unit| if (!validName(unit, 128)) return error.InvalidStatisticalUnitId;
for (manifest.cases[0..i]) |prior| if (std.mem.eql(u8, prior.id, case.id)) return error.DuplicateCaseId;
+ const unit = case.statistical_unit_id orelse case.id;
+ for (manifest.cases[0..i]) |prior| {
+ const prior_unit = prior.statistical_unit_id orelse prior.id;
+ if (std.mem.eql(u8, prior_unit, unit) and prior.critical != case.critical)
+ return error.MixedStatisticalUnitCriticality;
+ }
}
}
+pub fn statisticalUnitCount(manifest: SuiteManifest) usize {
+ var count: usize = 0;
+ for (manifest.cases, 0..) |case, index| {
+ const unit = case.statistical_unit_id orelse case.id;
+ var seen = false;
+ for (manifest.cases[0..index]) |prior| {
+ const prior_unit = prior.statistical_unit_id orelse prior.id;
+ if (std.mem.eql(u8, prior_unit, unit)) {
+ seen = true;
+ break;
+ }
+ }
+ if (!seen) count += 1;
+ }
+ return count;
+}
+
+/// A holdout is confirmation evidence only when it is declared as a distinct
+/// suite and none of its independent statistical units appeared in primary
+/// selection. Different JSON bytes alone are insufficient: an edited copy of
+/// the primary cases would otherwise look like fresh evidence.
+pub fn validateHoldoutIndependence(
+ primary_sha256: []const u8,
+ primary: SuiteManifest,
+ holdout_sha256: []const u8,
+ holdout: SuiteManifest,
+) !void {
+ if (std.mem.eql(u8, primary_sha256, holdout_sha256)) return error.HoldoutMatchesPrimary;
+ if (std.mem.eql(u8, primary.suite_id, holdout.suite_id)) return error.HoldoutSuiteIdOverlap;
+ for (primary.cases) |primary_case| {
+ const primary_unit = primary_case.statistical_unit_id orelse primary_case.id;
+ for (holdout.cases) |holdout_case| {
+ const holdout_unit = holdout_case.statistical_unit_id orelse holdout_case.id;
+ if (std.mem.eql(u8, primary_unit, holdout_unit))
+ return error.HoldoutStatisticalUnitOverlap;
+ }
+ }
+}
+
+pub fn validateSuitePower(manifest: SuiteManifest, gate: store.Gate) !void {
+ const units = statisticalUnitCount(manifest);
+ if (units < gate.minimum_pairs) return error.UnderpoweredSuite;
+ if (gate.promotion_mode == .economy and units < gate.minimum_economy_pairs)
+ return error.UnderpoweredSuite;
+}
+
+/// Fewest all-win independent units whose exact one-sided p-value can survive
+/// the configured Bonferroni correction. With no losses, p = 2^-units.
+pub fn minimumSignificantUnits(gate: store.Gate, planned_candidates: usize) !usize {
+ if (planned_candidates == 0 or planned_candidates > 16) return error.InvalidNumber;
+ const target = @as(u64, @intCast(planned_candidates)) * 1_000_000;
+ var corrected_alpha: u64 = gate.alpha_ppm;
+ var units: usize = 0;
+ while (corrected_alpha < target) : (units += 1)
+ corrected_alpha = try std.math.mul(u64, corrected_alpha, 2);
+ return units;
+}
+
+pub fn validateSuiteTrialPower(manifest: SuiteManifest, gate: store.Gate, planned_candidates: usize) !void {
+ try validateSuitePower(manifest, gate);
+ if (statisticalUnitCount(manifest) < try minimumSignificantUnits(gate, planned_candidates))
+ return error.InsufficientSignificancePower;
+}
+
pub fn validateTransaction(tx: store.Transaction) !void {
if (!std.mem.eql(u8, tx.schema, store.transaction_schema)) return error.UnsupportedSchema;
if (!std.mem.eql(u8, tx.operation, "init") and !std.mem.eql(u8, tx.operation, "promote") and !std.mem.eql(u8, tx.operation, "rollback")) return error.InvalidOperation;
diff --git a/src/learn_submit.zig b/src/learn_submit.zig
index 066d9976..e07f2ccc 100644
--- a/src/learn_submit.zig
+++ b/src/learn_submit.zig
@@ -2,8 +2,8 @@
//!
//! Candidate genomes and evaluation payloads stay in the local immutable
//! store. Only the existing signed OTLP score envelope leaves the machine:
-//! short prompt/parent fingerprints, aggregate pass rate, suite/cohort
-//! metadata, and content-addressed evidence ids.
+//! short prompt/parent fingerprints, aggregate comparison metrics, suite/cohort
+//! metadata, gate settings, and content-addressed evidence ids.
const std = @import("std");
const Io = std.Io;
@@ -15,25 +15,29 @@ const store = @import("learn_store.zig");
const scoring = @import("scoring.zig");
const telemetry = @import("telemetry.zig");
const telemetry_net = @import("telemetry_net.zig");
-const keys_cli = @import("keys_cli.zig");
const learning_privacy = @import("learning_privacy.zig");
+const receipt = @import("learn_receipt.zig");
pub const SubmitResult = struct {
grades: usize,
endpoint: []const u8,
};
+pub fn deletionEndpoint(environ: *const std.process.Environ.Map) ![]const u8 {
+ const value = environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") orelse
+ environ.get("GRAFF_OTEL_ENDPOINT") orelse
+ build_options.telemetry_endpoint;
+ if (value.len == 0) return error.TelemetryDisabled;
+ return value;
+}
+
fn endpoint(environ: *const std.process.Environ.Map) ![]const u8 {
if (environ.get("GRAFF_NO_TELEMETRY") != null) return error.TelemetryDisabled;
if (environ.get("GRAFF_FLEET")) |value| {
if (std.ascii.eqlIgnoreCase(value, "off") or std.mem.eql(u8, value, "0") or std.ascii.eqlIgnoreCase(value, "false"))
return error.TelemetryDisabled;
}
- const value = environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") orelse
- environ.get("GRAFF_OTEL_ENDPOINT") orelse
- build_options.telemetry_endpoint;
- if (value.len == 0) return error.TelemetryDisabled;
- return value;
+ return deletionEndpoint(environ);
}
/// Fail before an expensive learning run when an explicit submit could not
@@ -60,6 +64,8 @@ fn appendGrade(
candidate: eval.CandidateRecord,
comparison: eval.ComparisonRecord,
judge_id: []const u8,
+ multiplicity: usize,
+ delete_token: []const u8,
) !void {
const prompt_sha = candidate.genome_id[0..16];
const parent_sha = run.parent_genome_id[0..16];
@@ -80,14 +86,35 @@ fn appendGrade(
provider_class,
);
if (signature[0] == 0) return error.ScoreSigningKeyRequired;
- var provenance_buf: [320]u8 = undefined;
- const provenance = std.fmt.bufPrint(&provenance_buf, "{s}\t{s}\t{s}\t{s}\t{s}", .{
+ const grade = receipt.fromComparison(config.gate, comparison, multiplicity);
+ const grade_signature = receipt.sign(
+ prompt_sha,
+ parent_sha,
+ value,
+ run_id,
+ judge_id,
+ comparison.response_evidence_id,
+ comparison.suite_sha256,
+ niche,
+ provider_class,
+ delete_token,
+ run.created_unix_ms,
+ grade,
+ );
+ if (grade_signature[0] == 0) return error.ScoreSigningKeyRequired;
+ var provenance_buf: [2048]u8 = undefined;
+ const provenance = receipt.provenance(
+ &provenance_buf,
judge_id,
comparison.response_evidence_id,
comparison.suite_sha256,
provider_class,
niche,
- }) catch return error.ProvenanceTooLong;
+ &grade_signature,
+ delete_token,
+ run.created_unix_ms,
+ grade,
+ ) orelse return error.ProvenanceTooLong;
sink.scoreEvent(prompt_sha, parent_sha, value, run_id, &signature, provenance);
}
@@ -120,14 +147,15 @@ pub fn submitVerifiedRun(
const target = try endpoint(environ);
var client: std.http.Client = .{ .allocator = gpa, .io = io };
defer client.deinit();
- const home = keys_cli.homeEnv(environ) orelse "";
var sink: telemetry.Telemetry = .{
.io = io,
.gpa = gpa,
.client = &client,
.endpoint = target,
.auth_key = telemetry.validatedAuthKey(environ.get("GRAFF_TELEMETRY_KEY")),
- .install_id = keys_cli.loadOrCreateId(io, gpa, home, ".simple-harness-install-id"),
+ // Explicit learning receipts are deliberately unlinkable to a stable
+ // installation. writeOtlp also omits this sentinel for this client.
+ .install_id = @splat('0'),
.client_name = "harness-learn",
.sdk_install_id = "",
.start = Io.Timestamp.now(io, .awake),
@@ -136,13 +164,15 @@ pub fn submitVerifiedRun(
defer sink.deinit();
var grades: usize = 0;
+ const delete_token = receipt.deletionToken(run_id, run.nonce);
+ if (delete_token[0] == 0) return error.ScoreSigningKeyRequired;
for (run.candidates) |candidate| {
if (candidate.primary) |comparison| {
- try appendGrade(&sink, config, run_id, run, candidate, comparison, "learn-primary-v2");
+ try appendGrade(&sink, config, run_id, run, candidate, comparison, "learn-primary-v2", run.planned_candidates, &delete_token);
grades += 1;
}
if (candidate.holdout) |comparison| {
- try appendGrade(&sink, config, run_id, run, candidate, comparison, "learn-holdout-v2");
+ try appendGrade(&sink, config, run_id, run, candidate, comparison, "learn-holdout-v2", 1, &delete_token);
grades += 1;
}
}
@@ -188,3 +218,7 @@ test "learning pass-rate grade uses repeated pair count" {
};
try std.testing.expectApproxEqAbs(@as(f64, 0.75), try passRate(comparison), 1e-12);
}
+
+test {
+ _ = @import("learn_receipt.zig");
+}
diff --git a/src/learn_tournament.zig b/src/learn_tournament.zig
index b799f2f7..c20edc25 100644
--- a/src/learn_tournament.zig
+++ b/src/learn_tournament.zig
@@ -10,8 +10,8 @@ pub const Eligibility = struct {
};
pub const Finalized = struct {
- /// Best unique, non-parent candidate with primary evidence. This candidate
- /// advances to the holdout even when its primary gate is not yet eligible.
+ /// Best unique, non-parent candidate with primary evidence. Eligibility is
+ /// applied separately before deciding whether holdout exposure is useful.
primary_winner_index: ?usize,
/// Set only when that one winner passes every configured promotion gate.
selected_genome_id: ?[]const u8,
diff --git a/src/process_runner.zig b/src/process_runner.zig
new file mode 100644
index 00000000..898efdae
--- /dev/null
+++ b/src/process_runner.zig
@@ -0,0 +1,202 @@
+//! Capped subprocess execution with optional whole-process-tree ownership.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Agent = @import("agent.zig").Agent;
+
+const posix_process_groups = switch (builtin.os.tag) {
+ .windows, .wasi => false,
+ else => true,
+};
+const GroupId = if (posix_process_groups) std.posix.pid_t else void;
+const WindowsJobHandle = if (builtin.os.tag == .windows) ?std.os.windows.HANDLE else void;
+
+const WinJob = if (builtin.os.tag == .windows) struct {
+ const windows = std.os.windows;
+ const kill_on_close: windows.DWORD = 0x00002000;
+ const extended_limit_information: c_int = 9;
+
+ const BasicLimitInformation = extern struct {
+ per_process_user_time_limit: windows.LARGE_INTEGER = 0,
+ per_job_user_time_limit: windows.LARGE_INTEGER = 0,
+ limit_flags: windows.DWORD = 0,
+ minimum_working_set_size: windows.SIZE_T = 0,
+ maximum_working_set_size: windows.SIZE_T = 0,
+ active_process_limit: windows.DWORD = 0,
+ affinity: windows.ULONG_PTR = 0,
+ priority_class: windows.DWORD = 0,
+ scheduling_class: windows.DWORD = 0,
+ };
+ const IoCounters = extern struct {
+ read_operation_count: u64 = 0,
+ write_operation_count: u64 = 0,
+ other_operation_count: u64 = 0,
+ read_transfer_count: u64 = 0,
+ write_transfer_count: u64 = 0,
+ other_transfer_count: u64 = 0,
+ };
+ const ExtendedLimitInformation = extern struct {
+ basic_limit_information: BasicLimitInformation = .{},
+ io_info: IoCounters = .{},
+ process_memory_limit: windows.SIZE_T = 0,
+ job_memory_limit: windows.SIZE_T = 0,
+ peak_process_memory_used: windows.SIZE_T = 0,
+ peak_job_memory_used: windows.SIZE_T = 0,
+ };
+
+ extern "kernel32" fn CreateJobObjectW(
+ job_attributes: ?*windows.SECURITY_ATTRIBUTES,
+ name: ?windows.LPCWSTR,
+ ) callconv(.winapi) ?windows.HANDLE;
+ extern "kernel32" fn SetInformationJobObject(
+ job: windows.HANDLE,
+ info_class: c_int,
+ info: *const anyopaque,
+ info_len: windows.DWORD,
+ ) callconv(.winapi) windows.BOOL;
+ extern "kernel32" fn AssignProcessToJobObject(
+ job: windows.HANDLE,
+ process: windows.HANDLE,
+ ) callconv(.winapi) windows.BOOL;
+
+ fn setup(child: *std.process.Child) !windows.HANDLE {
+ const job = CreateJobObjectW(null, null) orelse return error.ProcessTreeSetupFailed;
+ errdefer windows.CloseHandle(job);
+ var limits: ExtendedLimitInformation = .{};
+ limits.basic_limit_information.limit_flags = kill_on_close;
+ if (!SetInformationJobObject(job, extended_limit_information, &limits, @sizeOf(ExtendedLimitInformation)).toBool())
+ return error.ProcessTreeSetupFailed;
+ if (!AssignProcessToJobObject(job, child.id.?).toBool()) return error.ProcessTreeSetupFailed;
+ if (windows.ntdll.NtResumeThread(child.thread_handle, null) != .SUCCESS)
+ return error.ProcessTreeSetupFailed;
+ return job;
+ }
+} else struct {};
+
+pub const CappedRun = struct {
+ term: std.process.Child.Term,
+ stdout: []u8,
+ stderr: []u8,
+ stdout_truncated: bool,
+ stderr_truncated: bool,
+ timed_out: bool,
+};
+
+/// Supplying an explicit environment replaces (rather than augments) the
+/// parent environment. `kill_process_tree` creates an owned process group/job
+/// so descendants cannot outlive the orchestrated command.
+pub const CappedRunOptions = struct {
+ cwd: std.process.Child.Cwd = .inherit,
+ environ_map: ?*const std.process.Environ.Map = null,
+ kill_process_tree: bool = false,
+};
+
+fn setupWindowsJob(child: *std.process.Child, enabled: bool) !WindowsJobHandle {
+ if (comptime builtin.os.tag == .windows) {
+ return if (enabled) try WinJob.setup(child) else null;
+ } else {
+ return {};
+ }
+}
+
+fn closeWindowsJob(job: *WindowsJobHandle) void {
+ if (comptime builtin.os.tag == .windows) if (job.*) |handle| {
+ std.os.windows.CloseHandle(handle);
+ job.* = null;
+ };
+}
+
+fn killProcessGroup(group_id: GroupId, enabled: bool) void {
+ if (comptime posix_process_groups) {
+ if (!enabled) return;
+ std.posix.kill(-group_id, .KILL) catch {};
+ }
+}
+
+fn terminateTree(child: *std.process.Child, io: Io, job: *WindowsJobHandle, group_id: GroupId, enabled: bool) void {
+ closeWindowsJob(job);
+ killProcessGroup(group_id, enabled);
+ child.kill(io);
+}
+
+pub fn runCapped(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64) !CappedRun {
+ return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{});
+}
+
+pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, options: CappedRunOptions) !CappedRun {
+ var child = try std.process.spawn(io, .{
+ .argv = argv,
+ .cwd = options.cwd,
+ .environ_map = options.environ_map,
+ .stdin = .ignore,
+ .stdout = .pipe,
+ .stderr = .pipe,
+ .pgid = if (posix_process_groups and options.kill_process_tree) 0 else null,
+ .start_suspended = builtin.os.tag == .windows and options.kill_process_tree,
+ });
+ var setup_cleanup_needed = true;
+ errdefer if (setup_cleanup_needed) child.kill(io);
+ const group_id: GroupId = if (posix_process_groups) child.id.? else {};
+ var windows_job = try setupWindowsJob(&child, options.kill_process_tree);
+ setup_cleanup_needed = false;
+ var cleanup_needed = true;
+ defer if (cleanup_needed) terminateTree(&child, io, &windows_job, group_id, options.kill_process_tree);
+
+ var multi_reader_buffer: Io.File.MultiReader.Buffer(2) = undefined;
+ var multi_reader: Io.File.MultiReader = undefined;
+ multi_reader.init(gpa, io, multi_reader_buffer.toStreams(), &.{ child.stdout.?, child.stderr.? });
+ defer multi_reader.deinit();
+
+ const readers = [2]*Io.Reader{ multi_reader.reader(0), multi_reader.reader(1) };
+ const caps = [2]usize{ stdout_cap, stderr_cap };
+ var saved: [2]?[]u8 = .{ null, null };
+ errdefer for (saved) |item| if (item) |bytes| gpa.free(bytes);
+
+ var esc_killed = false;
+ var timed_out = false;
+ const started: Io.Timestamp = .now(io, .awake);
+ loop: while (true) {
+ multi_reader.fill(64, .{ .duration = .{ .raw = .fromMilliseconds(200), .clock = .awake } }) catch |err| switch (err) {
+ error.EndOfStream => break :loop,
+ error.Timeout => {},
+ else => |other| return other,
+ };
+ for (readers, caps, &saved) |reader, cap, *item| {
+ const buffered = reader.buffered();
+ if (item.* == null and buffered.len > cap) item.* = try gpa.dupe(u8, buffered[0..cap]);
+ if (item.* != null) reader.toss(buffered.len);
+ }
+ if (Agent.esc_cancel.load(.acquire)) {
+ esc_killed = true;
+ terminateTree(&child, io, &windows_job, group_id, options.kill_process_tree);
+ cleanup_needed = false;
+ break :loop;
+ }
+ if (deadline_ms > 0 and started.untilNow(io, .awake).toMilliseconds() >= deadline_ms) {
+ timed_out = true;
+ terminateTree(&child, io, &windows_job, group_id, options.kill_process_tree);
+ cleanup_needed = false;
+ break :loop;
+ }
+ }
+ if (!esc_killed and !timed_out) try multi_reader.checkAnyError();
+
+ const term: std.process.Child.Term = if (esc_killed or timed_out) .{ .signal = .TERM } else try child.wait(io);
+ const stdout = if (saved[0]) |bytes| bytes else try gpa.dupe(u8, readers[0].buffered());
+ errdefer gpa.free(stdout);
+ const stderr = if (saved[1]) |bytes| bytes else try gpa.dupe(u8, readers[1].buffered());
+ return .{
+ .term = term,
+ .stdout = stdout,
+ .stderr = stderr,
+ .stdout_truncated = saved[0] != null,
+ .stderr_truncated = saved[1] != null,
+ .timed_out = timed_out,
+ };
+}
+
+pub fn ranOk(run: CappedRun) bool {
+ return run.term == .exited and run.term.exited == 0;
+}
diff --git a/src/scoring.zig b/src/scoring.zig
index cdcc943f..ad5c28ee 100644
--- a/src/scoring.zig
+++ b/src/scoring.zig
@@ -156,6 +156,38 @@ pub fn sanitizeMetaField(buf: []u8, field: []const u8) []const u8 {
return buf[0..n];
}
+/// Project free-form fleet metadata onto a non-sensitive wire shape. Values
+/// already shaped like hashes remain joinable; everything else becomes the
+/// same 16-hex fingerprint used for prompts, so paths and task labels cannot
+/// leave as plaintext even after aggregate telemetry is opted in.
+pub fn telemetryHash(buf: *[16]u8, value: []const u8, min_len: usize) []const u8 {
+ if (value.len == 0) return "";
+ if (value.len >= min_len and value.len <= 64) {
+ var valid = true;
+ for (value) |c| if (!std.ascii.isHex(c) or std.ascii.isUpper(c)) {
+ valid = false;
+ break;
+ };
+ if (valid) return value;
+ }
+ buf.* = promptFingerprint(value);
+ return buf;
+}
+
+pub fn telemetryNiche(buf: *[23]u8, value: []const u8) []const u8 {
+ const builtins = [_][]const u8{ "reviewer", "researcher", "implementer", "skeptic" };
+ for (builtins) |name| if (std.ascii.eqlIgnoreCase(value, name)) return name;
+ if (value.len == 0) return "";
+ const fp = promptFingerprint(value);
+ return std.fmt.bufPrint(buf, "custom-{s}", .{&fp}) catch "";
+}
+
+pub fn telemetryProviderClass(value: []const u8) ?[]const u8 {
+ for ([_][]const u8{ "frontier", "mid", "small" }) |name|
+ if (std.ascii.eqlIgnoreCase(value, name)) return name;
+ return null;
+}
+
/// Read the signing key from GRAFF_SCORE_KEY_FILE, or the conventional
/// ~/.simple-harness/score.key when no path is configured. The key stays
/// outside cwd so learning adapters and confined subagents cannot read it.
@@ -278,3 +310,16 @@ test "sanitizeMetaField: a niche with an embedded tab signs and round-trips iden
const verified = signScore("a1b2", "", 0.5, "run1", "j1", "art", "evalhash", transported, "mid");
try std.testing.expectEqualStrings(&signed, &verified);
}
+
+test "telemetry metadata projection retains hashes and hides free-form labels" {
+ var hash_buf: [16]u8 = undefined;
+ try std.testing.expectEqualStrings("0123456789abcdef", telemetryHash(&hash_buf, "0123456789abcdef", 16));
+ const projected = telemetryHash(&hash_buf, "/private/evals/customer-a.json", 8);
+ try std.testing.expectEqual(@as(usize, 16), projected.len);
+ try std.testing.expect(!std.mem.eql(u8, projected, "/private/evals/customer-a.json"));
+ var niche_buf: [23]u8 = undefined;
+ try std.testing.expectEqualStrings("reviewer", telemetryNiche(&niche_buf, "Reviewer"));
+ try std.testing.expect(std.mem.startsWith(u8, telemetryNiche(&niche_buf, "client-secret"), "custom-"));
+ try std.testing.expectEqualStrings("frontier", telemetryProviderClass("FRONTIER").?);
+ try std.testing.expect(telemetryProviderClass("private-provider") == null);
+}
diff --git a/src/telemetry.zig b/src/telemetry.zig
index 3b137e9d..195b1dd8 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -25,6 +25,7 @@ const http = @import("http.zig");
// For the session run id (score/run join key) and the propose-site
// fingerprint check. No cycle: scoring imports only std + pricing.
const scoring = @import("scoring.zig");
+const telemetry_score = @import("telemetry_score.zig");
const learning_privacy = @import("learning_privacy.zig");
const root = @import("main.zig");
@@ -91,7 +92,7 @@ pub const Telemetry = struct {
extra: []const u8 = "", // gpa-duped: score → parent_sha, run → tool sequence
run_id: []const u8 = "", // gpa-duped: score → run_id (signed)
sig: []const u8 = "", // gpa-duped: score → HMAC signature ("" when unsigned)
- prov: []const u8 = "", // gpa-duped: score → "judge_id\tartifact_sha\teval_set_hash" (signed)
+ prov: []const u8 = "", // gpa-duped: score provenance + optional aggregate grade
phases: i64 = 0,
tasks: i64 = 0,
failed: i64 = 0,
@@ -149,34 +150,19 @@ pub const Telemetry = struct {
}
/// Record an issue (API failure, tool failure, aborted turn) as an ERROR
- /// log record. `kind` and the truncated `detail` become attributes.
+ /// log record. Only the fixed call-site category leaves the process: raw
+ /// provider/tool error text can echo prompts, paths, source, or secrets.
pub fn errorEvent(self: *Telemetry, kind: []const u8, detail: []const u8) void {
if (!self.on()) return;
+ _ = detail;
{
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
- self.push(.{ .t_ms = self.elapsedMsLocked(), .body = "error", .kind = kind, .detail = self.dupDetail(detail) });
+ self.push(.{ .t_ms = self.elapsedMsLocked(), .body = "error", .kind = kind });
}
self.maybeFlushEvents();
}
- /// Truncate to max_detail without splitting a UTF-8 codepoint, and force
- /// the copy to valid UTF-8 — std.json serializes an invalid []u8 as an
- /// ARRAY of integers, which is schema-invalid OTLP that makes a collector
- /// reject the entire batch. detail can carry raw provider bytes (e.g.
- /// "unparseable response: …"), so both the cut and the content matter.
- pub fn dupDetail(self: *Telemetry, detail: []const u8) []const u8 {
- var p = detail[0..@min(detail.len, max_detail)];
- var strips: usize = 0; // a split codepoint needs at most 3 byte strips
- while (strips < 3 and p.len > 0 and !std.unicode.utf8ValidateSlice(p)) : (strips += 1)
- p = p[0 .. p.len - 1];
- const dup = self.gpa.dupe(u8, p) catch return "";
- if (!std.unicode.utf8ValidateSlice(dup)) for (dup) |*b| {
- if (b.* >= 0x80) b.* = '?'; // invalid mid-string bytes: degrade to ASCII
- };
- return dup;
- }
-
/// Count a subagent spawned with a system-prompt override (an agent-type
/// persona or an inline variant) — the swarm's prompt diversity signal.
pub fn countVariant(self: *Telemetry) void {
@@ -199,11 +185,9 @@ pub const Telemetry = struct {
const pdup = if (parent.len > 0) self.gpa.dupe(u8, parent[0..@min(parent.len, 32)]) catch "" else "";
const rdup = if (run_id.len > 0) self.gpa.dupe(u8, run_id[0..@min(run_id.len, 64)]) catch "" else "";
const sdup = if (sig.len > 0) self.gpa.dupe(u8, sig[0..@min(sig.len, 64)]) catch "" else "";
- // 320, not 256: a max-length prov (64+64+64 signed Step-0 fields +
- // pclass + a 64-char niche + 4 tabs = 268) must never truncate —
- // niche/provider_class are folded into the v2 HMAC (issue #168
- // Gap 2), so a clipped niche would break signature verification.
- const vdup = if (prov.len > 0) self.gpa.dupe(u8, utf8Prefix(prov, 320)) catch "" else "";
+ // Learning receipts append a second signature plus fixed aggregate
+ // metrics. Never truncate signed provenance in transport.
+ const vdup = if (prov.len > 0) self.gpa.dupe(u8, utf8Prefix(prov, 2048)) catch "" else "";
self.push(.{ .t_ms = self.elapsedMsLocked(), .body = "score", .detail = dup, .extra = pdup, .run_id = rdup, .sig = sdup, .prov = vdup, .score = value });
}
self.maybeFlushEvents();
@@ -448,6 +432,10 @@ pub const Telemetry = struct {
}
pub fn writeOtlp(self: *Telemetry, w: *Io.Writer, events: []const Event, include_summary: bool) !void {
+ // Consent is a live send-time decision, not only an enqueue decision.
+ // A later `/privacy local` or `/fleet off` revokes buffered learning
+ // events, and a template approval is rechecked for the exact bytes.
+ const learning_allowed = root.g_fleet and learning_privacy.allowsAggregate();
var s: std.json.Stringify = .{ .writer = w };
try s.beginObject();
try s.objectField("resourceLogs");
@@ -457,13 +445,16 @@ pub const Telemetry = struct {
try s.beginObject();
try s.objectField("attributes");
try s.beginArray();
- try attr(&s, "service.name", .{ .str = "simple-harness" });
- try attr(&s, "service.version", .{ .str = harness_version });
- try attr(&s, "os.type", .{ .str = @tagName(builtin.os.tag) });
- try attr(&s, "host.arch", .{ .str = @tagName(builtin.cpu.arch) });
- try attr(&s, "install.id", .{ .str = &self.install_id });
+ const explicit_learning = std.mem.eql(u8, self.client_name, "harness-learn");
+ if (!explicit_learning) {
+ try attr(&s, "service.name", .{ .str = "simple-harness" });
+ try attr(&s, "service.version", .{ .str = harness_version });
+ try attr(&s, "os.type", .{ .str = @tagName(builtin.os.tag) });
+ try attr(&s, "host.arch", .{ .str = @tagName(builtin.cpu.arch) });
+ try attr(&s, "install.id", .{ .str = &self.install_id });
+ }
try attr(&s, "client.name", .{ .str = self.client_name });
- if (self.sdk_install_id.len > 0) try attr(&s, "sdk.install.id", .{ .str = self.sdk_install_id });
+ if (!explicit_learning and self.sdk_install_id.len > 0) try attr(&s, "sdk.install.id", .{ .str = self.sdk_install_id });
try s.endArray();
try s.endObject();
try s.objectField("scopeLogs");
@@ -477,6 +468,12 @@ pub const Telemetry = struct {
try s.objectField("logRecords");
try s.beginArray();
for (events) |e| {
+ const learning_event = std.mem.eql(u8, e.body, "score") or std.mem.eql(u8, e.body, "run") or std.mem.eql(u8, e.body, "fleet");
+ if (learning_event and !learning_allowed) continue;
+ if (std.mem.eql(u8, e.body, "fleet") and
+ !std.mem.eql(u8, e.kind, "propose") and
+ !std.mem.eql(u8, e.kind, "submit") and
+ !std.mem.eql(u8, e.kind, "elite_pull")) continue;
try s.beginObject();
try timeField(&s, self.start_unix_ms + e.t_ms);
try s.objectField("severityText");
@@ -489,21 +486,7 @@ pub const Telemetry = struct {
try s.objectField("attributes");
try s.beginArray();
if (std.mem.eql(u8, e.body, "score")) {
- try attr(&s, "prompt_sha", .{ .str = e.detail });
- try attr(&s, "value", .{ .num = e.score });
- if (e.extra.len > 0) try attr(&s, "parent_sha", .{ .str = e.extra });
- if (e.run_id.len > 0) try attr(&s, "run_id", .{ .str = e.run_id });
- if (e.sig.len > 0) try attr(&s, "sig", .{ .str = e.sig });
- if (e.prov.len > 0) {
- // prov = "judge_id\tartifact_sha\teval_set_hash" — split so
- // the worker can recompute the HMAC over the same fields.
- var it = std.mem.splitScalar(u8, e.prov, '\t');
- if (it.next()) |j| if (j.len > 0) try attr(&s, "judge_id", .{ .str = j });
- if (it.next()) |a| if (a.len > 0) try attr(&s, "artifact_sha", .{ .str = a });
- if (it.next()) |h| if (h.len > 0) try attr(&s, "eval_set_hash", .{ .str = h });
- if (it.next()) |pc| if (pc.len > 0) try attr(&s, "provider_class", .{ .str = pc });
- if (it.next()) |nc| if (nc.len > 0) try attr(&s, "niche", .{ .str = nc });
- }
+ try telemetry_score.write(&s, e);
} else if (std.mem.eql(u8, e.body, "run")) {
try attr(&s, "prompt_sha", .{ .str = e.detail });
try attr(&s, "variant", .{ .int = @intFromBool(std.mem.eql(u8, e.kind, "variant")) });
@@ -515,16 +498,25 @@ pub const Telemetry = struct {
if (e.extra.len > 0) try attr(&s, "tools", .{ .str = e.extra });
} else if (std.mem.eql(u8, e.body, "fleet")) {
try attr(&s, "kind", .{ .str = e.kind });
- if (e.extra.len > 0) try attr(&s, "niche", .{ .str = e.extra });
- if (e.detail.len > 0) try attr(&s, "prompt_sha", .{ .str = e.detail });
- if (e.run_id.len > 0) try attr(&s, "parent_sha", .{ .str = e.run_id });
+ var niche_buf: [23]u8 = undefined;
+ const niche = scoring.telemetryNiche(&niche_buf, e.extra);
+ if (niche.len > 0) try attr(&s, "niche", .{ .str = niche });
+ var hash_buf: [16]u8 = undefined;
+ const prompt_sha = scoring.telemetryHash(&hash_buf, e.detail, 16);
+ if (prompt_sha.len > 0) try attr(&s, "prompt_sha", .{ .str = prompt_sha });
+ const parent_sha = scoring.telemetryHash(&hash_buf, e.run_id, 16);
+ if (parent_sha.len > 0) try attr(&s, "parent_sha", .{ .str = parent_sha });
if (e.prov.len > 0) {
var fit = std.mem.splitScalar(u8, e.prov, '\t');
- if (fit.next()) |pc| if (pc.len > 0) try attr(&s, "provider_class", .{ .str = pc });
- if (fit.next()) |eh| if (eh.len > 0) try attr(&s, "eval_set_hash", .{ .str = eh });
+ if (fit.next()) |pc| if (scoring.telemetryProviderClass(pc)) |projected| try attr(&s, "provider_class", .{ .str = projected });
+ if (fit.next()) |eh| {
+ const eval_hash = scoring.telemetryHash(&hash_buf, eh, 8);
+ if (eval_hash.len > 0) try attr(&s, "eval_set_hash", .{ .str = eval_hash });
+ }
}
- if (std.mem.eql(u8, e.kind, "elite_pull")) try attr(&s, "n_elites", .{ .int = e.tasks });
- if (e.text.len > 0) try attr(&s, "prompt_text", .{ .str = e.text });
+ if (std.mem.eql(u8, e.kind, "elite_pull")) try attr(&s, "n_elites", .{ .int = @min(@max(e.tasks, 0), 1000) });
+ const admitted_text = learning_privacy.templateTextForUpload(self.io, e.text);
+ if (admitted_text.len > 0) try attr(&s, "prompt_text", .{ .str = admitted_text });
} else {
if (e.kind.len > 0) try attr(&s, "kind", .{ .str = e.kind });
if (e.detail.len > 0) try attr(&s, "detail", .{ .str = e.detail });
@@ -562,8 +554,8 @@ pub const Telemetry = struct {
try attr(&s, "workflows", .{ .int = @intCast(self.workflows) });
try attr(&s, "workflow_tasks", .{ .int = @intCast(self.workflow_tasks) });
try attr(&s, "ultracode_turns", .{ .int = @intCast(self.ultracode_turns) });
- try attr(&s, "prompt_variants", .{ .int = @intCast(self.prompt_variants) });
- try attr(&s, "scores_recorded", .{ .int = @intCast(self.scores_recorded) });
+ try attr(&s, "prompt_variants", .{ .int = @intCast(if (learning_allowed) self.prompt_variants else 0) });
+ try attr(&s, "scores_recorded", .{ .int = @intCast(if (learning_allowed) self.scores_recorded else 0) });
try attr(&s, "models", .{ .str = models_joined });
const c = g_cost.snap(self.io);
try attr(&s, "cost_usd", .{ .num = c.usd });
diff --git a/src/telemetry_score.zig b/src/telemetry_score.zig
new file mode 100644
index 00000000..69feea1c
--- /dev/null
+++ b/src/telemetry_score.zig
@@ -0,0 +1,82 @@
+//! OTLP attribute serialization for score and signed learning-grade events.
+
+const std = @import("std");
+
+const AttrVal = union(enum) { str: []const u8, int: i64, num: f64 };
+
+fn attr(s: *std.json.Stringify, key: []const u8, value: AttrVal) !void {
+ try s.beginObject();
+ try s.objectField("key");
+ try s.write(key);
+ try s.objectField("value");
+ try s.beginObject();
+ switch (value) {
+ .str => |item| {
+ try s.objectField("stringValue");
+ try s.write(item);
+ },
+ .int => |item| {
+ var buffer: [24]u8 = undefined;
+ try s.objectField("intValue");
+ try s.write(std.fmt.bufPrint(&buffer, "{d}", .{item}) catch unreachable);
+ },
+ .num => |item| {
+ try s.objectField("doubleValue");
+ try s.write(item);
+ },
+ }
+ try s.endObject();
+ try s.endObject();
+}
+
+const metric_names = [_][]const u8{
+ "pairs", "statistical_units", "parent_passes", "child_passes",
+ "child_critical_failures", "critical_regressions", "correctness_regressions", "delta_ppm",
+ "mean_score_delta_ppm", "p_value_ppb", "tool_calls_measured", "parent_tool_calls",
+ "child_tool_calls", "tool_wins", "tool_losses", "tool_ties",
+ "tool_delta_ppm", "tool_p_value_ppb", "parent_cost_micros", "child_cost_micros",
+ "latency_measured", "parent_latency_ms", "child_latency_ms", "economy_eligible",
+ "eligible", "economy_gate_enabled", "alpha_ppm", "minimum_delta_ppm",
+ "minimum_pairs", "minimum_tool_reduction_ppm", "minimum_economy_pairs", "multiplicity",
+};
+
+pub fn write(s: *std.json.Stringify, event: anytype) !void {
+ try attr(s, "prompt_sha", .{ .str = event.detail });
+ try attr(s, "value", .{ .num = event.score });
+ if (event.extra.len > 0) try attr(s, "parent_sha", .{ .str = event.extra });
+ if (event.run_id.len > 0) try attr(s, "run_id", .{ .str = event.run_id });
+ if (event.sig.len > 0) try attr(s, "sig", .{ .str = event.sig });
+ if (event.prov.len == 0) return;
+
+ var parts = std.mem.splitScalar(u8, event.prov, '\t');
+ for ([_][]const u8{ "judge_id", "artifact_sha", "eval_set_hash", "provider_class", "niche" }) |name| {
+ const value = parts.next() orelse return error.InvalidScoreProvenance;
+ if (value.len > 0) try attr(s, name, .{ .str = value });
+ }
+ const grade_schema = parts.next() orelse return;
+ if (grade_schema.len == 0) return;
+ const grade_sig = parts.next() orelse return error.InvalidScoreProvenance;
+ var delete_token: []const u8 = "";
+ var run_created_unix_ms: ?i64 = null;
+ if (std.mem.eql(u8, grade_schema, "codegraff.learn.grade.v2")) {
+ delete_token = parts.next() orelse return error.InvalidScoreProvenance;
+ const raw_created = parts.next() orelse return error.InvalidScoreProvenance;
+ run_created_unix_ms = std.fmt.parseInt(i64, raw_created, 10) catch return error.InvalidScoreProvenance;
+ }
+ var metrics: [metric_names.len]i64 = undefined;
+ for (&metrics) |*metric| {
+ const raw = parts.next() orelse return error.InvalidScoreProvenance;
+ metric.* = std.fmt.parseInt(i64, raw, 10) catch return error.InvalidScoreProvenance;
+ }
+ const reason = parts.next() orelse return error.InvalidScoreProvenance;
+ const promotion_mode = parts.next() orelse return error.InvalidScoreProvenance;
+ if (parts.next() != null) return error.InvalidScoreProvenance;
+
+ try attr(s, "grade_schema", .{ .str = grade_schema });
+ try attr(s, "grade_sig", .{ .str = grade_sig });
+ if (delete_token.len > 0) try attr(s, "delete_token", .{ .str = delete_token });
+ if (run_created_unix_ms) |created| try attr(s, "run_created_unix_ms", .{ .int = created });
+ for (metric_names, metrics) |name, metric| try attr(s, name, .{ .int = metric });
+ try attr(s, "reason", .{ .str = reason });
+ try attr(s, "promotion_mode", .{ .str = promotion_mode });
+}
diff --git a/src/telemetry_tests.zig b/src/telemetry_tests.zig
index 8b440a5b..5db53c53 100644
--- a/src/telemetry_tests.zig
+++ b/src/telemetry_tests.zig
@@ -11,36 +11,38 @@ const learning_privacy = @import("learning_privacy.zig");
const main_mod = @import("main.zig");
const scoring = @import("scoring.zig");
-test "telemetry dupDetail never yields invalid UTF-8" {
+test "telemetry error events never retain or serialize raw detail" {
var t: Telemetry = .{
- .io = undefined, // dupDetail only touches gpa
+ .io = std.testing.io,
.gpa = std.testing.allocator,
.endpoint = "x",
.install_id = @splat('0'),
.client_name = "harness",
.sdk_install_id = "",
- .start = undefined,
+ .start = Io.Timestamp.now(std.testing.io, .awake),
.start_unix_ms = 0,
};
- // The 200-byte cap lands mid-codepoint: 199 ASCII bytes + 2-byte 'é'.
- var buf: [201]u8 = undefined;
- @memset(buf[0..199], 'a');
- buf[199] = 0xC3;
- buf[200] = 0xA9;
- const cut = t.dupDetail(&buf);
- defer std.testing.allocator.free(cut);
- try std.testing.expect(std.unicode.utf8ValidateSlice(cut));
- try std.testing.expectEqual(@as(usize, 199), cut.len); // split lead byte dropped
- // Raw invalid bytes mid-string (unparseable provider response) degrade
- // to ASCII instead of corrupting the OTLP payload.
- const garbage = t.dupDetail("ok\xff\xfe more text here");
- defer std.testing.allocator.free(garbage);
- try std.testing.expect(std.unicode.utf8ValidateSlice(garbage));
- try std.testing.expect(std.mem.startsWith(u8, garbage, "ok??"));
+ defer t.deinit();
+ t.errorEvent("api", "provider echoed sk-proj-private-canary and /private/source.zig");
+ try std.testing.expectEqual(@as(usize, 1), t.events.items.len);
+ try std.testing.expectEqualStrings("", t.events.items[0].detail);
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ try t.writeOtlp(&aw.writer, t.events.items, false);
+ const out = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"api\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "sk-proj-private-canary") == null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "/private/source.zig") == null);
}
test "telemetry writeOtlp emits a fleet record with kind + split prov attrs" {
+ const io = std.testing.io;
+ const previous_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ learning_privacy.setMode(io, .aggregate);
+ defer main_mod.g_fleet = previous_fleet;
+ defer learning_privacy.setMode(io, .local);
var t: Telemetry = .{
- .io = undefined, // writeOtlp(.., include_summary=false) never touches io
+ .io = io,
.gpa = std.testing.allocator,
.endpoint = "x",
.install_id = @splat('0'),
@@ -70,8 +72,14 @@ test "telemetry writeOtlp emits a fleet record with kind + split prov attrs" {
try std.testing.expect(std.mem.indexOf(u8, out, "\"a9134381\"") != null); // eval_set_hash (split from prov)
}
test "telemetry writeOtlp stamps run records with run_id (issue #168 Gap 6)" {
+ const io = std.testing.io;
+ const previous_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ learning_privacy.setMode(io, .aggregate);
+ defer main_mod.g_fleet = previous_fleet;
+ defer learning_privacy.setMode(io, .local);
var t: Telemetry = .{
- .io = undefined, // writeOtlp(.., include_summary=false) never touches io
+ .io = io,
.gpa = std.testing.allocator,
.endpoint = "x",
.install_id = @splat('0'),
@@ -100,6 +108,121 @@ test "telemetry writeOtlp stamps run records with run_id (issue #168 Gap 6)" {
try std.testing.expect(std.mem.indexOf(u8, out, "\"read,edit\"") != null); // tools
}
+test "send-time privacy and fleet state revoke buffered learning egress" {
+ const io = std.testing.io;
+ const previous_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ defer main_mod.g_fleet = previous_fleet;
+ defer learning_privacy.setMode(io, .local);
+ var t: Telemetry = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = Io.Timestamp.now(io, .awake),
+ .start_unix_ms = 0,
+ };
+ defer t.deinit();
+ const prompt = "private approved template bytes";
+ const prompt_fp = scoring.promptFingerprint(prompt);
+ learning_privacy.setMode(io, .templates);
+ try std.testing.expect(learning_privacy.approveTemplate(io, prompt));
+ t.fleetEvent("propose", "reviewer", &prompt_fp, "", "frontier", "", 0, prompt);
+ try std.testing.expectEqualStrings(prompt, t.events.items[0].text);
+
+ learning_privacy.setMode(io, .local);
+ var local_payload: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer local_payload.deinit();
+ try t.writeOtlp(&local_payload.writer, t.events.items, false);
+ try std.testing.expect(std.mem.indexOf(u8, local_payload.written(), prompt) == null);
+ try std.testing.expect(std.mem.indexOf(u8, local_payload.written(), "\"stringValue\":\"fleet\"") == null);
+
+ learning_privacy.setMode(io, .templates); // mode change cleared exact approval
+ var revoked_payload: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer revoked_payload.deinit();
+ try t.writeOtlp(&revoked_payload.writer, t.events.items, false);
+ try std.testing.expect(std.mem.indexOf(u8, revoked_payload.written(), "\"stringValue\":\"fleet\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, revoked_payload.written(), prompt) == null);
+
+ try std.testing.expect(learning_privacy.approveTemplate(io, prompt));
+ main_mod.g_fleet = false;
+ var fleet_off_payload: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer fleet_off_payload.deinit();
+ try t.writeOtlp(&fleet_off_payload.writer, t.events.items, false);
+ try std.testing.expect(std.mem.indexOf(u8, fleet_off_payload.written(), prompt) == null);
+ try std.testing.expect(std.mem.indexOf(u8, fleet_off_payload.written(), "\"stringValue\":\"fleet\"") == null);
+}
+
+test "fleet egress projects free-form metadata and rejects unknown records" {
+ const io = std.testing.io;
+ const previous_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ learning_privacy.setMode(io, .aggregate);
+ defer main_mod.g_fleet = previous_fleet;
+ defer learning_privacy.setMode(io, .local);
+ var t: Telemetry = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('0'),
+ .client_name = "harness",
+ .sdk_install_id = "",
+ .start = Io.Timestamp.now(io, .awake),
+ .start_unix_ms = 0,
+ };
+ defer t.deinit();
+ t.fleetEvent("submit", "client-secret-project", "private-prompt-label", "/private/parent", "private-provider", "/private/evals/customer-a.json", 0, "");
+ t.fleetEvent("private-event-kind", "reviewer", "0123456789abcdef", "", "frontier", "", 0, "");
+ var payload: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer payload.deinit();
+ try t.writeOtlp(&payload.writer, t.events.items, false);
+ const out = payload.written();
+ for ([_][]const u8{
+ "client-secret-project",
+ "private-prompt-label",
+ "/private/parent",
+ "private-provider",
+ "/private/evals/customer-a.json",
+ "private-event-kind",
+ }) |canary| try std.testing.expect(std.mem.indexOf(u8, out, canary) == null);
+ const prompt_fp = scoring.promptFingerprint("private-prompt-label");
+ const eval_fp = scoring.promptFingerprint("/private/evals/customer-a.json");
+ try std.testing.expect(std.mem.indexOf(u8, out, &prompt_fp) != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, &eval_fp) != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "custom-") != null);
+}
+
+test "explicit learning resource omits stable and platform identifiers" {
+ const io = std.testing.io;
+ const previous_fleet = main_mod.g_fleet;
+ main_mod.g_fleet = true;
+ learning_privacy.setMode(io, .aggregate);
+ defer main_mod.g_fleet = previous_fleet;
+ defer learning_privacy.setMode(io, .local);
+ var t: Telemetry = .{
+ .io = io,
+ .gpa = std.testing.allocator,
+ .endpoint = "x",
+ .install_id = @splat('z'),
+ .client_name = "harness-learn",
+ .sdk_install_id = "private-stable-sdk-id",
+ .start = Io.Timestamp.now(io, .awake),
+ .start_unix_ms = 0,
+ };
+ defer t.deinit();
+ t.scoreEvent("abcd", "", 1.0, "run", "sig", "");
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ try t.writeOtlp(&aw.writer, t.events.items, false);
+ const out = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"client.name\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"harness-learn\"") != null);
+ for ([_][]const u8{ "install.id", "sdk.install.id", "service.version", "os.type", "host.arch", "private-stable-sdk-id" }) |excluded|
+ try std.testing.expect(std.mem.indexOf(u8, out, excluded) == null);
+}
+
test "learning privacy gates fleet metadata, scores, and exact template text" {
const io = std.testing.io;
main_mod.g_fleet = true;
diff --git a/tests/learn_e2e.py b/tests/learn_e2e.py
index f159fe17..47e9fcfd 100644
--- a/tests/learn_e2e.py
+++ b/tests/learn_e2e.py
@@ -1,12 +1,5 @@
#!/usr/bin/env python3
-"""Loopback-only end-to-end regression test for `graff learn`.
-
-Build first, then run:
- python3 tests/learn_e2e.py --graff zig-out/bin/graff
-
-The fixture uses deterministic local mutator/evaluator programs. Ordinary
-telemetry is disabled; one explicit submit is captured by a loopback server.
-"""
+"""Loopback E2E for local learning plus one explicit captured submission."""
from __future__ import annotations
@@ -27,6 +20,8 @@ import tempfile
import threading
from typing import Any
+from learning_receipt_assertions import assert_learning_records
+
def raw_sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
@@ -217,6 +212,7 @@ def run_id_from(output: str) -> str:
class GradeCapture(BaseHTTPRequestHandler):
payloads: list[dict[str, Any]] = []
+ deletions: list[tuple[str, str | None]] = []
def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
assert self.path == "/v1/logs"
@@ -227,6 +223,11 @@ class GradeCapture(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(b'{"ok":true,"queued":true}')
+ def do_DELETE(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
+ self.deletions.append((self.path, self.headers.get("x-learning-delete-token")))
+ self.send_response(204)
+ self.end_headers()
+
def log_message(self, _format: str, *_args: Any) -> None:
pass
@@ -238,6 +239,7 @@ def verify_grade_submit(graff: Path, workspace: Path, env: dict[str, str], root:
key_path.parent.mkdir(mode=0o700)
write_private(key_path, key + b"\n")
GradeCapture.payloads = []
+ GradeCapture.deletions = []
server = ThreadingHTTPServer(("127.0.0.1", 0), GradeCapture)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
@@ -265,32 +267,29 @@ def verify_grade_submit(graff: Path, workspace: Path, env: dict[str, str], root:
assert not GradeCapture.payloads, "fleet master-off must block learning egress"
output = invoke(graff, workspace, submit_env, "submit", run_id).stdout
assert "submitted 2 signed aggregate grade(s)" in output
+ delete_env = {**submit_env, "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off"}
+ deleted = invoke(graff, workspace, delete_env, "delete-remote", run_id).stdout
+ assert "local evidence was not changed" in deleted
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
assert len(GradeCapture.payloads) == 1
+ run = json.loads((workspace / ".graff" / "learn" / "runs" / f"{run_id}.json").read_text())
+ delete_message = f"codegraff.learn.delete.v1\n{run_id}\n{run['nonce']}".encode()
+ expected_delete_token = hmac.new(key, delete_message, hashlib.sha256).hexdigest()
+ assert GradeCapture.deletions == [(f"/v1/learning/{run_id}", expected_delete_token)]
payload = GradeCapture.payloads[0]
encoded = json.dumps(payload, separators=(",", ":"))
assert "prompt_text" not in encoded and "Learned fixture policy" not in encoded
resource = payload["resourceLogs"][0]
resource_attrs = {item["key"]: next(iter(item["value"].values())) for item in resource["resource"]["attributes"]}
- assert resource_attrs["client.name"] == "harness-learn"
+ assert resource_attrs == {"client.name": "harness-learn"}
+ assert not (root / ".simple-harness-install-id").exists()
records = resource["scopeLogs"][0]["logRecords"]
assert len(records) == 2
- for record in records:
- assert record["body"]["stringValue"] == "score"
- attrs = {item["key"]: next(iter(item["value"].values())) for item in record["attributes"]}
- assert attrs["run_id"] == run_id and attrs["value"] == 1
- message = "\n".join(
- [
- "v2", attrs["prompt_sha"], attrs["parent_sha"], f'{attrs["value"]:.6f}',
- attrs["run_id"], attrs["judge_id"], attrs["artifact_sha"],
- attrs["eval_set_hash"], attrs["niche"], attrs["provider_class"],
- ]
- ).encode()
- assert attrs["sig"] == hmac.new(key, message, hashlib.sha256).hexdigest()
+ assert_learning_records(records, run_id, key, 1, expected_delete_token)
def status(graff: Path, workspace: Path, env: dict[str, str]) -> dict[str, Any]:
diff --git a/tests/learn_graff_adapters.py b/tests/learn_graff_adapters.py
index 4ff5e811..4f84925b 100755
--- a/tests/learn_graff_adapters.py
+++ b/tests/learn_graff_adapters.py
@@ -20,18 +20,24 @@ SETTINGS = ROOT / "examples" / "learn_graff_evaluator.json"
PREPARE = ROOT / "examples" / "prepare_graff_tournament.py"
FAKE_GRAFF = r'''#!/usr/bin/env python3
-import json, pathlib, sys
+import json, os, pathlib, sys
args = sys.argv[1:]
-system = args[args.index("--system-prompt") + 1]
+if os.environ.get("HARNESS_CLIENT") == "learn-evaluator":
+ assert "--system-prompt" not in args
+system = args[args.index("--system-prompt") + 1] if "--system-prompt" in args else None
turns = 0
for raw in sys.stdin:
value = json.loads(raw)
kind = value.get("type")
- if kind == "set_model":
+ if kind == "set_system_prompt":
+ system = value["text"]
+ event = {"type":"system_prompt","ok":True,"append":False,"chars":len(system.encode("utf-8"))}
+ elif kind == "set_model":
event = {"type":"model","ok":True,"provider":value["provider"],"model":value["model"]}
elif kind == "set_effort":
event = {"type":"effort","ok":True,"level":value["level"],"applies":True}
elif kind == "user":
+ assert system is not None
if "concise clause" in system:
turns += 1
text = "invalid first attempt" if turns == 1 else json.dumps({
@@ -196,18 +202,36 @@ def run() -> None:
assert len({case["id"] for case in holdout["cases"]}) == 40
primary_ids = [case["id"] for case in primary["cases"]]
holdout_ids = [case["id"] for case in holdout["cases"]]
+ unit_count = lambda cases: len({
+ case.get("statistical_unit_id", case["id"]) for case in cases
+ })
+ assert preparation["primary_units"] == unit_count(primary["cases"]) == 44
+ assert preparation["holdout_units"] == unit_count(holdout["cases"]) == 40
+ for prefix, unit in (
+ ("edit-noop-random-", "edit-noop"),
+ ("edit-filter-random-", "edit-filter"),
+ ("edit-dedupe-random-", "edit-dedupe"),
+ ("edit-copy-random-", "edit-copy"),
+ ):
+ clustered = [case for case in primary["cases"] if case["id"].startswith(prefix)]
+ assert len(clustered) == 5
+ assert {case["statistical_unit_id"] for case in clustered} == {unit}
assert [sum(item.startswith(prefix) for item in primary_ids) for prefix in (
"semantic-", "edit-", "dependency-", "economy-",
)] == [10, 30, 10, 10]
assert [sum(item.startswith(prefix) for item in holdout_ids) for prefix in (
- "fresh-sem-", "fresh-edit-", "fresh-dep-", "fresh-econ-",
- )] == [7, 19, 7, 7]
+ "fresh-sem-", "fresh-edit-", "fresh-dep-", "fresh-econ-", "fresh-shift-",
+ )] == [7, 11, 7, 7, 8]
configured_target = json.loads(ARMS.read_text(encoding="utf-8"))["targets"]["root_workflow"]
prepared_parent = (prepared / "parent.md").read_text(encoding="utf-8")
assert prepared_parent.count(configured_target) == 1
assert config["gate"]["default_candidates"] == 4
assert config["gate"]["promotion_mode"] == "economy"
assert config["gate"]["require_all_candidates"] is True
+ assert config["gate"]["minimum_pairs"] <= preparation["primary_units"]
+ assert config["gate"]["minimum_pairs"] <= preparation["holdout_units"]
+ assert config["cohort"]["adapter_version"] == "graff-eval-v7"
+ assert config["cohort"]["verifier_version"] == "clustered-exact-v6"
assert config["auto"] == {"enabled": False}
suite = root / "suite.json"
diff --git a/tests/learn_graff_evaluator_retries.py b/tests/learn_graff_evaluator_retries.py
index 47899dc6..a083290d 100644
--- a/tests/learn_graff_evaluator_retries.py
+++ b/tests/learn_graff_evaluator_retries.py
@@ -8,7 +8,11 @@ import io
import json
import os
from pathlib import Path
+import signal
+import subprocess
+import sys
import tempfile
+import time
import unittest
from unittest import mock
@@ -53,6 +57,7 @@ class RetryAccountingTests(unittest.TestCase):
def test_terminal_error_carries_observed_resources(self) -> None:
events = [
+ {"type": "system_prompt", "ok": True, "append": False, "chars": 7},
{"type": "model", "provider": "codex", "model": "test-model"},
{"type": "effort", "level": "low", "applies": True},
*({"type": "tool_call"} for _ in range(4)),
@@ -89,7 +94,7 @@ class RetryAccountingTests(unittest.TestCase):
mock.patch.object(EVALUATOR.time, "monotonic", side_effect=(1.0, 1.03)):
with self.assertRaises(EVALUATOR.EvaluationAttemptError) as raised:
EVALUATOR.run_variant(
- Path("/unused-graff"), settings, "prompt", {"task": "task"}, Path.cwd()
+ Path("/unused-graff"), settings, "prømpt", {"task": "task"}, Path.cwd()
)
self.assertEqual(raised.exception.tool_calls, 4)
self.assertEqual(raised.exception.latency_ms, 30)
@@ -142,7 +147,7 @@ class RetryAccountingTests(unittest.TestCase):
child_attempts = 0
child_scratch: list[Path] = []
- def fake_run_variant(graff, settings, prompt, case, cwd):
+ def fake_run_variant(graff, settings, prompt, case, cwd, observer=None):
nonlocal child_attempts
self.assertEqual((cwd / "fixture.txt").read_text(encoding="utf-8"), "clean")
if prompt == "parent":
@@ -185,6 +190,157 @@ class RetryAccountingTests(unittest.TestCase):
self.assertGreater(pair["child_cost_micros"], pair["parent_cost_micros"])
self.assertNotIn("attempt_count", pair)
+ def test_abrupt_process_loss_recovers_journaled_resources_and_completed_side(self) -> None:
+ with tempfile.TemporaryDirectory(prefix="learn-attempt-journal-") as raw_temp:
+ temp = Path(raw_temp)
+ prompt = "SENSITIVE PROMPT MUST NOT ENTER JOURNAL"
+ case = {"task": "private task", "check": {"exact": "ok"}}
+ pair = {"case_id": "journal-case", "seed": "f"}
+ key = EVALUATOR.attempt_key("a" * 64, pair, "child", prompt)
+ journal = Path(".attempt-child.json")
+ settings = {"max_attempts": 2}
+
+ def abrupt(graff, settings, prompt, case, cwd, observer=None):
+ assert observer is not None
+ observer({"latency_ms": 17, "tool_calls": 3, "cost_micros": 13})
+ raise SystemExit(99)
+
+ original_cwd = Path.cwd()
+ os.chdir(temp)
+ try:
+ with mock.patch.object(EVALUATOR, "run_variant", side_effect=abrupt), \
+ self.assertRaises(SystemExit):
+ EVALUATOR.run_with_retries(
+ temp / "graff", settings, prompt, case, "child", key, journal,
+ )
+ partial = json.loads(journal.read_text(encoding="utf-8"))
+ self.assertFalse(partial["complete"])
+ self.assertEqual(partial["metrics"], {
+ "latency_ms": 17, "tool_calls": 3, "cost_micros": 13,
+ })
+
+ def succeeds(graff, settings, prompt, case, cwd, observer=None):
+ return {
+ "pass": True, "score_ppm": 1_000_000,
+ "latency_ms": 5, "tool_calls": 2, "cost_micros": 11,
+ }
+
+ with mock.patch.object(EVALUATOR, "run_variant", side_effect=succeeds):
+ recovered = EVALUATOR.run_with_retries(
+ temp / "graff", settings, prompt, case, "child", key, journal,
+ )
+ self.assertEqual(recovered["latency_ms"], 22)
+ self.assertEqual(recovered["tool_calls"], 5)
+ self.assertEqual(recovered["cost_micros"], 24)
+
+ with mock.patch.object(
+ EVALUATOR, "run_variant", side_effect=AssertionError("reran completed side"),
+ ):
+ cached = EVALUATOR.run_with_retries(
+ temp / "graff", settings, prompt, case, "child", key, journal,
+ )
+ self.assertEqual(cached, recovered)
+ encoded = journal.read_text(encoding="utf-8")
+ self.assertNotIn(prompt, encoded)
+ self.assertNotIn(case["task"], encoded)
+ finally:
+ os.chdir(original_cwd)
+
+ @unittest.skipIf(sys.platform == "win32", "POSIX process-group crash injection")
+ def test_real_evaluator_process_death_preserves_observed_usage(self) -> None:
+ with tempfile.TemporaryDirectory(prefix="learn-real-process-loss-") as raw_temp:
+ temp = Path(raw_temp)
+ settings = temp / "settings.json"
+ suite = temp / "suite.json"
+ request = temp / "request.json"
+ response = temp / "response.json"
+ parent = temp / "parent.md"
+ fake_graff = temp / "fake-graff.py"
+ settings.write_text(json.dumps({
+ "schema": "codegraff.learn.graff-evaluator.v1",
+ "provider": "codex", "model": "test-model", "effort": "low",
+ "max_model_calls": 4, "max_tool_calls": 4,
+ "max_attempts": 1, "task_timeout_seconds": 30,
+ }), encoding="utf-8")
+ suite.write_text(json.dumps({
+ "schema": "codegraff.learn.suite.v1",
+ "cases": [{
+ "id": "crash-case",
+ "payload": {"task": "private crash task", "check": {"exact": "ok"}},
+ }],
+ }), encoding="utf-8")
+ parent.write_text("private parent prompt", encoding="utf-8")
+ request.write_text(json.dumps({
+ "schema": EVALUATOR.BASELINE_REQUEST_SCHEMA,
+ "trial_id": "trial", "cohort_id": "cohort",
+ "suite_path": str(suite), "suite_sha256": "suite",
+ "parent": {"id": "parent", "path": str(parent)},
+ "pairs": [{"case_id": "crash-case", "seed": "0"}],
+ }), encoding="utf-8")
+ fake_graff.write_text(f"#!{sys.executable}\n" + r'''import json, os, sys, time
+complete = os.environ.get("FAKE_COMPLETE") == "1"
+assert "--system-prompt" not in sys.argv
+for raw in sys.stdin:
+ message = json.loads(raw)
+ if message.get("type") == "set_system_prompt":
+ text = message["text"]
+ print(json.dumps({"type":"system_prompt","ok":True,"append":False,"chars":len(text.encode("utf-8"))}), flush=True)
+ elif message.get("type") == "set_model":
+ print(json.dumps({"type":"model","provider":"codex","model":"test-model"}), flush=True)
+ elif message.get("type") == "set_effort":
+ print(json.dumps({"type":"effort","level":"low","applies":True}), flush=True)
+ elif message.get("type") == "user":
+ cost = 0.000011 if complete else 0.000013
+ print(json.dumps({"type":"tool_call","cost_usd":cost}), flush=True)
+ if complete:
+ print(json.dumps({"type":"turn","complete":True,"text":"ok","cost_usd":cost}), flush=True)
+ break
+ time.sleep(30)
+''', encoding="utf-8")
+ fake_graff.chmod(0o700)
+ command = [
+ sys.executable, str(REPO / "examples" / "learn_graff_evaluator.py"),
+ str(settings), str(fake_graff), "baseline", str(request), str(response),
+ ]
+ first_env = {**os.environ, "FAKE_COMPLETE": "0"}
+ first = subprocess.Popen(
+ command, cwd=temp, env=first_env,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ start_new_session=True,
+ )
+ journal = temp / ".attempt-baseline.json"
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ if journal.exists():
+ value = json.loads(journal.read_text(encoding="utf-8"))
+ if value.get("metrics", {}).get("cost_micros") == 13:
+ break
+ time.sleep(0.02)
+ else:
+ first.kill()
+ self.fail("evaluator did not durably journal the in-flight attempt")
+ commands = subprocess.run(
+ ["ps", "-Ao", "command="], capture_output=True, text=True, check=True,
+ ).stdout
+ self.assertNotIn("private parent prompt", commands)
+ os.killpg(first.pid, signal.SIGKILL)
+ first.communicate(timeout=5)
+
+ completed = subprocess.run(
+ command, cwd=temp, env={**os.environ, "FAKE_COMPLETE": "1"},
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ timeout=20, check=False,
+ )
+ self.assertEqual(completed.returncode, 0, completed.stderr)
+ result = json.loads(response.read_text(encoding="utf-8"))["pairs"][0]
+ self.assertEqual(result["tool_calls"], 2)
+ self.assertEqual(result["cost_micros"], 24)
+ self.assertGreaterEqual(result["latency_ms"], 0)
+ self.assertFalse(journal.exists())
+ encoded_progress = (temp / ".baseline-progress.json").read_text(encoding="utf-8")
+ self.assertNotIn("private parent prompt", encoded_progress)
+ self.assertNotIn("private crash task", encoded_progress)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/learn_tournament_e2e.py b/tests/learn_tournament_e2e.py
index 344f1af8..64792bc6 100755
--- a/tests/learn_tournament_e2e.py
+++ b/tests/learn_tournament_e2e.py
@@ -6,6 +6,8 @@ from __future__ import annotations
import argparse
from collections import Counter
import copy
+import hashlib
+import hmac
from http.server import ThreadingHTTPServer
import json
import os
@@ -16,6 +18,8 @@ import tempfile
import threading
import time
+from learning_receipt_assertions import assert_learning_records
+
from learn_e2e import (
GradeCapture,
invoke,
@@ -41,6 +45,16 @@ deadline = time.monotonic() + 10
while len(list(barrier.glob("mutation-*"))) != 4:
assert time.monotonic() < deadline, "mutations did not run concurrently"
time.sleep(0.01)
+attempt_path = barrier / f"mutator-attempts-{index}"
+attempts = int(attempt_path.read_text()) if attempt_path.exists() else 0
+attempt_path.write_text(str(attempts + 1))
+retry_marker = barrier / f"mutator-retried-{index}"
+if index == 0 and not retry_marker.exists():
+ retry_marker.write_text("retry")
+ raise SystemExit(19)
+if (barrier / f"fail-mutator-{index}").exists():
+ print("PRIVATE_ADAPTER_CANARY_DO_NOT_EXPOSE /Users/private/repository", file=sys.stderr)
+ raise SystemExit(31)
parent = pathlib.Path(request["parent"]["path"]).read_text()
child = parent.rstrip() + f"\n\nTournament variant {index}.\n"
child_bytes = child.encode()
@@ -52,7 +66,7 @@ response = {
"parent_id": request["parent"]["id"],
"child_path": request["child_path"],
"child_sha256": hashlib.sha256(child_bytes).hexdigest(),
- "description": f"fixture arm {index}",
+ "description": f"PRIVATE_MUTATION_DESCRIPTION_{index}_DO_NOT_RENDER",
}
pathlib.Path(response_path).write_text(json.dumps(response, separators=(",", ":")) + "\n")
'''
@@ -91,6 +105,11 @@ elif operation == "evaluate_primary":
while len(list(barrier.glob("primary-start-*"))) != 4:
assert time.monotonic() < deadline, "primary evaluations did not run concurrently"
time.sleep(0.01)
+ attempt_path = barrier / f"primary-attempts-{index}"
+ attempts = int(attempt_path.read_text()) if attempt_path.exists() else 0
+ attempt_path.write_text(str(attempts + 1))
+ if (barrier / f"fail-primary-{index}").exists():
+ raise SystemExit(29)
retry_marker = barrier / f"primary-retried-{index}"
if index == 0 and not retry_marker.exists():
retry_marker.write_text("retry")
@@ -119,7 +138,16 @@ elif operation == "evaluate":
assert suite["suite_id"] == "tournament-fresh-holdout"
index = request["candidate_index"]
assert len(list(barrier.glob("primary-done-*"))) == 4, "holdout started before the primary barrier"
- (barrier / "holdout-once").open("x").write(str(index))
+ holdout_marker = barrier / "holdout-once"
+ if holdout_marker.exists():
+ assert holdout_marker.read_text() == str(index), "resume changed the holdout winner"
+ else:
+ holdout_marker.write_text(str(index))
+ holdout_attempts = barrier / "holdout-attempts"
+ attempt_count = int(holdout_attempts.read_text()) if holdout_attempts.exists() else 0
+ holdout_attempts.write_text(str(attempt_count + 1))
+ if (barrier / "fail-holdout").exists():
+ raise SystemExit(23)
calls = [9, 7, 3, 5][index]
pairs = [{
"case_id": pair["case_id"], "seed": pair["seed"],
@@ -237,6 +265,10 @@ def exercise(graff: Path, root: Path) -> None:
assert sum(candidate["holdout"] is not None for candidate in record["candidates"]) == 1
winner = next(candidate for candidate in record["candidates"] if candidate["holdout"] is not None)
assert winner["primary"]["child_tool_calls"] == 24
+ assert all(
+ candidate["primary"]["correctness_regressions"] == 0
+ for candidate in record["candidates"]
+ )
parent_projections = {
(
candidate["primary"]["parent_passes"],
@@ -248,18 +280,40 @@ def exercise(graff: Path, root: Path) -> None:
assert parent_projections == {(0, 80, 800)}
assert winner["genome_id"] == record["primary_winner_genome_id"] == record["selected_genome_id"]
assert "manual promotion:" in output
+ assert "PRIVATE_MUTATION_DESCRIPTION" not in output
assert status(graff, workspace, env)["generation"] == 0
assert len(list(barrier.glob("mutation-*"))) == 4
+ assert (barrier / "mutator-retried-0").is_file()
+ assert [(barrier / f"mutator-attempts-{index}").read_text() for index in range(4)] == ["2", "1", "1", "1"]
assert (barrier / "baseline-once").read_text() == "parent"
assert len(list(barrier.glob("primary-done-*"))) == 4
assert (barrier / "holdout-once").read_text() == "2"
+ assert [(barrier / f"primary-attempts-{index}").read_text() for index in range(4)] == ["2", "1", "1", "1"]
+ assert (barrier / "holdout-attempts").read_text() == "1"
+
+ # A consumed holdout makes a new trial impossible, so reject it before
+ # spending another mutation or evaluation call.
+ adapter_attempts = [
+ (barrier / f"mutator-attempts-{index}").read_text() for index in range(4)
+ ]
+ consumed = invoke(graff, workspace, env, "run", "--candidates", "4", succeeds=False)
+ assert "HoldoutConsumed" in consumed.stderr
+ assert adapter_attempts == [
+ (barrier / f"mutator-attempts-{index}").read_text() for index in range(4)
+ ]
assert len(GradeCapture.payloads) == 1
encoded = json.dumps(GradeCapture.payloads[0], separators=(",", ":"))
assert "secret-internal-agent-name" not in encoded
assert "Tournament variant" not in encoded and "prompt_text" not in encoded
+ resource_attrs = GradeCapture.payloads[0]["resourceLogs"][0]["resource"]["attributes"]
+ assert {item["key"] for item in resource_attrs} == {"client.name"}
records = GradeCapture.payloads[0]["resourceLogs"][0]["scopeLogs"][0]["logRecords"]
assert len(records) == 5
+ key = key_path.read_bytes().strip()
+ message = f"codegraff.learn.delete.v1\n{run_id}\n{record['nonce']}".encode()
+ delete_token = hmac.new(key, message, hashlib.sha256).hexdigest()
+ assert_learning_records(records, run_id, key, 4, delete_token)
stages = Counter(attrs(item)["judge_id"] for item in records)
assert stages == {"learn-primary-v2": 4, "learn-holdout-v2": 1}
hashes = Counter(attrs(item)["eval_set_hash"] for item in records)
@@ -282,36 +336,239 @@ def exercise(graff: Path, root: Path) -> None:
assert "BaselineProjectionMismatch" in rejected.stderr
assert status(graff, workspace, env)["generation"] == 0
+ # Statistical grouping is suite-owned. Re-addressing a request with a
+ # forged unit ID must not let stored evidence collapse or inflate power.
+ forged_units = copy.deepcopy(record)
+ request_id = forged_units["candidates"][0]["primary"]["request_evidence_id"]
+ request = json.loads((learn_root / "evidence" / f"{request_id}.json").read_text())
+ request["pairs"][0]["statistical_unit_id"] = "forged-unit"
+ forged_request_id = write_forged_object(
+ learn_root / "evidence", "codegraff-learn/evidence/v1", request,
+ )
+ forged_units["candidates"][0]["primary"]["request_evidence_id"] = forged_request_id
+ forged_units_run_id = write_forged_object(
+ learn_root / "runs", "codegraff-learn/run/v1", forged_units,
+ )
+ rejected_units = invoke(
+ graff, workspace, env, "promote", forged_units_run_id, succeeds=False,
+ )
+ assert "PairMismatch" in rejected_units.stderr
+ assert status(graff, workspace, env)["generation"] == 0
+
+ # Raw regression counts are derived evidence, not trusted run metadata.
+ # Omitting a real regression or inventing one must mismatch recomputation.
+ forged_regressions = copy.deepcopy(record)
+ forged_regressions["candidates"][0]["primary"]["correctness_regressions"] = 1
+ forged_regressions_run_id = write_forged_object(
+ learn_root / "runs", "codegraff-learn/run/v1", forged_regressions,
+ )
+ rejected_regressions = invoke(
+ graff, workspace, env, "promote", forged_regressions_run_id, succeeds=False,
+ )
+ assert "ComparisonMismatch" in rejected_regressions.stderr
+ assert status(graff, workspace, env)["generation"] == 0
+
# The untampered v3 evidence remains fully verifiable and promotable.
invoke(graff, workspace, env, "promote", run_id)
assert status(graff, workspace, env)["generation"] == 1
assert json.loads(invoke(graff, workspace, env, "verify").stdout)["integrity"] == "ok"
- # A ranked but underpowered primary is persisted without exposing the
- # hidden suite at all.
+ # A suite that meets minimum_pairs but cannot possibly clear corrected
+ # significance is rejected before model calls or store initialization.
ineligible_workspace = root / "workspace-ineligible"
ineligible_barrier = root / "barrier-ineligible"
ineligible_workspace.mkdir(mode=0o700)
ineligible_barrier.mkdir(mode=0o700)
ineligible_config = copy.deepcopy(config)
- ineligible_config["gate"]["minimum_pairs"] = 9
+ ineligible_config["gate"]["alpha_ppm"] = 1_000
ineligible_config_path = root / "config-ineligible.json"
write_private(ineligible_config_path, json_bytes(ineligible_config))
ineligible_env = {**env, "TOURNAMENT_BARRIER": str(ineligible_barrier)}
- invoke(
+ underpowered = invoke(
graff, ineligible_workspace, ineligible_env, "init",
"--parent", str(parent.resolve()), "--config", str(ineligible_config_path.resolve()),
+ succeeds=False,
+ )
+ assert "InsufficientSignificancePower" in underpowered.stderr
+ assert not ineligible_workspace.joinpath(".graff", "learn").exists()
+ assert not (ineligible_barrier / "holdout-once").exists()
+
+ # Different bytes are not enough to make a holdout fresh. Reusing a
+ # primary statistical unit is rejected before store creation or adapters.
+ overlap_workspace = root / "workspace-overlap"
+ overlap_workspace.mkdir(mode=0o700)
+ overlap_holdout = tools / "overlap-holdout.json"
+ write_private(overlap_holdout, json_bytes({
+ "schema": "codegraff.learn.suite.v1",
+ "suite_id": "tournament-overlap-holdout",
+ "cases": [
+ {"id": "holdout-copy", "statistical_unit_id": "primary-0"},
+ *[{"id": f"fresh-{index}"} for index in range(7)],
+ ],
+ }))
+ overlap_config = copy.deepcopy(config)
+ overlap_config["holdout_suite"] = {
+ "path": str(overlap_holdout.resolve()),
+ "sha256": raw_sha256(overlap_holdout),
+ }
+ overlap_config_path = root / "config-overlap.json"
+ write_private(overlap_config_path, json_bytes(overlap_config))
+ overlapping = invoke(
+ graff, overlap_workspace, env, "init", "--parent", str(parent.resolve()),
+ "--config", str(overlap_config_path.resolve()), succeeds=False,
)
- ineligible_output = invoke(graff, ineligible_workspace, ineligible_env, "run", "--candidates", "4").stdout
- ineligible_record = json.loads(
- ineligible_workspace.joinpath(
- ".graff", "learn", "runs", f"{run_id_from(ineligible_output)}.json",
+ assert "HoldoutStatisticalUnitOverlap" in overlapping.stderr
+ assert not overlap_workspace.joinpath(".graff", "learn").exists()
+
+ # The run-time override is checked too: eight units can clear alpha=.01
+ # for one arm, but not after correcting for four requested arms.
+ override_workspace = root / "workspace-power-override"
+ override_barrier = root / "barrier-power-override"
+ override_workspace.mkdir(mode=0o700)
+ override_barrier.mkdir(mode=0o700)
+ override_config = copy.deepcopy(config)
+ override_config["gate"]["alpha_ppm"] = 10_000
+ override_config["gate"]["default_candidates"] = 1
+ override_config_path = root / "config-power-override.json"
+ write_private(override_config_path, json_bytes(override_config))
+ override_env = {**env, "TOURNAMENT_BARRIER": str(override_barrier)}
+ invoke(
+ graff, override_workspace, override_env, "init",
+ "--parent", str(parent.resolve()), "--config", str(override_config_path.resolve()),
+ )
+ impossible_override = invoke(
+ graff, override_workspace, override_env, "run", "--candidates", "4",
+ succeeds=False,
+ )
+ assert "InsufficientSignificancePower" in impossible_override.stderr
+ assert not list(override_barrier.glob("mutation-*"))
+
+ # A failure after holdout reservation leaves a verified, resumable trial.
+ # New runs cannot overwrite it, forged state fails closed, and resuming the
+ # original state must not repeat mutations, baseline, or primary arms.
+ resume_workspace = root / "workspace-resume"
+ resume_barrier = root / "barrier-resume"
+ resume_workspace.mkdir(mode=0o700)
+ resume_barrier.mkdir(mode=0o700)
+ resume_env = {**env, "TOURNAMENT_BARRIER": str(resume_barrier)}
+ invoke(
+ graff, resume_workspace, resume_env, "init",
+ "--parent", str(parent.resolve()), "--config", str(config_path.resolve()),
+ )
+ primary_fail_marker = resume_barrier / "fail-primary-1"
+ primary_fail_marker.write_text("fail both bounded primary attempts")
+ fail_marker = resume_barrier / "fail-holdout"
+ fail_marker.write_text("fail both bounded holdout attempts")
+ interrupted = invoke(
+ graff, resume_workspace, resume_env, "run", "--candidates", "4",
+ succeeds=False,
+ )
+ assert "ProcessFailed" in interrupted.stderr
+ pending_path = resume_workspace / ".graff" / "learn" / "refs" / "pending.json"
+ assert pending_path.is_file()
+ pending_bytes = pending_path.read_bytes()
+ pending_record = json.loads(pending_bytes)
+ pending_status = status(graff, resume_workspace, resume_env)
+ assert pending_status["pending_trial_id"] == pending_record["trial_id"]
+ assert pending_status["pending_primary_arms"] == 3
+ assert pending_status["pending_holdout_arms"] == 0
+ assert pending_status["pending_verified"] is False
+ verified_pending = json.loads(invoke(graff, resume_workspace, resume_env, "verify").stdout)
+ assert verified_pending["pending_verified"] is True
+ assert len(list(resume_barrier.glob("mutation-*"))) == 4
+ assert len(list(resume_barrier.glob("primary-done-*"))) == 3
+ assert (resume_barrier / "baseline-once").read_text() == "parent"
+ assert not (resume_barrier / "holdout-once").exists()
+
+ refused = invoke(
+ graff, resume_workspace, resume_env, "run", "--candidates", "4",
+ succeeds=False,
+ )
+ assert "PendingRunExists" in refused.stderr
+ assert "--resume" in refused.stdout
+
+ forged_pending = json.loads(pending_bytes)
+ forged_pending["trial_id"] = "0" * 64
+ write_private(pending_path, json_bytes(forged_pending))
+ forged_resume = invoke(
+ graff, resume_workspace, resume_env, "run", "--resume", "--candidates", "4",
+ succeeds=False,
+ )
+ assert "TrialMismatch" in forged_resume.stderr
+ forged_verify = invoke(graff, resume_workspace, resume_env, "verify", succeeds=False)
+ assert "TrialMismatch" in forged_verify.stderr
+ write_private(pending_path, pending_bytes)
+
+ primary_fail_marker.unlink()
+ holdout_interrupted = invoke(
+ graff, resume_workspace, resume_env, "run", "--resume", "--candidates", "4",
+ succeeds=False,
+ )
+ assert "ProcessFailed" in holdout_interrupted.stderr
+ holdout_pending_status = status(graff, resume_workspace, resume_env)
+ assert holdout_pending_status["pending_primary_arms"] == 4
+ assert holdout_pending_status["pending_holdout_arms"] == 0
+ assert (resume_barrier / "holdout-once").read_text() == "2"
+
+ fail_marker.unlink()
+ resumed_output = invoke(
+ graff, resume_workspace, resume_env, "run", "--resume", "--candidates", "4",
+ ).stdout
+ resumed_id = run_id_from(resumed_output)
+ assert "resuming checkpointed trial" in resumed_output
+ assert not pending_path.exists()
+ resumed_status = status(graff, resume_workspace, resume_env)
+ assert resumed_status["pending_trial_id"] is None
+ assert resumed_status["pending_primary_arms"] == 0
+ assert resumed_status["pending_holdout_arms"] == 0
+ assert resumed_status["pending_verified"] is True
+ assert len(list(resume_barrier.glob("mutation-*"))) == 4
+ assert len(list(resume_barrier.glob("primary-done-*"))) == 4
+ assert (resume_barrier / "baseline-once").read_text() == "parent"
+ assert (resume_barrier / "holdout-once").read_text() == "2"
+ assert [
+ (resume_barrier / f"primary-attempts-{index}").read_text()
+ for index in range(4)
+ ] == ["2", "3", "1", "1"]
+ assert (resume_barrier / "holdout-attempts").read_text() == "3"
+ resumed_record = json.loads(
+ resume_workspace.joinpath(
+ ".graff", "learn", "runs", f"{resumed_id}.json",
).read_text()
)
- assert ineligible_record["primary_winner_genome_id"] is not None
- assert ineligible_record["selected_genome_id"] is None
- assert all(candidate["holdout"] is None for candidate in ineligible_record["candidates"])
- assert not (ineligible_barrier / "holdout-once").exists()
+ assert sum(item["holdout"] is not None for item in resumed_record["candidates"]) == 1
+
+ # A persistent mutator failure gets exactly one retry. It fails before the
+ # baseline/primary barrier and cannot leave a misleading resumable record.
+ mutation_failure_workspace = root / "workspace-mutation-failure"
+ mutation_failure_barrier = root / "barrier-mutation-failure"
+ mutation_failure_workspace.mkdir(mode=0o700)
+ mutation_failure_barrier.mkdir(mode=0o700)
+ mutation_failure_env = {**env, "TOURNAMENT_BARRIER": str(mutation_failure_barrier)}
+ invoke(
+ graff, mutation_failure_workspace, mutation_failure_env, "init",
+ "--parent", str(parent.resolve()), "--config", str(config_path.resolve()),
+ )
+ (mutation_failure_barrier / "fail-mutator-1").write_text("fail both bounded attempts")
+ failed_mutation = invoke(
+ graff, mutation_failure_workspace, mutation_failure_env,
+ "run", "--candidates", "4", succeeds=False,
+ )
+ assert "IncompleteCandidateSet" in failed_mutation.stderr
+ assert "private diagnostics hidden" in failed_mutation.stderr
+ assert "PRIVATE_ADAPTER_CANARY_DO_NOT_EXPOSE" not in failed_mutation.stderr
+ assert mutator["program"] not in failed_mutation.stderr
+ assert Path(mutator["program"]).name not in failed_mutation.stderr
+ assert (mutation_failure_barrier / "mutator-attempts-1").read_text() == "2"
+ assert not (mutation_failure_barrier / "baseline-once").exists()
+ assert status(graff, mutation_failure_workspace, mutation_failure_env)["pending_trial_id"] is None
+
+ detailed_failure = invoke(
+ graff, mutation_failure_workspace, mutation_failure_env,
+ "run", "--candidates", "4", "--show-adapter-stderr", succeeds=False,
+ )
+ assert "PRIVATE_ADAPTER_CANARY_DO_NOT_EXPOSE" in detailed_failure.stderr
+ assert Path(mutator["program"]).name in detailed_failure.stderr
def main() -> int:
diff --git a/tests/learning_receipt_assertions.py b/tests/learning_receipt_assertions.py
new file mode 100644
index 00000000..c218cdcd
--- /dev/null
+++ b/tests/learning_receipt_assertions.py
@@ -0,0 +1,142 @@
+"""Independent verifier for aggregate learning OTLP receipt fixtures."""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import re
+from typing import Any
+
+SCHEMA = "codegraff.learn.grade.v2"
+INTEGER_FIELDS = (
+ "pairs", "statistical_units", "parent_passes", "child_passes",
+ "child_critical_failures", "critical_regressions", "correctness_regressions",
+ "delta_ppm", "mean_score_delta_ppm", "p_value_ppb", "tool_calls_measured",
+ "parent_tool_calls", "child_tool_calls", "tool_wins", "tool_losses", "tool_ties",
+ "tool_delta_ppm", "tool_p_value_ppb", "parent_cost_micros", "child_cost_micros",
+ "latency_measured", "parent_latency_ms", "child_latency_ms", "economy_eligible",
+ "eligible", "economy_gate_enabled", "alpha_ppm", "minimum_delta_ppm", "minimum_pairs",
+ "minimum_tool_reduction_ppm", "minimum_economy_pairs", "multiplicity",
+)
+CORE_FIELDS = {
+ "prompt_sha", "value", "parent_sha", "run_id", "sig", "judge_id",
+ "artifact_sha", "eval_set_hash", "provider_class", "niche",
+ "grade_schema", "grade_sig", "delete_token", "run_created_unix_ms",
+ "reason", "promotion_mode",
+}
+
+
+def attributes(record: dict[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for item in record["attributes"]:
+ value = item["value"]
+ if "intValue" in value:
+ result[item["key"]] = int(value["intValue"])
+ elif "doubleValue" in value:
+ result[item["key"]] = float(value["doubleValue"])
+ else:
+ result[item["key"]] = value["stringValue"]
+ return result
+
+
+def _signature(key: bytes, lines: list[str]) -> str:
+ return hmac.new(key, "\n".join(lines).encode(), hashlib.sha256).hexdigest()
+
+
+def _reduction_ppm(parent: int, child: int) -> int:
+ if parent == 0:
+ return 0 if child == 0 else -1_000_000
+ return max(-1_000_000, int((parent - child) * 1_000_000 / parent))
+
+
+def _assert_decision(values: dict[str, Any]) -> None:
+ significant = lambda name: (
+ values[name] * values["multiplicity"] <= values["alpha_ppm"] * 1_000
+ )
+ discordant = values["tool_wins"] + values["tool_losses"]
+ economy = bool(
+ values["economy_gate_enabled"]
+ and values["child_critical_failures"] == 0
+ and values["statistical_units"] >= values["minimum_pairs"]
+ and values["correctness_regressions"] == 0
+ and values["child_passes"] >= values["parent_passes"]
+ and values["mean_score_delta_ppm"] >= 0
+ and values["tool_calls_measured"]
+ and discordant >= values["minimum_economy_pairs"]
+ and values["tool_delta_ppm"] >= values["minimum_tool_reduction_ppm"]
+ and significant("tool_p_value_ppb")
+ )
+ assert values["economy_eligible"] == int(economy)
+ if values["child_critical_failures"]:
+ reason = "critical_regression" if values["critical_regressions"] else "critical_failure"
+ eligible = False
+ elif values["statistical_units"] < values["minimum_pairs"]:
+ reason, eligible = "minimum_pairs", False
+ elif values["promotion_mode"] == "correctness" and values["delta_ppm"] >= values["minimum_delta_ppm"] and significant("p_value_ppb"):
+ reason, eligible = "eligible", True
+ elif values["promotion_mode"] == "economy" and economy:
+ reason, eligible = "economy_eligible", True
+ elif values["promotion_mode"] == "economy" and (values["correctness_regressions"] or values["child_passes"] < values["parent_passes"] or values["mean_score_delta_ppm"] < 0):
+ reason, eligible = "correctness_regression", False
+ elif values["promotion_mode"] == "economy" and not values["tool_calls_measured"]:
+ reason, eligible = "tool_calls_unmeasured", False
+ elif values["promotion_mode"] == "economy" and discordant < values["minimum_economy_pairs"]:
+ reason, eligible = "minimum_economy_pairs", False
+ elif values["promotion_mode"] == "economy" and values["tool_delta_ppm"] < values["minimum_tool_reduction_ppm"]:
+ reason, eligible = "minimum_tool_reduction", False
+ elif values["promotion_mode"] == "economy" and not significant("tool_p_value_ppb"):
+ reason, eligible = "economy_not_significant", False
+ elif values["delta_ppm"] < values["minimum_delta_ppm"]:
+ reason, eligible = "minimum_delta", False
+ else:
+ reason, eligible = "not_significant", False
+ assert (values["reason"], values["eligible"]) == (reason, int(eligible))
+
+
+def assert_learning_records(
+ records: list[dict[str, Any]], run_id: str, key: bytes,
+ primary_multiplicity: int, delete_token: str,
+) -> None:
+ assert records
+ for record in records:
+ assert record["body"]["stringValue"] == "score"
+ values = attributes(record)
+ assert set(values) == CORE_FIELDS | set(INTEGER_FIELDS)
+ assert values["run_id"] == run_id
+ assert values["delete_token"] == delete_token
+ assert values["grade_schema"] == SCHEMA
+ assert re.fullmatch(r"[0-9a-f]{16}", values["prompt_sha"])
+ assert re.fullmatch(r"[0-9a-f]{16}", values["parent_sha"])
+ for field in ("run_id", "artifact_sha", "eval_set_hash"):
+ assert re.fullmatch(r"[0-9a-f]{64}", values[field])
+ event_ms = int(record["timeUnixNano"]) // 1_000_000
+ assert 0 <= event_ms - values["run_created_unix_ms"] < 60_000
+ expected_multiplicity = primary_multiplicity if values["judge_id"] == "learn-primary-v2" else 1
+ assert values["multiplicity"] == expected_multiplicity
+ assert values["value"] == values["child_passes"] / values["pairs"]
+ assert values["delta_ppm"] == int(
+ (values["child_passes"] - values["parent_passes"]) * 1_000_000 / values["pairs"]
+ )
+ assert values["tool_delta_ppm"] == _reduction_ppm(
+ values["parent_tool_calls"], values["child_tool_calls"]
+ )
+ if values["tool_calls_measured"]:
+ assert values["tool_wins"] + values["tool_losses"] + values["tool_ties"] == values["statistical_units"]
+ else:
+ assert values["tool_wins"] == values["tool_losses"] == values["tool_ties"] == 0
+ _assert_decision(values)
+
+ score_lines = [
+ "v2", values["prompt_sha"], values["parent_sha"], f'{values["value"]:.6f}',
+ values["run_id"], values["judge_id"], values["artifact_sha"],
+ values["eval_set_hash"], values["niche"], values["provider_class"],
+ ]
+ assert hmac.compare_digest(values["sig"], _signature(key, score_lines))
+ grade_lines = [SCHEMA, *score_lines[1:], values["delete_token"],
+ str(values["run_created_unix_ms"]), *(str(values[field]) for field in INTEGER_FIELDS),
+ values["reason"], values["promotion_mode"]]
+ assert hmac.compare_digest(values["grade_sig"], _signature(key, grade_lines))
+
+ encoded = repr(values)
+ for forbidden in ("prompt_text", "task", "adapter_output", "/Users/", "PRIVATE_"):
+ assert forbidden not in encoded