diff --git a/docs/design/e0-12-outcome-route-decision.adoc b/docs/design/e0-12-outcome-route-decision.adoc new file mode 100644 index 00000000..5471111d --- /dev/null +++ b/docs/design/e0-12-outcome-route-decision.adoc @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += E0-12: Outcome route and observation identity decision +:toc: +:date: 2026-11-23 + +Status: PROPOSED; no owner ruling is recorded here. The bounded NS-02 producer +identity patch can be reviewed, but full E0-12 closure and automatic delivery +remain unqualified. Production dispatch remains quarantined. + +== Decision requested + +Adopt the existing trusted fleet importer as the sole admission path for a +producer-identified attempt. Retain Hypatia's rescan as evidence about that +attempt, with explicit correlation and at most one effective contribution to +learning per attempt. The current direct callback must cease creating an +additional independent qualified attempt for the same dispatch. + +This is the recommended contract direction, not an implemented route change +or a claim that the observation/revision schema already exists. It needs the +owner's ruling because the existing May contract requires the direct recording +call, while the E0 design introduces a distinct identity-preserving importer. + +== Authorities and measured sources + +The Hypatia sources below are pinned at +`d158aed87f76b93e4f291e995bef9f26559c7fb2`; the inspected fleet baseline is +`f1b14e2a352491ff7972f0dfd592bfbb28d2f32c`. + +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/operations/e0-closeout/work-orders/E0-12-fleet-writes-event-id.adoc[E0-12] + requires one identity per attempt and equal identities on its mirrored rows. + Its stop condition says that two different outcome rows from an attempt + need identities and a design explaining their relationship. +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/design/e0-receipt.adoc[E0 receipt design], + section 5.2 and accepted D4, names + `shared-context/learning/fix-attempts.jsonl` beside the fleet outcome feed. + Starts carry no evidence credit and do not consume an outcome's identity. +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/operations/e0-closeout/work-orders/E0-31-event-id-task.adoc[E0-31] + records the newer owner choice of `mix hypatia.event_id` for the producer. +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/operations/dispatch-runner-contract.adoc[The May dispatch-runner contract] + says the runner MUST call `mix hypatia.record_outcome` after a fix and retains + default rescan behavior. Its later verdict table makes failed/incomplete + calls qualified failures without a rescan. + +== S-01: Producer-to-learning admission + +[cols="2,3,3",options="header"] +|=== +|Path |Current behavior |Identity and qualification +|Producer start +|The NS-02 patch writes `shared-context/learning/fix-attempts.jsonl`. +|One producer ID, before execution; no outcome or evidence credit. +|Producer outcome +|The runner writes `$HYPATIA_DATA/outcomes/YYYY-MM.jsonl` and a central copy at +`$VERISIMDB_DATA/outcomes/YYYY-MM.jsonl` when those stores differ. +|Both copies retain one producer ID. These raw rows have a verdict but no +Hypatia `verification` field; their mere presence in a learning-store directory +does not qualify them. +|Direct recording callback +|The runner calls Mix from `$HYPATIA_HOME`. Hypatia resolves its data through +`HYPATIA_VERISIM_DATA_PATH`, not the runner's `HYPATIA_DATA` variable. +|The public task creates a newly identified `local_caller` or `local_rescan` +row. A failed/incomplete verdict can be qualified immediately. +|Fleet importer +|`LearningScheduler.ingest_fleet_outcomes/1` reads only +`$HYPATIA_FLEET_PATH/shared-context/learning/fix-outcomes.jsonl`. +|The trusted import preserves a valid producer ID and deduplicates persisted +`fleet_import_id` values. No current runner forwarding step joins these paths. +|=== + +The direct call also emits an echo marked `bot=hypatia`; the importer skips +that echo. The echo alone is not the duplicate-credit defect demonstrated +below. Its missing event ID is an additional existing gap against ruled R6; +this patch does not silently repair that separate path. + +The raw monthly file and the qualified consumer store must not be treated as +interchangeable. Code inspection indicates that publishing the same producer +ID into both raw and admitted rows within the receipt lookup's store can make +lookup depend on row order: +https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/lib/hypatia/receipt.ex[`Receipt.locate/2`] +returns the first matching event-ID row. This is an inference from the pinned +implementation, not an additional executed counterexample. +The selected route must separate transport mirrors from the canonical +learning ledger, not merely add a third write. + +== Executed counterexample + +The producer fixture uses the real canonical Mix generator and an inert +throwaway fixer. It emits two distinct failed attempts and their exact +primary/central copies. The wire witness transfers those bytes explicitly to +the importer and passes three checks: identity/mirror fidelity, start exclusion +and replay-safe import, and absence of implicit qualification for raw monthly +rows. This is compatibility evidence, not automatic delivery. + +`tests/hypatia-route-counterexample.exs` then takes one actual emitted failure, +calls the actual `Mix.Tasks.Hypatia.RecordOutcome` task with its labels, verifies +that the echo imports nothing, and explicitly appends the producer row to the +importer's feed. On the pinned Hypatia base it reports: + +[cols="2,1",options="header"] +|=== +|Measurement |Observed +|Actual emitted attempts selected |1 +|Qualified failure contributions after the direct task |1 +|Qualified failure contributions after adding the producer row |2 +|Distinct persisted event IDs |2 +|Receipts |2 +|Counterexample process exit |1 +|Automatic delivery exercised |No +|=== + +The negative result falsifies joining the current paths while leaving the +independent recording callback active. It is deliberately not converted into +an expected-bad passing test. A future exclusive-ingress design needs an +acceptance test through its actual chosen flow; this artificial dual-call +diagnostic is not a universal acceptance condition for every possible design. + +Reproduce both witnesses from a configured test Hypatia checkout: + +[source,shell] +---- +# Set these to the two isolated checkouts; do not use a live fleet store. +export FLEET_CHECKOUT=/absolute/gitbot-fleet +export HYPATIA_CHECKOUT=/absolute/hypatia +export DISPATCH_TEST_HYPATIA_HOME="$HYPATIA_CHECKOUT" +export DISPATCH_TEST_MIX_BIN="$(command -v mix)" +export DISPATCH_TEST_EVIDENCE_DIR="$(mktemp -d)" +export MIX_ENV=test +bash "$FLEET_CHECKOUT/scripts/tests/dispatch-paths.sh" +cd "$HYPATIA_CHECKOUT" +mix run --no-start "$FLEET_CHECKOUT/tests/hypatia-event-import-test.exs" +mix run --no-start "$FLEET_CHECKOUT/tests/hypatia-route-counterexample.exs" +# The final command currently exits 1 and reports the duplicate contribution. +---- + +== Recommended ruling: one attempt admission, correlated rescan evidence + +. Use the trusted E0-11 fleet import as the canonical admission path for + producer-identified dispatch attempts. The source is append-only; primary + and central transport copies remain one attempt. Mirrors live outside the + canonical learning store and never create extra admitted trials. +. Retain rescan verification, but change the current mandatory recording + callback into a verification/evidence step for that admitted attempt. It + must not independently record another qualified attempt. Revise the May + callback contract explicitly as part of implementation. +. An attempt's ID, an observation's ID and a qualification revision's ID have + distinct meanings. Bind any separately stored rescan observation to the + attempt through a restricted, source-bound contract. A public caller's + syntax-valid UUID is insufficient provenance. +. Derive at most one current contribution per attempt. Multiple observations + are evidence for that contribution, not additional successes, failures or + qualified false positives. Preserve the existing separate false-positive + accounting. + Conflicting observations must use an explicit qualification/retraction rule + and preserve the history. E0-35's withdrawal work remains a dependency; + approval of this direction does not claim that machinery is implemented. +. Do not silently reuse `parent_event_ids` for an unruled relation. D7 defines + that field for receipt revision ancestry. The detailed observation/attempt + correlation and its relation to D7 must be written and reviewed before code + relies on them. +. Preserve legacy rows and uncertainty. Do not infer common attempt identity + from equal content, timestamps or recipe names: two identical attempts may + be distinct. Historical reconciliation needs its own evidence and receipts. + +The invariant can be stated without inventing new mathematics: count effective +attempt qualifications, not raw rows or observations. A single attempt may +contribute at most one effective qualified contribution -- success, failure +or qualified false positive -- or none, under the existing gate. Qualified +false positives retain their current separate accounting, as implemented by +https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/lib/outcome_tracker.ex[`OutcomeTracker.qualified_outcome_counts/1`]. +A later authorised revision changes that effective contribution without +erasing prior evidence. + +=== Alternative: make a new restricted direct recorder the sole ingress + +The direct route could instead become an idempotent trusted producer-admission +API, while fleet files become audit-only for those events. This preserves more +of the current invocation shape, but requires new admission/provenance and +offline/replay machinery and an explicit restriction on E0-11. Adding a public +`--event-id` option is not that machinery: `OutcomeTracker.record_outcome/5` +deliberately strips caller identity to prevent forged replay/receipt identity, +and the current qualification fold counts rows even if their IDs agree. + +The importer option reuses the existing persisted producer identity, source +hash and replay controls and is recommended. Neither option is activated by +the bounded NS-02 producer patch. + +== Work authorised by approval of the recommended direction + +Prepare the explicit contract amendment and correlated observation design; +implement one source-bound admission path in isolated changes; and demonstrate +the actual producer-to-consumer flow with fault, replay, mirror, conflict and +forged-identity controls. Preserve the existing qualification criteria and +quarantine while those gates are developed. E0 acceptance, production +activation and any Kautz qualification remain separate decisions supported by +their own evidence. diff --git a/docs/operations/NS-02-producer-identity.adoc b/docs/operations/NS-02-producer-identity.adoc new file mode 100644 index 00000000..3b2c984f --- /dev/null +++ b/docs/operations/NS-02-producer-identity.adoc @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += NS-02: Bounded producer identity evidence +:toc: +:date: 2026-11-23 + +Status: implemented and independently reviewed for the bounded producer +contract. Full E0-12 closure remains blocked on the route and observation +decision in `docs/design/e0-12-outcome-route-decision.adoc`. No production +dispatch or quarantine removal occurred. + +Fleet base: `f1b14e2a352491ff7972f0dfd592bfbb28d2f32c`. +Hypatia generator/importer base: `d158aed87f76b93e4f291e995bef9f26559c7fb2`. +E0-11 and E0-31 were confirmed in that Hypatia ancestry, at `6de3764` +(PR #1165) and `00ee725` (PR #1213). The existing receipt design fixes the +start record; the later E0-31 ruling fixes the Mix tooling choice. + +== Behavior + +An executable fix attempt calls `mix hypatia.event_id` once and checks the +canonical final output line. Nonzero generator exit is refused even if stdout +contains a plausible ID. Final-line checking follows the task's documented +handling of first-run compile chatter; it is validation, not a new generator. + +Before either fix-script or RRA execution, the producer appends the exact +sorted six-field start to +`$FLEET_ROOT/shared-context/learning/fix-attempts.jsonl`. Failed identity or +start persistence prevents the fix. An interrupted attempt leaves a start +without an outcome. + +The existing primary and central outcome destinations are preserved. Their +copies carry the same producer ID and serialized bytes. Primary failure +prevents later mirror/direct-report calls; mirror failure retains the primary +row and reports failure. New infrastructure failures propagate from parallel +children to the parent through a narrow marker alongside the existing tally; +success counters are added after successful outcome persistence. + +The production exit 78 before manifest processing and the complete licence +refusal branch remain unchanged. A policy refusal does not become a fix +attempt and keeps its existing row shape. No public caller may supply trusted +receipt identity through a new CLI flag. + +== Failing-before evidence and correction + +* Against unchanged producer source, the new row-identity assertion found + `null`: 62 existing checks passed and the new assertion failed. +* The whole-runner fixture showed the fixer executing without its required + start record. +* Independent review found that the old parallel drain discarded the new + infrastructure failure return. A failing-before control showed two failed + generator jobs, `FAILED=2`, and overall exit zero. The explicit error marker + now makes that case fail visibly. +* The existing smoke test assumed Mix was present in two no-call cases. Its + inert presence stub makes those assertions independent of the host without + allowing a real Mix call or changing production behavior. + +== Completed checks + +[cols="3,2",options="header"] +|=== +|Command / scope |Result +|`bash tests/outcome-verdict-test.sh` +|63 outcome checks pass; it also invokes the 112-check whole-runner fixture. +|`bash tests/automation-quarantine-test.sh` +|Seven blocked entrypoints and the no-publication/state-mutation assertion pass. +|`bash tests/hypatia-record-outcome-smoke.sh` +|5 checks pass. +|`bash scripts/tests/dispatch-paths.sh` with the actual canonical Mix generator +|112 checks pass, including serial and parallel generator/start/primary/mirror failures. +|`bash -n` on the four changed shell files; `git diff --check` +|Pass. ShellCheck was unavailable locally. +|`tests/hypatia-event-import-test.exs`, run by `MIX_ENV=test mix run --no-start` from Hypatia +|3 checks pass using actual emitted rows and an explicit test transfer. +|`mix test test/learning_scheduler_test.exs test/event_id_test.exs test/mix_tasks/event_id_test.exs --seed 0` from Hypatia +|56 tests pass, zero failures, covering the existing importer and event-ID contracts. +|`tests/hypatia-route-counterexample.exs`, same isolated runtime +|Exit 1: one actual attempt yields two qualified failures and two receipts after direct recording plus explicit import. This unresolved integration failure remains visible. +|=== + +The real generator and consumer witness used Elixir 1.19.4 / OTP 27.3.4.19, +matching Hypatia's pin. The fixture runs only a disposable copy of the runner, +using the pre-existing quarantine test seam and inert temporary fixes. The +unmodified production entrypoint is separately required to return 78. No +test makes a production exception or enables dispatch through an environment +switch. + +The harness can preserve actual rows under `DISPATCH_TEST_EVIDENCE_DIR`: +`success-starts.jsonl`, `success-primary.jsonl`, `success-central.jsonl`, and +the corresponding three `failure-*` files. Each primary/start pair contains +two distinct attempts; each central file is the exact second outcome. Set +`DISPATCH_TEST_HYPATIA_HOME` to the pinned Hypatia checkout and +`DISPATCH_TEST_MIX_BIN` to its configured Mix executable to use the canonical +generator. Omitting those selects the deterministic test stub, never a +production fallback generator. + +The companion decision packet contains the exact cross-repository commands. +The importer witness proves ID and receipt fidelity, mirror/replay +deduplication and start exclusion. Its deliberate copy into the import feed +does not demonstrate automatic delivery. + +== Claim boundary + +This patch establishes local producer identity and tested wire compatibility. +It does not establish power-loss durability, a multi-file atomic transaction, +exactly-once neural parameter updates, corpus quality, held-out usefulness, +live deployment, full E0-12/E0 acceptance or a higher Kautz type. + +The current monthly-log routes and direct recording callback remain unchanged. +Do not add forwarding without settling the decision packet: the reproduced +counterexample shows how that naive connection multiplies evidence. The new +identity patch does not justify relaxing the existing quarantine. diff --git a/scripts/dispatch-runner.sh b/scripts/dispatch-runner.sh index 3be4e087..ec8e5be6 100755 --- a/scripts/dispatch-runner.sh +++ b/scripts/dispatch-runner.sh @@ -121,6 +121,15 @@ fold_counts() { esac done < "$PARALLEL_TMPDIR/tally" } + +# Background wait calls do not retain each child's status. Mark a failed +# identity/start/outcome contract explicitly so the parent also fails closed. +mark_dispatch_error() { + count FAILED + if [[ "${IN_JOB:-0}" == 1 ]]; then + printf '%s\n' failed >> "$PARALLEL_TMPDIR/errors" + fi +} # --- end run counters --- # --- Parse arguments --- @@ -174,6 +183,8 @@ echo "" OUTCOME_FILE="${HYPATIA_DATA}/outcomes/$(date -u +%Y-%m).jsonl" OUTCOME_FILE_CENTRAL="${VERISIMDB_DATA}/outcomes/$(date -u +%Y-%m).jsonl" mkdir -p "$(dirname "$OUTCOME_FILE")" +# E0 receipt design, section 5.2: starts are separate from every outcome log. +ATTEMPT_FILE="${FLEET_ROOT}/shared-context/learning/fix-attempts.jsonl" # Repos that received at least one successful fix this run. Appended by # record_outcome (file, not a variable: execute_entry may run in @@ -205,9 +216,9 @@ fi # Configuration via env: # HYPATIA_HOME path to the hypatia checkout (defaults to # $REPOS_BASE/hypatia) -# HYPATIA_OUTCOME_REPORT set to "off" to disable mix calls (e.g. a -# CI runner without Elixir/mix on PATH); -# defaults to "on" +# HYPATIA_OUTCOME_REPORT set to "off" to disable outcome reports; +# defaults to "on". Fix attempts still require +# mix and HYPATIA_HOME to mint their event id. # HYPATIA_BATCH_ID when set, exit-2 hints suggest # `mix hypatia.rollback_batch $HYPATIA_BATCH_ID` # @@ -226,7 +237,7 @@ HYPATIA_BATCH_ID="${HYPATIA_BATCH_ID:-}" # unverified are recorded (they carry no credit). # legacy an older Hypatia: no --verdict, and no call for no_op or unverified # (the behaviour before this check, exactly). -# off no calls are made at all (reporting off, no checkout, no mix). +# off no outcome calls (reporting off, no checkout, no mix). # A help command that fails is not an older Hypatia: the run stops, visibly. HYPATIA_VERDICT_MODE="off" hypatia_detect_verdict_mode() { @@ -315,7 +326,46 @@ hypatia_record_outcome() { return "$rc" } -# record_outcome [exit before after] +# begin_attempt -> event_id, only after its start is appended. +# event_id is ADR-008 version 8, profile T. E0-31 names Hypatia's existing Mix +# task as the producer tool; there is no fallback generator. E0-08 section 5.2 +# fixes this six-field start schema and its separate append-only destination. +begin_attempt() { + local recipe_id="$1" repo="$2" generated event_id start_json rc=0 + if [[ ! -d "$HYPATIA_HOME" ]]; then + echo "ERROR: event id unavailable: HYPATIA_HOME is not a directory: $HYPATIA_HOME" >&2 + return 1 + fi + if ! command -v mix &>/dev/null; then + echo "ERROR: event id unavailable: mix is not on PATH" >&2 + return 1 + fi + generated=$(cd "$HYPATIA_HOME" && mix hypatia.event_id) || rc=$? + if [[ "$rc" -ne 0 ]]; then + echo "ERROR: event id generation failed: mix hypatia.event_id exited $rc" >&2 + return 1 + fi + # The task documents compilation messages before its final id line. Never + # accept trailing output, a malformed id, or output from a failed command. + event_id="${generated##*$'\n'}" + if [[ ! "$event_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]]; then + echo "ERROR: event id generation returned no valid ADR-008 v8 profile T id" >&2 + return 1 + fi + if ! start_json=$(jq -cnS --arg event_id "$event_id" --arg recipe_id "$recipe_id" --arg repo "$repo" \ + '{chain_version: "e0-receipt/1", event_id: $event_id, kind: "start", + producer: "dispatch-runner", recipe_id: $recipe_id, repo: $repo}'); then + echo "ERROR: could not encode attempt start for event_id=$event_id" >&2 + return 1 + fi + if ! mkdir -p "$(dirname "$ATTEMPT_FILE")" || ! printf '%s\n' "$start_json" >> "$ATTEMPT_FILE"; then + echo "ERROR: could not append attempt start for event_id=$event_id to $ATTEMPT_FILE" >&2 + return 1 + fi + printf '%s\n' "$event_id" +} + +# record_outcome [exit before after event_id] # # is one of lib/outcome-verdict.sh's verdicts, or refused_* for a # policy refusal. `outcome` is kept for older readers and reports the exit @@ -329,6 +379,9 @@ record_outcome() { local exit_code="${6:-}" local before="${7:-NA}" local after="${8:-NA}" + # Execution attempts pass the id already committed by begin_attempt. + # Policy refusals do not execute a fix and keep their existing row shape. + local event_id="${9:-}" local bot="dispatch-runner" local outcome @@ -341,7 +394,7 @@ record_outcome() { ts=$(date -u +"%Y-%m-%dT%H:%M:%SZ") local json - json=$(jq -cn \ + if ! json=$(jq -cn \ --arg pid "$pattern_id" \ --arg rid "$recipe_id" \ --arg repo "$repo" \ @@ -353,21 +406,31 @@ record_outcome() { --arg after "$after" \ --arg ts "$ts" \ --arg bot "$bot" \ + --arg event_id "$event_id" \ '{pattern_id: $pid, recipe_id: $rid, repo: $repo, file: $file, outcome: $outcome, verdict: $verdict, exit_code: (if $exit_code == "" then null else ($exit_code | tonumber) end), before_hits: (if $before == "NA" then null else ($before | tonumber) end), after_hits: (if $after == "NA" then null else ($after | tonumber) end), - timestamp: $ts, bot: $bot}') + timestamp: $ts, bot: $bot} + + (if $event_id == "" then {} else {event_id: $event_id} end)'); then + echo "ERROR: could not encode outcome for $repo/$recipe_id event_id=$event_id" >&2 + return 1 + fi - echo "$json" >> "$OUTCOME_FILE" + if ! printf '%s\n' "$json" >> "$OUTCOME_FILE"; then + echo "ERROR: could not append outcome for event_id=$event_id to $OUTCOME_FILE" >&2 + return 1 + fi # Avoid duplicate JSONL records when the two configured stores are the same. local primary_path central_path primary_path=$(realpath -m "$OUTCOME_FILE") central_path=$(realpath -m "$OUTCOME_FILE_CENTRAL") if [[ "$primary_path" != "$central_path" && ! "$OUTCOME_FILE" -ef "$OUTCOME_FILE_CENTRAL" ]]; then - mkdir -p "$(dirname "$OUTCOME_FILE_CENTRAL")" - echo "$json" >> "$OUTCOME_FILE_CENTRAL" + if ! mkdir -p "$(dirname "$OUTCOME_FILE_CENTRAL")" || ! printf '%s\n' "$json" >> "$OUTCOME_FILE_CENTRAL"; then + echo "ERROR: could not mirror outcome for event_id=$event_id to $OUTCOME_FILE_CENTRAL; primary row is committed" >&2 + return 1 + fi fi # Hypatia closed-loop contract — best-effort, never fails the dispatch @@ -543,9 +606,15 @@ execute_entry() { tmp_finding=$(mktemp /tmp/dispatch-finding-XXXXXX.json) echo "$entry" > "$tmp_finding" - local before after rc verdict + local before after rc verdict event_id if [[ "$PARALLEL" -gt 1 ]]; then repo_lock "$PARALLEL_TMPDIR" "$repo_path"; fi before=$(recipe_check_count "$FLEET_SCRIPTS/$fix_script" "$repo_path") + if ! event_id=$(begin_attempt "$recipe_id" "$repo"); then + if [[ "$PARALLEL" -gt 1 ]]; then repo_unlock; fi + rm -f "$tmp_finding" + mark_dispatch_error + return 1 + fi echo " Running: $fix_script $repo_path $tmp_finding" rc=0 @@ -556,17 +625,27 @@ execute_entry() { if [[ "$PARALLEL" -gt 1 ]]; then repo_unlock; fi verdict=$(outcome_verdict "$rc" "$before" "$after") echo " $verdict (exit $rc, targets $before -> $after)" + record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" "$before" "$after" "$event_id" || { + rm -f "$tmp_finding" + count EXECUTED + mark_dispatch_error + return 1 + } if [[ "$verdict" == failed || "$verdict" == incomplete ]]; then count FAILED else count SUCCEEDED fi - record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" "$before" "$after" rm -f "$tmp_finding" elif command -v "$RRA_BIN" &>/dev/null; then # Use robot-repo-automaton fix command + local event_id + if ! event_id=$(begin_attempt "$recipe_id" "$repo"); then + mark_dispatch_error + return 1 + fi echo " Running: $RRA_BIN fix --repo $repo_path --commit" # robot-repo-automaton exposes no predicate, so a clean exit # is recorded as unverified, never as a confirmed fix. @@ -576,12 +655,16 @@ execute_entry() { local verdict verdict=$(outcome_verdict "$rc" NA NA) echo " $verdict (exit $rc)" + record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" NA NA "$event_id" || { + count EXECUTED + mark_dispatch_error + return 1 + } if [[ "$verdict" == failed ]]; then count FAILED else count SUCCEEDED fi - record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" else echo " SKIP: No fix mechanism available (no fix_script, no $RRA_BIN)" count SKIPPED @@ -722,6 +805,11 @@ done < "$MANIFEST_PATH" if [[ "$PARALLEL" -gt 1 ]]; then wait fold_counts + if [[ -s "$PARALLEL_TMPDIR/errors" ]]; then + echo "ERROR: a dispatch job could not commit its attempt identity or outcome" >&2 + rm -rf "$PARALLEL_TMPDIR" + exit 1 + fi fi rm -rf "$PARALLEL_TMPDIR" 2>/dev/null || true diff --git a/scripts/tests/dispatch-paths.sh b/scripts/tests/dispatch-paths.sh old mode 100644 new mode 100755 index f5adc9f0..cbd0d098 --- a/scripts/tests/dispatch-paths.sh +++ b/scripts/tests/dispatch-paths.sh @@ -1,94 +1,333 @@ #!/usr/bin/env bash # SPDX-License-Identifier: MPL-2.0 -# Exercise dispatch orchestration with an inert fix executable and isolated data. +# Exercise the actual dispatch orchestration with inert fixes and isolated data. +# Optional DISPATCH_TEST_HYPATIA_HOME and DISPATCH_TEST_MIX_BIN use the canonical +# generator for successful cases. DISPATCH_TEST_EVIDENCE_DIR retains emitted rows +# for a separate consumer wire/replay witness; it does not enable delivery. set -euo pipefail fleet_test_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" fixture="$(mktemp -d)" trap 'rm -rf "$fixture"' EXIT -mkdir -p "$fixture/repos/sample" "$fixture/checkout/scripts" "$fixture/primary/dispatch" +mkdir -p "$fixture/repos/sample" "$fixture/checkout/scripts/lib" "$fixture/primary/dispatch" \ + "$fixture/bin" "$fixture/hypatia" cp "$fleet_test_root/scripts/repo-path-overrides.json" "$fixture/checkout/scripts/" -# dispatch-runner sources its outcome-verdict library from beside itself. -mkdir -p "$fixture/checkout/scripts/lib" cp "$fleet_test_root/scripts/lib/outcome-verdict.sh" "$fixture/checkout/scripts/lib/" +month="$(date -u +%Y-%m)" +starts="$fixture/checkout/shared-context/learning/fix-attempts.jsonl" +primary="$fixture/primary/outcomes/$month.jsonl" +central="$fixture/central/outcomes/$month.jsonl" +manifest="$fixture/primary/dispatch/pending.jsonl" +canonical_mix="${DISPATCH_TEST_MIX_BIN:-$(command -v mix || true)}" +pass=0 +check() { + local label="$1"; shift + if ! "$@" > "$fixture/assertion-result" 2>&1; then + echo "FAIL: $label" >&2 + cat "$fixture/assertion-result" >&2 + [[ ! -f "$fixture/result" ]] || cat "$fixture/result" >&2 + exit 1 + fi + pass=$((pass + 1)) + printf 'PASS: %s\n' "$label" +} -# While dispatch is quarantined (docs/AUTOMATION-QUARANTINE.adoc), the -# production runner must refuse every call. The path/outcome contracts -# below run against a test-only copy with the interlock removed, inside the -# throwaway fixture; that copy is unreachable from any production entry point. +# While dispatch is quarantined, the production runner refuses every call. Only +# this disposable copy has exactly the BLOCKED printf and following exit removed; +# it is unreachable from production entry points and uses only fixture adapters. real_runner="$fleet_test_root/scripts/dispatch-runner.sh" seam_runner="$fixture/checkout/scripts/dispatch-runner.sh" interlock_msg='BLOCKED: repository directive enforcement is not qualified' -if ! grep -qF "$interlock_msg" "$real_runner"; then - echo "FAIL: dispatch-runner.sh no longer carries the quarantine interlock;" >&2 - echo " update this test to run the real runner and drop the seam." >&2 - exit 1 -fi -# Strip exactly the interlock: the BLOCKED printf and the exit 78 after it. +check 'production interlock exists' grep -qF "$interlock_msg" "$real_runner" awk -v msg="$interlock_msg" ' skip_exit && /^exit 78$/ { skip_exit = 0; next } index($0, msg) && /^printf / { skip_exit = 1; next } { print } ' "$real_runner" > "$seam_runner" +check 'test copy removed only the two interlock lines' test \ + "$(( $(wc -l < "$real_runner") - $(wc -l < "$seam_runner") ))" -eq 2 if grep -qF "$interlock_msg" "$seam_runner" || cmp -s "$real_runner" "$seam_runner"; then - echo "FAIL: could not build the test-only seam runner" >&2 + echo 'FAIL: could not build the test-only seam runner' >&2 exit 1 fi -# Run one dispatch against the fixture with the given runner and central store. +cat > "$fixture/bin/mix" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >> "$FIXTURE_ROOT/mix-calls" +case "$*" in + 'help hypatia.record_outcome') echo '--verdict verified|no_op|incomplete|unverified|failed'; exit 0 ;; + hypatia.record_outcome*) exit 0 ;; + hypatia.event_id) ;; + *) echo 'unexpected mix arguments' >&2; exit 98 ;; +esac +fixture_id=018e4000-0000-8000-8000-000000000001 +case "$FIXTURE_GENERATOR_MODE" in + fail) echo "$fixture_id"; exit 3 ;; + empty) exit 0 ;; + bad) echo 'not-an-event-id'; exit 0 ;; + v4) echo "${fixture_id:0:14}4${fixture_id:15}"; exit 0 ;; + variant) echo "${fixture_id:0:19}c${fixture_id:20}"; exit 0 ;; + uppercase) echo "${fixture_id^^}"; exit 0 ;; + trailing) printf '%s\ntrailing noise\n' "$fixture_id"; exit 0 ;; + chatter) echo 'Compiling fixture source' ;; +esac +if [[ -n "${DISPATCH_TEST_HYPATIA_HOME:-}" ]]; then + exec "$DISPATCH_TEST_MIX_BIN" hypatia.event_id +fi +# These are fixed wire fixtures, not a replacement event-id generator. The lock +# only lets two background runner jobs consume distinct fixture rows safely. +{ + flock 9 + head -n 1 "$FIXTURE_ROOT/ids" + tail -n +2 "$FIXTURE_ROOT/ids" > "$FIXTURE_ROOT/ids.next" + mv "$FIXTURE_ROOT/ids.next" "$FIXTURE_ROOT/ids" +} 9> "$FIXTURE_ROOT/ids.lock" +STUB +cat > "$fixture/checkout/scripts/fix-fixture.sh" <<'STUB' +#!/usr/bin/env bash +# outcome-predicate: --check +set -euo pipefail +if [[ "$1" == --check ]]; then + if [[ -e "$2/needs-fix" ]]; then echo 1; else echo 0; fi + exit 0 +fi +# This observation is made by the fixer, before it changes the fixture repo. +jq -e '.kind == "start" and .producer == "dispatch-runner"' \ + "$FIXTURE_ROOT/checkout/shared-context/learning/fix-attempts.jsonl" >/dev/null +printf '%s\n' started >> "$FIXTURE_ROOT/fix-calls" +case "$FIXTURE_FIX_MODE" in + interrupt) kill -TERM "$PPID"; exit 0 ;; + fail) exit 7 ;; +esac +rm -f "$1/needs-fix" +STUB +cat > "$fixture/bin/rra" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +[[ "$1" == fix && "$2" == --repo && "$4" == --commit ]] +exec "$FIXTURE_ROOT/checkout/scripts/fix-fixture.sh" "$3" +STUB +chmod +x "$fixture/bin/mix" "$fixture/bin/rra" "$fixture/checkout/scripts/fix-fixture.sh" + +reset_fixture() { + rm -rf "$fixture/primary/outcomes" "$fixture/central" "$fixture/checkout/shared-context" "$fixture/kin" + : > "$fixture/mix-calls" + : > "$fixture/fix-calls" + printf '%s\n' '018e4000-0000-8000-8000-000000000001' \ + '018e4000-0000-8000-8000-000000000002' > "$fixture/ids" + touch "$fixture/repos/sample/needs-fix" + printf '%s\n' '{"repo":"sample","tier":"eliminate","strategy":"auto_execute","pattern_id":"fixture","recipe_id":"recipe-fixture","fix_script":"fix-fixture.sh","auto_fixable":true}' > "$manifest" + generator_mode=ok fix_mode=ok report_mode=off parallel=1 limit=1 + runner_args=() + hypatia_home="${DISPATCH_TEST_HYPATIA_HOME:-$fixture/hypatia}" + runner_path="$fixture/bin:$PATH" + rra_bin="$fixture/bin/rra" +} invoke_runner() { - local runner="$1" central="$2" - env -u GITHUB_TOKEN -u FLEET_DISPATCH_TOKEN \ - FLEET_ROOT="$fixture/checkout" REPOS_BASE="$fixture/repos" \ - HYPATIA_DATA="$fixture/primary" VERISIMDB_DATA="$central" \ - HYPATIA_OUTCOME_REPORT=off KIN_DIR="$fixture/kin" RRA_BIN=/bin/true \ - bash "$runner" --limit 1 + local runner="$1" store="$2" + env -u GITHUB_TOKEN -u FLEET_DISPATCH_TOKEN -u BASH_ENV -u ENV \ + PATH="$runner_path" FLEET_ROOT="$fixture/checkout" REPOS_BASE="$fixture/repos" \ + HYPATIA_DATA="$fixture/primary" VERISIMDB_DATA="$store" \ + HYPATIA_HOME="$hypatia_home" HYPATIA_OUTCOME_REPORT="$report_mode" \ + KIN_DIR="$fixture/kin" RRA_BIN="$rra_bin" FIXTURE_ROOT="$fixture" \ + FIXTURE_GENERATOR_MODE="$generator_mode" FIXTURE_FIX_MODE="$fix_mode" \ + DISPATCH_TEST_MIX_BIN="$canonical_mix" \ + bash "$runner" --limit "$limit" --parallel "$parallel" "${runner_args[@]}" } - -# Run one dispatch through the test-only seam runner (interlock removed). -run_dispatch() { - invoke_runner "$seam_runner" "$1" +run_dispatch() { invoke_runner "$seam_runner" "${1:-$fixture/central}" > "$fixture/result" 2>&1; } +expect_failure() { + local label="$1" rc=0 + run_dispatch || rc=$? + check "$label: runner refuses" test "$rc" -ne 0 +} +no_fix_or_outcome() { + check "$1: fixer was not called" test ! -s "$fixture/fix-calls" + check "$1: no outcome was written" test ! -s "$primary" +} +retain_rows() { + [[ -n "${DISPATCH_TEST_EVIDENCE_DIR:-}" ]] || return 0 + mkdir -p "$DISPATCH_TEST_EVIDENCE_DIR" + cp "$starts" "$DISPATCH_TEST_EVIDENCE_DIR/$1-starts.jsonl" + cp "$primary" "$DISPATCH_TEST_EVIDENCE_DIR/$1-primary.jsonl" + cp "$central" "$DISPATCH_TEST_EVIDENCE_DIR/$1-central.jsonl" } -manifest="$fixture/primary/dispatch/pending.jsonl" -printf '%s\n' '{"repo":"sample","tier":"eliminate","strategy":"auto_execute","pattern_id":"fixture","recipe_id":"none","auto_fixable":true}' > "$manifest" - -# The production runner refuses with exit 78 and writes no outcome state. -set +e -quarantine_err="$(invoke_runner "$real_runner" "$fixture/primary/." 2>&1 >/dev/null)" -quarantine_rc=$? -set -e -test "$quarantine_rc" -eq 78 -grep -qF "$interlock_msg" <<<"$quarantine_err" -test ! -e "$fixture/primary/outcomes" -# Planted control: the seam copy must NOT be refused, or the assertion above -# could never distinguish a quarantined runner from an unquarantined one. -set +e -invoke_runner "$seam_runner" "$fixture/scratch-control" >/dev/null 2>&1 -control_rc=$? -set -e -test "$control_rc" -ne 78 -rm -rf "$fixture/primary/outcomes" "$fixture/scratch-control" "$fixture/kin" -# Default primary and central stores are the same; exactly one JSONL record. +reset_fixture +quarantine_rc=0 +invoke_runner "$real_runner" "$fixture/primary/." > "$fixture/result" 2>&1 || quarantine_rc=$? +check 'production runner exits 78 before manifest work' test "$quarantine_rc" -eq 78 +check 'quarantine calls no generator' test ! -s "$fixture/mix-calls" +check 'quarantine writes no attempt or outcome state' test ! -e "$fixture/checkout/shared-context" +check 'quarantine writes no primary state' test ! -e "$fixture/primary/outcomes" + +# Two identical manifest entries and initial repo states are two attempts. run_dispatch "$fixture/primary/." -month="$(date -u +%Y-%m)" -test "$(wc -l < "$fixture/primary/outcomes/$month.jsonl")" -eq 1 -jq -e '.outcome == "success"' "$fixture/primary/outcomes/$month.jsonl" >/dev/null -# Separate stores both receive one copy of this new outcome. -run_dispatch "$fixture/central" -test "$(wc -l < "$fixture/primary/outcomes/$month.jsonl")" -eq 2 -test "$(wc -l < "$fixture/central/outcomes/$month.jsonl")" -eq 1 +check 'first outcome is verified' jq -e '.verdict == "verified" and .before_hits == 1 and .after_hits == 0' "$primary" +check 'same store gets exactly one outcome' test "$(wc -l < "$primary")" -eq 1 +check 'start has exactly the ruled six fields' jq -e \ + 'keys == ["chain_version","event_id","kind","producer","recipe_id","repo"] and .chain_version == "e0-receipt/1" and .kind == "start" and .producer == "dispatch-runner" and .recipe_id == "recipe-fixture" and .repo == "sample"' "$starts" +check 'start uses canonical compact sorted JSON' test "$(cat "$starts")" "=" "$(jq -cS . "$starts")" +check 'event id has ADR-008 v8 text and variant' jq -e \ + '.event_id | test("^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")' "$starts" +check 'first start and outcome have one id' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" +touch "$fixture/repos/sample/needs-fix" +run_dispatch +check 'each identical attempt minted exactly once' test "$(grep -c '^hypatia.event_id$' "$fixture/mix-calls")" -eq 2 +check 'identical attempts have distinct event ids' jq -se 'map(.event_id) | length == 2 and (unique | length == 2)' "$primary" +check 'both starts match their outcomes' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" +check 'mirrored outcome is the exact same row' test "$(tail -n 1 "$primary")" "=" "$(cat "$central")" +check 'mirror contains one outcome' test "$(wc -l < "$central")" -eq 1 +retain_rows success + +reset_fixture +fix_mode=fail +run_dispatch "$fixture/primary/." +run_dispatch +check 'failed fix retains its producer id and exit code' jq -e '.verdict == "failed" and .exit_code == 7 and (.event_id | type == "string")' "$primary" +check 'failed attempt keeps one id across all copies' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" +check 'identical failed attempts have distinct event ids' jq -se 'map(.event_id) | length == 2 and (unique | length == 2)' "$primary" +check 'failed mirrored outcome is byte-identical' test "$(tail -n 1 "$primary")" "=" "$(cat "$central")" +retain_rows failure + +reset_fixture +fix_mode=interrupt +expect_failure 'interrupted after start' +check 'interrupted attempt leaves exactly one start' test "$(wc -l < "$starts")" -eq 1 +check 'interrupted fixer observed its durable start' test "$(wc -l < "$fixture/fix-calls")" -eq 1 +check 'interrupted attempt has no outcome' test ! -s "$primary" + +for mode in fail empty bad v4 variant uppercase trailing; do + reset_fixture + generator_mode="$mode" + expect_failure "generator $mode" + no_fix_or_outcome "generator $mode" + check "generator $mode: no start was written" test ! -e "$starts" + check "generator $mode: diagnostic is visible" grep -qi 'event.id' "$fixture/result" +done +reset_fixture +generator_mode=chatter +run_dispatch +check 'compile chatter is excluded from the id' jq -e '.event_id | test("^[0-9a-f-]{36}$")' "$primary" +reset_fixture +hypatia_home="$fixture/missing-hypatia" +expect_failure 'missing Hypatia checkout' +no_fix_or_outcome 'missing Hypatia checkout' +mkdir "$fixture/no-mix" +for command_name in bash dirname wc tr date mkdir mktemp jq realpath sed grep rm; do + ln -s "$(command -v "$command_name")" "$fixture/no-mix/$command_name" +done +reset_fixture +runner_path="$fixture/no-mix" +expect_failure 'missing mix executable' +no_fix_or_outcome 'missing mix executable' + +for failure in directory append; do + reset_fixture + mkdir -p "$fixture/checkout/shared-context" + if [[ "$failure" == directory ]]; then + : > "$fixture/checkout/shared-context/learning" + else + mkdir -p "$starts" + fi + expect_failure "start $failure failure" + no_fix_or_outcome "start $failure failure" +done +for failure in primary central; do + reset_fixture + report_mode=on + if [[ "$failure" == primary ]]; then mkdir -p "$primary"; else mkdir -p "$central"; fi + expect_failure "$failure outcome append failure" + check "$failure append failure leaves its start" test -s "$starts" + check "$failure append failure does not call direct outcome reporting" test \ + "$(grep -c '^hypatia.record_outcome ' "$fixture/mix-calls" || true)" -eq 0 + if [[ "$failure" == primary ]]; then + check 'primary append failure does not write a mirror' test ! -e "$central" + else + check 'mirror append failure preserves the committed primary row' jq -e '.event_id | type == "string"' "$primary" + fi +done + +# Infrastructure failures must reach the parent under --parallel too: wait +# without a job id otherwise hides a failed child behind an overall exit 0. +for failure in generator start primary central; do + reset_fixture + limit=0 parallel=2 + cat "$manifest" > "$fixture/entry" + cat "$fixture/entry" >> "$manifest" + case "$failure" in + generator) generator_mode=fail ;; + start) mkdir -p "$starts" ;; + primary) mkdir -p "$primary" ;; + central) mkdir -p "$central" ;; + esac + expect_failure "parallel $failure failure" + if [[ "$failure" == generator || "$failure" == start ]]; then + no_fix_or_outcome "parallel $failure failure" + fi +done + +# Both executable mechanisms require the same pre-execution identity contract. +reset_fixture +jq -c 'del(.fix_script)' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +check 'RRA attempt keeps start identity' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" +check 'RRA remains unverified without a predicate' jq -e '.verdict == "unverified"' "$primary" +reset_fixture +generator_mode=fail +jq -c 'del(.fix_script)' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +expect_failure 'RRA generator failure' +no_fix_or_outcome 'RRA generator failure' + +reset_fixture +generator_mode=fail +runner_args=(--dry-run) +run_dispatch +no_fix_or_outcome 'fixture dry run' +check 'fixture dry run mints no id' test ! -s "$fixture/mix-calls" +reset_fixture +generator_mode=fail rra_bin="$fixture/no-rra" +jq -c 'del(.fix_script)' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +no_fix_or_outcome 'no executable fix mechanism' +check 'no executable fix mechanism mints no id' test ! -s "$fixture/mix-calls" + +reset_fixture +limit=0 parallel=2 +cat "$manifest" > "$fixture/entry" +cat "$fixture/entry" >> "$manifest" +run_dispatch +check 'parallel attempts each receive an id' jq -se 'map(.event_id) | length == 2 and (unique | length == 2)' "$primary" +check 'parallel starts and outcomes name the same attempts' test \ + "$(jq -r .event_id "$starts" | sort)" "=" "$(jq -r .event_id "$primary" | sort)" +check 'parallel repo lock still credits only one fix' jq -se 'map(.verdict) | sort == ["no_op","verified"]' "$primary" + +# No attempted execution means no new attempt id. Preserve the licence refusal. +reset_fixture +generator_mode=fail +jq -c '.recipe_id = "recipe-license-hygiene"' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +check 'licence refusal still has its original outcome' jq -e '.verdict == "refused_license_policy" and (has("event_id") | not)' "$primary" +check 'licence refusal mints no execution id' test ! -s "$fixture/mix-calls" +check 'licence refusal never calls the fixer' test ! -s "$fixture/fix-calls" +check 'licence refusal creates no start' test ! -e "$starts" + +reset_fixture +generator_mode=fail printf '%s\n' '{"repo":"sample","tier":"control","strategy":"review","pattern_id":"review-fixture"}' > "$manifest" -run_dispatch "$fixture/central" -test -s "$fixture/checkout/shared-context/findings/pending/sample--review-fixture.json" +run_dispatch +check 'review still writes its finding' test -s "$fixture/checkout/shared-context/findings/pending/sample--review-fixture.json" printf '%s\n' '{"repo":"sample","tier":"control","strategy":"report_only","pattern_id":"advisory-fixture"}' > "$manifest" -run_dispatch "$fixture/central" -test -s "$fixture/checkout/shared-context/advisories/$month.jsonl" -test ! -d "$fixture/repos/gitbot-fleet" - -# Legacy aliases remain fallbacks; direct checkouts still take precedence. +run_dispatch +check 'report-only still writes its advisory' test -s "$fixture/checkout/shared-context/advisories/$month.jsonl" +check 'review and report-only mint no ids' test ! -s "$fixture/mix-calls" +check 'paths stay inside configured checkout' test ! -d "$fixture/repos/gitbot-fleet" mkdir -p "$fixture/repos/developer-ecosystem/julia-ecosystem/packages/Axiom.jl" printf '%s\n' '{"repo":"Axiom.jl","tier":"control","strategy":"review","pattern_id":"alias-fixture"}' > "$manifest" -run_dispatch "$fixture/central" -test -s "$fixture/checkout/shared-context/findings/pending/Axiom.jl--alias-fixture.json" -echo 'Dispatch path and outcome contracts passed' +run_dispatch +check 'legacy repository path alias remains a fallback' test -s "$fixture/checkout/shared-context/findings/pending/Axiom.jl--alias-fixture.json" +printf 'Dispatch path and producer identity contracts: %s passed\n' "$pass" diff --git a/tests/hypatia-event-import-test.exs b/tests/hypatia-event-import-test.exs new file mode 100644 index 00000000..187cdaef --- /dev/null +++ b/tests/hypatia-event-import-test.exs @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MPL-2.0 +# Explicit wire-compatibility witness. Run from the pinned Hypatia checkout: +# DISPATCH_TEST_EVIDENCE_DIR=/absolute/emitted-fixture MIX_ENV=test \ +# mix run --no-start /absolute/gitbot-fleet/tests/hypatia-event-import-test.exs +# The fixture files must come from scripts/tests/dispatch-paths.sh. Copying +# their bytes into the import path below is a test transfer, not delivery code. + +unless Mix.env() == :test, do: raise("run this witness with MIX_ENV=test") + +if Process.whereis(Hypatia.Supervisor), + do: raise("run this witness with --no-start; the Hypatia application must be stopped") + +{:ok, _} = Application.ensure_all_started(:telemetry) +ExUnit.start(autorun: false, seed: 0) + +defmodule Fleet.HypatiaEventImportTest do + use ExUnit.Case, async: false + + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + + @moduletag capture_log: true + + setup do + evidence = System.fetch_env!("DISPATCH_TEST_EVIDENCE_DIR") |> Path.expand() + root = Path.join(System.tmp_dir!(), "fleet-wire-#{System.unique_integer([:positive])}") + data = Path.join(root, "data") + fleet = Path.join(root, "fleet") + keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path] + original = Map.new(keys, &{&1, Application.fetch_env(:hypatia, &1)}) + + on_exit(fn -> + for {key, value} <- original do + case value do + {:ok, previous} -> Application.put_env(:hypatia, key, previous) + :error -> Application.delete_env(:hypatia, key) + end + end + + File.rm_rf!(root) + end) + + File.mkdir_p!(Path.join(data, "outcomes")) + File.mkdir_p!(Path.join(fleet, "shared-context/learning")) + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, Path.join(data, "annealing")) + Application.put_env(:hypatia, :fleet_path, fleet) + + primary = File.read!(Path.join(evidence, "failure-primary.jsonl")) + central = File.read!(Path.join(evidence, "failure-central.jsonl")) + starts = File.read!(Path.join(evidence, "failure-starts.jsonl")) + + for bytes <- [primary, central, starts], do: assert(String.ends_with?(bytes, "\n")) + + %{ + data: data, + fleet: fleet, + source: Path.join(fleet, "shared-context/learning/fix-outcomes.jsonl"), + primary: primary, + central: central, + starts: starts + } + end + + test "actual producer rows retain two distinct attempt identities and their mirror", ctx do + assert [first, second] = decode(ctx.primary) + assert [mirrored] = decode(ctx.central) + assert [first_start, second_start] = decode(ctx.starts) + assert first["verdict"] == "failed" + assert second["verdict"] == "failed" + assert first["outcome"] == "failure" + assert second["outcome"] == "failure" + assert first["recipe_id"] not in [nil, "", "none", "null"] + assert first["recipe_id"] == second["recipe_id"] + assert EventId.valid?(first["event_id"]) + assert EventId.valid?(second["event_id"]) + refute first["event_id"] == second["event_id"] + assert first_start["kind"] == "start" + assert second_start["kind"] == "start" + assert first_start["event_id"] == first["event_id"] + assert second_start["event_id"] == second["event_id"] + assert mirrored == second + assert List.last(lines(ctx.primary)) == hd(lines(ctx.central)) + end + + test "explicit transfer imports attempts once, skips starts, and preserves receipt identity", + ctx do + File.write!(Path.join(ctx.fleet, "shared-context/learning/fix-attempts.jsonl"), ctx.starts) + assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) + assert stored(ctx.data) == [] + assert Receipt.all(ctx.data) == [] + + # Even a misplaced start must not consume the later outcome's identity. + File.write!(ctx.source, ctx.starts) + assert {0, _signature} = LearningScheduler.ingest_fleet_outcomes(nil) + assert stored(ctx.data) == [] + + # This deliberate test transfer is the boundary being exercised. The + # runner's current monthly-log paths do not perform this operation. + File.write!(ctx.source, ctx.starts <> ctx.primary <> ctx.central) + assert {2, signature} = LearningScheduler.ingest_fleet_outcomes(nil) + rows = stored(ctx.data) + expected_ids = ctx.primary |> decode() |> Enum.map(& &1["event_id"]) |> Enum.sort() + assert Enum.sort(Enum.map(rows, & &1["event_id"])) == expected_ids + + assert Enum.all?(rows, fn row -> + row["event_id_source"] == "producer" and + row["fleet_import_id"] == row["event_id"] and + row["verification"] == "failed" + end) + + assert OutcomeTracker.qualified_outcome_counts(rows) == %{ + successes: 0, + failures: 2, + false_positives: 0, + ignored: 0 + } + + receipts = Receipt.all(ctx.data) + assert Enum.sort(Enum.map(receipts, & &1["event_id"])) == expected_ids + assert Enum.all?(receipts, &(&1["verdict"] == "credited_failure")) + assert Enum.all?(receipts, &(&1["provenance"]["event_id_source"] == "producer")) + + before_replay = snapshot(ctx.data) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(signature) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert snapshot(ctx.data) == before_replay + end + + test "raw monthly producer rows do not implicitly become qualified fleet imports", ctx do + month = Date.utc_today() |> Date.to_iso8601() |> String.slice(0, 7) + File.write!(Path.join([ctx.data, "outcomes", month <> ".jsonl"]), ctx.primary) + + assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) + + assert OutcomeTracker.qualified_outcome_counts(stored(ctx.data)) == %{ + successes: 0, + failures: 0, + false_positives: 0, + ignored: 2 + } + + assert Receipt.all(ctx.data) == [] + end + + defp lines(bytes), do: String.split(bytes, "\n", trim: true) + defp decode(bytes), do: bytes |> lines() |> Enum.map(&Jason.decode!/1) + + defp stored(data) do + Path.wildcard(Path.join(data, "outcomes/*.jsonl")) + |> Enum.sort() + |> Enum.flat_map(&(File.read!(&1) |> decode())) + end + + defp snapshot(data) do + Path.wildcard(Path.join(data, "**/*")) + |> Enum.filter(&File.regular?/1) + |> Map.new(&{Path.relative_to(&1, data), File.read!(&1)}) + end +end + +result = ExUnit.run() +System.halt(if(result.failures == 0, do: 0, else: 1)) diff --git a/tests/hypatia-record-outcome-smoke.sh b/tests/hypatia-record-outcome-smoke.sh index 7c28c46b..aa945d05 100755 --- a/tests/hypatia-record-outcome-smoke.sh +++ b/tests/hypatia-record-outcome-smoke.sh @@ -30,6 +30,16 @@ fi # capture the early exit. TMP=$(mktemp -d /tmp/c15-smoke-XXXXXX) trap 'rm -rf "$TMP"' EXIT +# The function checks for mix before it checks placeholder recipe ids. Supply +# an inert executable so these no-call cases are independent of the host PATH. +mkdir "$TMP/bin" +cat > "$TMP/bin/mix" <<'STUB' +#!/usr/bin/env bash +echo 'unexpected mix call in a no-call smoke case' >&2 +exit 99 +STUB +chmod +x "$TMP/bin/mix" +export PATH="$TMP/bin:$PATH" # Extract just the function definitions we need (between # --- Hypatia # closed-loop contract --- and the next "# --- " section). Cheap and diff --git a/tests/hypatia-route-counterexample.exs b/tests/hypatia-route-counterexample.exs new file mode 100644 index 00000000..6d453af3 --- /dev/null +++ b/tests/hypatia-route-counterexample.exs @@ -0,0 +1,117 @@ +# SPDX-License-Identifier: MPL-2.0 +# Separate, deliberately failing gate against naive dual-route wiring: one +# emitted attempt can be credited by both the direct Mix callback and a later +# explicit fleet import. This is a counterexample to joining the current routes, +# not a universal acceptance test for a future exclusive-ingress design. +# Run from Hypatia with MIX_ENV=test, --no-start and DISPATCH_TEST_EVIDENCE_DIR +# pointing at the real producer fixture from scripts/tests/dispatch-paths.sh. + +unless Mix.env() == :test, do: raise("run this witness with MIX_ENV=test") + +if Process.whereis(Hypatia.Supervisor), + do: raise("run this witness with --no-start; the Hypatia application must be stopped") + +{:ok, _} = Application.ensure_all_started(:telemetry) + +defmodule Fleet.HypatiaRouteCounterexample do + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + + def run do + evidence = System.fetch_env!("DISPATCH_TEST_EVIDENCE_DIR") |> Path.expand() + [line | _] = File.read!(Path.join(evidence, "failure-primary.jsonl")) |> lines() + row = Jason.decode!(line) + true = row["verdict"] == "failed" and row["outcome"] == "failure" + true = EventId.valid?(row["event_id"]) + root = Path.join(System.tmp_dir!(), "fleet-route-#{System.unique_integer([:positive])}") + data = Path.join(root, "data") + fleet = Path.join(root, "fleet") + keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path] + original = Map.new(keys, &{&1, Application.fetch_env(:hypatia, &1)}) + + try do + File.mkdir_p!(Path.join(data, "outcomes")) + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, Path.join(data, "annealing")) + Application.put_env(:hypatia, :fleet_path, fleet) + file = if row["file"] in [nil, ""], do: ".", else: row["file"] + + # The actual task called by dispatch-runner, with that attempt's actual + # labels. The task deliberately does not accept producer identity. + Mix.Tasks.Hypatia.RecordOutcome.run([ + "--recipe", + row["recipe_id"], + "--repo", + row["repo"], + "--file", + file, + "--outcome", + "failure", + "--verdict", + "failed", + "--format", + "json" + ]) + + [local] = stored(data) + true = local["event_id"] != row["event_id"] + true = local["source_kind"] == "local_caller" + before = OutcomeTracker.qualified_outcome_counts([local]) + true = before.failures == 1 + + # The callback's bot=hypatia echo is ignored; the duplicate below is + # caused by explicitly adding the real producer row, not by the echo. + {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + source = Path.join(fleet, "shared-context/learning/fix-outcomes.jsonl") + File.write!(source, line <> "\n", [:append]) + {1, _} = LearningScheduler.ingest_fleet_outcomes(nil) + rows = stored(data) + after_import = OutcomeTracker.qualified_outcome_counts(rows) + + IO.puts( + Jason.encode!(%{ + check: "one qualified contribution per emitted attempt", + emitted_attempts: 1, + producer_event_id: row["event_id"], + direct_event_id: local["event_id"], + qualified_before_import: before.failures, + qualified_after_import: after_import.failures, + receipts_after_import: length(Receipt.all(data)), + automatic_delivery_tested: false + }) + ) + + if after_import.failures == 1 do + IO.puts("PASS: one attempt has one qualified contribution across the two routes") + 0 + else + IO.puts( + :stderr, + "FAIL: one actual producer attempt has #{after_import.failures} qualified " <> + "contributions after direct recording plus explicit import; route contract is unresolved" + ) + + 1 + end + after + for {key, value} <- original do + case value do + {:ok, previous} -> Application.put_env(:hypatia, key, previous) + :error -> Application.delete_env(:hypatia, key) + end + end + + File.rm_rf!(root) + end + end + + defp lines(bytes), do: String.split(bytes, "\n", trim: true) + + defp stored(data) do + Path.wildcard(Path.join(data, "outcomes/*.jsonl")) + |> Enum.sort() + |> Enum.flat_map(&(File.read!(&1) |> lines())) + |> Enum.map(&Jason.decode!/1) + end +end + +System.halt(Fleet.HypatiaRouteCounterexample.run()) diff --git a/tests/outcome-verdict-test.sh b/tests/outcome-verdict-test.sh index 134ea650..93dadf40 100755 --- a/tests/outcome-verdict-test.sh +++ b/tests/outcome-verdict-test.sh @@ -21,6 +21,8 @@ # 8. Run counters from background jobs reach the parent (--parallel). # 9. The runner's own run_entry and post-loop drain keep those counts # (extracted; the quarantined main loop is not run). +# 10. The actual runner in dispatch-paths.sh's isolated fixture preserves one +# producer id across start/outcome/mirrors, and refuses an unrecorded start. set -euo pipefail @@ -137,7 +139,8 @@ RESCAN_REPOS_FILE="$TMP/rescan" # shellcheck disable=SC1091 source "$TMP/extracted.sh" -record_outcome "PA009" "recipe-shell-quote-vars" "repo-a" "" verified 0 3 0 +producer_id=018e4000-0000-8000-8000-000000000001 +record_outcome "PA009" "recipe-shell-quote-vars" "repo-a" "" verified 0 3 0 "$producer_id" record_outcome "PA009" "recipe-shell-quote-vars" "repo-b" "" no_op 0 0 0 record_outcome "PA009" "recipe-x" "repo-c" "" unverified 0 record_outcome "PA009" "recipe-license-hygiene" "repo-d" "" refused_license_policy @@ -149,6 +152,10 @@ check "unverified row has no counts" '{"verdict":"unverified","before_hits":null check "refusal keeps its own outcome" '{"verdict":"refused_license_policy","outcome":"refused_license_policy","exit_code":null}' \ "$(sed -n 4p "$OUTCOME_FILE" | jq -c '{verdict, outcome, exit_code}')" check "only verified repos trigger a rescan" "repo-a" "$(cat "$RESCAN_REPOS_FILE")" +check "outcome retains the producer's event id" "$producer_id" \ + "$(sed -n 1p "$OUTCOME_FILE" | jq -r '.event_id')" +check "policy refusal remains outside fix attempts" false \ + "$(sed -n 4p "$OUTCOME_FILE" | jq 'has("event_id")')" # --- 5. deprecated recipe ids --------------------------------------------- registry="$ROOT/scripts/fix-script-registry.json" @@ -341,6 +348,15 @@ run_case fail off check "reporting off: no help call and no record call" "detect_rc=0 mode=off 0" \ "$(grep '^detect_rc' "$TMP/case.out") $(calls | wc -l | tr -d ' ')" +# --- 11. producer identity through the actual dispatch paths (E0-12) ------ +# The existing harness copies the runner into a disposable tree and removes +# exactly its quarantine interlock there. It never changes the production +# runner or exposes a runtime switch that could unlock it. +dispatch_rc=0 +bash "$ROOT/scripts/tests/dispatch-paths.sh" > "$TMP/dispatch-paths.log" 2>&1 || dispatch_rc=$? +cat "$TMP/dispatch-paths.log" +check "isolated actual-runner producer identity contracts" 0 "$dispatch_rc" + echo "" echo "Results: $pass passed, $fail failed" [[ "$fail" -eq 0 ]]