From 4b4ba7987b0e2bda700f0d288d682b6e7b825436 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:27:28 +0000 Subject: [PATCH] fix(learning): admit fleet attempts once with unbound rescan evidence --- .claude/CLAUDE.md | 2 +- README.adoc | 2 +- docs/design/fleet-attempt-admission.adoc | 186 +++++ docs/operations/dispatch-runner-contract.adoc | 21 +- .../NS-02-fleet-admission.adoc | 333 +++++++++ lib/hypatia/fleet_admission.ex | 401 ++++++++++ lib/hypatia/receipt.ex | 82 ++- lib/learning_scheduler.ex | 177 +++-- lib/outcome_tracker.ex | 161 +++- test/fleet_admission_test.exs | 694 ++++++++++++++++++ test/neural_source_store_lifecycle_test.exs | 73 +- 11 files changed, 2065 insertions(+), 67 deletions(-) create mode 100644 docs/design/fleet-attempt-admission.adoc create mode 100644 docs/operations/nesy-reinforcement/NS-02-fleet-admission.adoc create mode 100644 lib/hypatia/fleet_admission.ex create mode 100644 test/fleet_admission_test.exs diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 653545dc0..0c66bd4b4 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -13,7 +13,7 @@ Hypatia is the neurosymbolic CI/CD intelligence layer for the hyperpolymath ecos ## Architecture ``` -Hypatia # 173 Elixir source files under lib/ (recursive tree count, 2026-11-21) +Hypatia # 174 Elixir source files under lib/ (recursive tree count, 2026-11-23) ├── Elixir pipeline # core: pattern analysis, dispatch, learning ├── Merge orchestration # 12 modules — leases, ledger, ticker (largest subsystem) ├── Kin subsystem # 6 modules — contingency, arbiter, gate, watchdog diff --git a/README.adoc b/README.adoc index 4af026a11..bafbff470 100644 --- a/README.adoc +++ b/README.adoc @@ -76,7 +76,7 @@ PatternRegistry ──> TriangleRouter ──> FleetDispatcher ──> DispatchM [cols="1,3"] |=== -| `lib/` | 173 Elixir source files — pipeline, rules, VCL, neural, safety, web, merge orchestration +| `lib/` | 174 Elixir source files — pipeline, rules, VCL, neural, safety, web, merge orchestration | `lib/rules/` | 44 source files: rule modules and their helpers; see link:docs/rules/catalogue.adoc[the catalogue] | `lib/neural/` | 8 networks + blackboard, coordinator, persistence, rebalancer | `lib/vcl/` | VCL query layer over verisim-data: parser, file executor, cache, federation diff --git a/docs/design/fleet-attempt-admission.adoc b/docs/design/fleet-attempt-admission.adoc new file mode 100644 index 000000000..c9598df52 --- /dev/null +++ b/docs/design/fleet-attempt-admission.adoc @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) += Fleet attempt admission: one attempt, correlated evidence +:toc: +:date: 2026-11-23 + +Status: owner direction APPROVED on 2026-11-23. Jonathan approved the +recommendation that the existing trusted fleet importer admits each attempt +once and that rescans add correlated evidence rather than independently +recording another qualified attempt. This document defines the bounded first +implementation; its acceptance evidence is recorded in +link:../operations/nesy-reinforcement/NS-02-fleet-admission.adoc[the NS-02 evidence note]. Approval does +not grant production activation, quarantine removal, E0 sign-off or a Kautz +promotion. + +== S-01: Decision and scope + +For versioned producer attempts, the E0-11 fleet reader is the sole production +admission writer. The dispatch runner appends one identified source event to +the configured fleet feed and does not call `mix hypatia.record_outcome` for +that event. This explicitly amends the mandatory callback in +`docs/operations/dispatch-runner-contract.adoc` for these versioned attempts. +The existing direct task remains available for its other callers; its public +identity and verification restrictions remain in force. + +The motivation is an executed counterexample on Hypatia +`d158aed87f76b93e4f291e995bef9f26559c7fb2`: one actual emitted failure became two +qualified failures and two receipts after direct recording plus explicit +fleet import. The decision and reproduction are preserved in fleet PR #709, +`docs/design/e0-12-outcome-route-decision.adoc`. The old diagnostic remains +historical evidence; acceptance of this route exercises the actual chosen +flow, without introducing its forbidden second admission. + +== Versioned transport + +The producer writes `attempt_contract = "fleet-attempt/1"`, a valid canonical +`event_id`, and `repo_relative_path`, the actual resolved target relative to +its configured repository root. Existing verdict and numeric evidence fields +remain. The exact six-field start schema is unchanged and stays in +`shared-context/learning/fix-attempts.jsonl`. + +The source outcome is appended to +`shared-context/learning/fix-outcomes.jsonl` under the fleet root. Primary and +central monthly mirrors live in `dispatch/fleet-outcomes/`, outside the +consumer's `outcomes/` ledger. Every copy has identical serialized bytes and +the same event ID. Two distinct attempts with identical inputs still have +different IDs. + +Producer and consumer must select the same physical fleet root. A successful +append establishes source persistence, not consumer admission. A failed +mirror after source persistence does not make the fix happen again and does +not justify a new event ID. Policy refusals are not executable attempts and +retain their separate existing reporting behavior. + +An explicitly unknown or malformed attempt-contract version is refused; it +does not fall back to legacy admission. Untagged historical E0-11 input keeps +its prior interpretation. Mixed-version rollout therefore requires the new +consumer before the new producer. Quarantine remains the current containment +boundary; a field on a source row cannot authorize deployment. + +== One canonical admission + +The file reader supplies the exact source bytes, locator, digest and captured +destination. The raw producer does not supply trusted `verification`, +`admission_version`, receipt context or a trusted observation. + +The consumer writes `admission_version = "fleet-attempt/1"` on one canonical +outcome whose `event_id` is the producer's ID. It retains the original +producer assertion and source provenance. Any scan it actually performs is +embedded as a `rescan_observation`, with a distinct observation ID, the +attempt ID, the same raw-source digest, the observer, resolved target, +observation time and result. A decision not to scan records its reason; it +does not invent an observation or claim that a scan occurred. + +The embedded observation is not another outcome, receipt or training sample. +It is committed with the canonical outcome. An observation ID identifies the +observation; it does not express receipt revision ancestry. The receipt's +`parent_event_ids` remains empty. + +The public recorder continues stripping caller-selected identity and the new +consumer-owned admission fields. A syntax-valid UUID is not provenance. This +design introduces no public flag that lets a caller stamp a trusted outcome. + +== S-02: What a rescan can establish + +A current-target scan may describe changes made after the named attempt. +Current shell fixes can leave dirty working trees, and the producer's per-run +locks do not exclude a different runner. HEAD equality alone does not bind +those uncommitted bytes. Calling a scanner later is consequently insufficient +to establish either success or false-positive blame for that attempt. + +The first implementation records any such rescan as explicitly *unbound*. +It may retain useful diagnostic evidence about the resolved target, but it +cannot promote or blame the attempt. If no safe target/category can be +resolved or the scanner is unavailable, that gap is explicit. + +[cols="3,3",options="header"] +|=== +|Producer evidence |Initial qualified contribution in this slice +|`failed` / `failure` with a nonzero integer exit code +|One failure, under the existing gate. +|`incomplete` with positive post-fix hits and the existing allowed outcome +|One failure, under the existing gate. +|Eligible `verified` / `success`, but no implemented post-state binding +|Audit only. Neither a later clean scan nor a later adverse scan adds credit or blame. +|`no_op`, `unverified`, inconsistent or insufficient evidence +|Audit only. A scan cannot upgrade the producer's insufficient evidence. +|=== + +`qualified_outcome_counts/1` retains its existing success, failure and separate +qualified-false-positive accounting. This slice adds no new bypass or +qualification category. A future bound initial scan can select one qualified +success or one qualified false positive under that existing gate; those +branches must not become reachable before a binding mechanism is implemented +and tested. + +Target resolution is constrained to an explicitly configured +`HYPATIA_REPOS_DIR`. The producer's relative target is validated and physically +checked before invocation. This conservative preflight rejects all symlinks, +including internal ones; an absent mapping or unsafe path never selects a +guessed checkout. It is not a locked filesystem snapshot or a guarantee +against a concurrent filesystem mutation. The category comes from the trusted +local recipe registry, not an arbitrary producer category claim. + +== Replay, conflicts and failure + +Replay is resolved before any scan. A committed producer ID with matching +raw-source digest/binding represents the existing attempt; it creates no new +outcome, observation or credit. A repeated ID with different source bytes or +binding is a visible conflict. Preserve that evidence outside the learning +ledger and refuse another admission. Do not silently revise the previous +qualification or infer that equal content means two IDs are one attempt. + +The canonical outcome append remains the commit point. A failed append leaves +the source unacknowledged. A failed receipt write after that commit retains +the ruled `receipt_pending`/repair behavior. Capture the selected store for +the operation; a scanner can run long enough for runtime configuration to +change. The new evidence must not be written into a different store halfway +through admission. + +The raw-source digest records the bytes reread at admission. Configuration and +the selected store are revalidated after a scan; the source bytes themselves +are not locked or reread after it. Feed aliases with existing outcomes or +receipt files are rejected, and tagged raw producer rows cannot qualify +themselves as canonical admissions. + +The production writer in this slice is the scheduler. This is not a promise +of cross-process or distributed exactly-once execution, multi-file atomicity, +power-loss durability or exactly-once neural parameter updates. + +== Receipt evidence binding + +For a stored row with consumer-owned `admission_version = "fleet-attempt/1"`, +the receipt indexes the exact canonical admitted outcome bytes. Its source +kind remains `fleet_import`; source log/line identify the canonical monthly +outcome, and `proof_or_test_ref.row_sha256` hashes that row. The raw producer +source and digest remain provenance inside it. Consequently, the receipt +binds the embedded evidence rather than hashing only the original assertion. + +Legacy fleet rows keep their existing raw-feed receipt interpretation. The +existing `e0-receipt/1` field schema and D7 revision meaning remain unchanged. +Only a trusted *bound* rescan may populate the receipt's rescan proof field; +unbound diagnostic scans do not remove that missing-evidence declaration. +Unavailable scan artifacts, tool versions and subject identity remain named +as missing. + +== Acceptance and next dependency + +Acceptance must exercise actual producer delivery into the configured source +feed, with no manual test copy; prove no direct-record callback for identified +attempts; and cover distinct identical attempts, mirrors, warm/cold replay, +changed payload conflicts, forged evidence, path confinement, unbound clean +and adverse scans, outcome/receipt failures and store changes. Receipts must +pass the existing Nickel contract and bind the intended exact bytes. + +This slice does not implement qualification revisions. E0-07 and E0-35 remain +the dependencies for changing an already committed qualification. A later +observation cannot silently promote an audit-only attempt or erase its +history. + +The next positive-verification package must capture an immutable post-fix +snapshot (including the actual supported dirty/untracked state), or enforce +a shared execution/verification window with a trustworthy state binding. +It must demonstrate that a later change cannot be attributed to an earlier +attempt. Unsupported states remain audit-only. Only after that evidence and +the remaining E0 gates may this route support an operational K2 claim. diff --git a/docs/operations/dispatch-runner-contract.adoc b/docs/operations/dispatch-runner-contract.adoc index 24e53b253..ada9a725e 100644 --- a/docs/operations/dispatch-runner-contract.adoc +++ b/docs/operations/dispatch-runner-contract.adoc @@ -16,8 +16,27 @@ documents the contract that side must implement. == The contract +=== Amendment approved 2026-11-23: versioned fleet attempts + +For producer rows declaring `attempt_contract = "fleet-attempt/1"`, the owner +has approved the existing trusted fleet importer as the sole attempt admission +path. The runner MUST publish the identified row to the configured fleet +`shared-context/learning/fix-outcomes.jsonl` and MUST NOT independently invoke +`mix hypatia.record_outcome` for that attempt. Rescan observations belong to +the same admitted attempt; they are not a second learning trial. + +The detailed contract and its conservative first implementation are in +`docs/design/fleet-attempt-admission.adoc`. A delayed scan without post-fix +state binding remains unqualified diagnostic evidence; it cannot establish +success or false-positive blame. The direct task below retains its existing +public restrictions and remains available to its other callers, including +the separate policy-refusal reporting path. No quarantine or activation +permission changes with this amendment. + +=== Existing direct-call interface + After a fix script runs against a target repository, the runner -MUST invoke: +under the legacy direct-call contract MUST invoke: mix hypatia.record_outcome \ --recipe # from the dispatch manifest diff --git a/docs/operations/nesy-reinforcement/NS-02-fleet-admission.adoc b/docs/operations/nesy-reinforcement/NS-02-fleet-admission.adoc new file mode 100644 index 000000000..1dc6f8193 --- /dev/null +++ b/docs/operations/nesy-reinforcement/NS-02-fleet-admission.adoc @@ -0,0 +1,333 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) += NS-02: Single fleet admission and unbound rescan evidence +:toc: +:toclevels: 2 + +Date: 2026-11-23. Consumer base: Hypatia #1224, +`10be2b996e9bd6d037b36b5cfad6101a2cfde9f2`. +Paired producer: gitbot-fleet +`37ea58c5b577485de9dc1e2af46af1d09e7056e6`, following #709. + +Jonathan approved single fleet admission and correlated rescans on +2026-11-23. The bounded contract is +`docs/design/fleet-attempt-admission.adoc`; the versioned route amendment is +in `docs/operations/dispatch-runner-contract.adoc`. This note records the +consumer implementation and its executed focused and paired evidence. +Approval and these results grant no production activation, quarantine +removal, E0 closeout or Kautz promotion. + +== Problem and scope + +The previous delivery route could admit one actual producer attempt twice: +once through direct outcome recording and once through fleet import. The +executed counterexample and route decision are preserved in fleet PR #709 +and its `docs/design/e0-12-outcome-route-decision.adoc`. + +For `fleet-attempt/1`, the configured fleet reader is the sole production +admission writer. The paired producer emits an identified source row without +calling `mix hypatia.record_outcome` for that attempt. The consumer admits +one canonical outcome with that producer ID. A scan, when actually performed, +is embedded evidence on that outcome, not another outcome, receipt or +training sample. Existing direct recording remains available for its other +callers under its existing restrictions. + +The production consumer changes are confined to `lib/hypatia/fleet_admission.ex`, +`lib/learning_scheduler.ex`, `lib/outcome_tracker.ex`, +and `lib/hypatia/receipt.ex`, with new controls in +`test/fleet_admission_test.exs`. A separate validation-fixture repair is +described below. The #1224 +dependency maintenance remains in the base; this slice adds no dependency, +CI policy or source-advisory exception. + +== Source admission and public boundaries + +The actual reader is `LearningScheduler.ingest_fleet_outcomes/1`. Its only +versioned source is the configured fleet root's +`shared-context/learning/fix-outcomes.jsonl`. A complete source row must have +the exact `attempt_contract = "fleet-attempt/1"`, a canonical valid +ADR-008 event ID, `bot = "dispatch-runner"`, and the existing recipe and +repository subject fields. Explicit unknown or malformed versions and +invalid IDs are refused; they do not acquire legacy interpretation. +Untagged historical E0-11 rows retain their existing semantics. + +The internal import entry captures the selected destination store and the +reader's source locator and raw-line digest. The admission helper re-reads +that complete line from the configured source and checks its digest before +constructing consumer metadata. A complete JSON value without its final LF +is not a complete versioned source row. The entry accepts no trusted +admission map, caller-selected receipt context or public trust switch. This +works through actual ingest under `mix run --no-start`; it does not require +a globally registered scheduler process. + +Public outcome paths strip caller-supplied identity and consumer-owned +admission/observation fields. Raw feed fields cannot install trusted +verification or observations. The canonical record retains an allowlisted +`producer_assertion` and nested `producer_source` containing the source +`path`, relative `log`, original `line`, `row_sha256` and source `bot`. +The raw digest is SHA-256 of the exact read line excluding its terminating +LF. The canonical outcome has `admission_version = "fleet-attempt/1"`, +the producer event ID, `source_kind = "fleet_import"`, origin +`gitbot-fleet`, and consumer bot `hypatia`. + +== Qualification and observations + +Producer fixes can leave dirty mutable working trees. A later scan can see +changes unrelated to the named attempt; neither HEAD equality nor the +producer's per-run lock binds that scan to the attempt's post-state. +Consequently every v1 success claim remains audit-only. A clean observation +adds no positive credit, and an adverse observation adds no false-positive +blame. The qualified-count path enforces this independently of caller +verification labels. + +[cols="3,3",options="header"] +|=== +|Producer evidence |Canonical contribution +|`failed` / `failure`, nonzero integer `exit_code` +|One qualified failure under the existing numeric gate. +|`incomplete`, existing allowed `success` or `failure` outcome, positive integer `after_hits` +|One qualified failure under the existing numeric gate. +|Otherwise eligible `verified` / `success`, positive integer `before_hits`, integer `after_hits = 0` +|Audit only; may receive an actual unbound current-target scan. +|`no_op`, `unverified`, inconsistent or insufficient evidence +|Audit only; a scan cannot upgrade this evidence. +|=== + +Only an otherwise eligible success is considered for scanning. An actual +scan creates one embedded `rescan_observation` with a distinct generated +`observation_id`, `attempt_event_id`, `source_row_sha256` matching +`producer_source.row_sha256`, `observer = "hypatia"`, +`binding = "unbound"`, observation time and resolved target. The closed +result vocabulary is `verified`, `still_present`, `ambiguous`, +`cannot_locate` and `scan_failed`. Malformed scanner output is retained as +an actual `scan_failed` observation. + +If the scan is not run, `rescan_not_run` states why and no observation ID is +invented. Failed/incomplete and other ineligible assertions use +`not_eligible_success`. Missing scanner, root, target or registry evidence +also leaves an explicit gap. No second admitted event is created for an +embedded observation. + +Target resolution requires an explicitly configured `HYPATIA_REPOS_DIR` and +a safe `repo_relative_path` naming the actual repository beneath it. Absolute +paths, traversal and unsafe path components are refused. The implementation +conservatively refuses every symlink in the root/target/file path, including +internal symlinks. The target must exist; a specified file must be regular. +The category comes only from the captured local recipe registry, matched by +recipe ID. Missing, unreadable or ambiguous mappings/categories do not cause +a guessed scan. A producer's arbitrary category is not trusted. These +optional scan prerequisites do not change the existing failed/incomplete +numeric criteria. + +== Replay, conflicts and destination separation + +Committed identity is checked before observation. A matching producer ID +with the same raw-source digest, source path and source bot returns the +committed identity and repairs a missing receipt when needed. It performs no +new scan and adds no outcome, observation or qualified contribution. The +original source line remains provenance; a moved line with the same bytes +and binding is replay. Distinct valid IDs remain distinct attempts even if +their other inputs match. + +Changed bytes or source binding for a committed ID produce a visible +conflict. The attempted raw bytes, their digest and locator, the committed +source binding, event ID and observation time are preserved with +`authorising = false` under +`admission-conflicts/YYYY-MM-DD.jsonl`. They do not enter the outcomes +ledger, retract the original event or change its existing count. Removing +or changing the version on a committed identity still reaches this conflict +handling. Failure to preserve conflict evidence is an error. Repeated +conflict evidence is not promised to be deduplicated. + +The reader refuses configured-feed aliases into both `outcomes/*.jsonl` +and `receipts/*.jsonl`, using physical device/inode identity so symlink and +hardlink aliases are covered. A raw same-ID source row already in the +outcome ledger is conflicted or refused, rather than admitted again. Raw rows carrying +top-level `attempt_contract` cannot count as canonical evidence even when +they forge `admission_version`. Duplicate committed identities and malformed +or incomplete destination logs fail closed. + +== Commit, retry and receipt proof + +The canonical outcome append is the commit point. A failure before append, +including an append failure after an actual scan, leaves no committed +outcome, receipt, observation or qualified count, and the source is retryable. +The selected store is captured before scanning. Source/store configuration +is checked again before append; changing the selected destination while the +scanner runs cannot redirect the result into either store. + +A receipt failure after a successful outcome append retains that committed +admission. Its qualified count is returned once from the stored row, not +from the pre-scan classification. Replay repairs the missing receipt without +rescanning or readmission. A deferred source scan or later incomplete tail +does not discard the count of earlier committed rows. Diagnostics describe +the scan as deferred and the committed admissions as retained; a pending +receipt is not an uncommitted event. + +For v1, receipt construction reads the exact persisted canonical outcome +bytes. The receipt uses: + +[source,text] +---- +source.kind = "fleet_import" +source.log = "outcomes/YYYY-MM.jsonl" +source.line = "" +proof_or_test_ref.row_sha256 = SHA-256(canonical outcome line without LF) +parent_event_ids = [] +---- + +Thus the receipt digest covers the embedded consumer evidence as well as +the retained producer provenance. The producer's raw-feed digest remains +nested in the stored outcome. Caller-supplied receipt context cannot +replace a persisted v1 row. Selection requires its exact root event ID and +canonical shape and rejects raw tagged rows, ambiguous same-ID evidence +and feed aliases. Removing the caller's admission marker cannot force a +legacy fallback for a persisted versioned identity; an ID mentioned only +inside another row is not a matching receipt source. + +Unbound v1 observations remain missing in receipt `observations.rescan`; +only genuinely bound evidence could populate that slot. No bound path is +implemented here. Legacy receipt context, empty revision ancestry and the +existing `e0-receipt/1` Nickel schema are unchanged. + +== Executed evidence + +The focused consumer runs used the task-scoped Elixir 1.19.4 / +Erlang/OTP 27.3.4.19 runtime. The same focused command was run before the +source changes and after the final controls were added: + +[source,shell] +---- +# Use the matching consumer checkout with the pinned BEAM runtime and dependencies. +cd /absolute/hypatia +MIX_ENV=test mix test test/fleet_admission_test.exs +---- + +[cols="2,3,2",options="header"] +|=== +|Stage |Evidence |Result +|Initial regression against unchanged consumer source +|Actual-ingest version, evidence, replay and receipt controls +|13 tests, 11 failures; exit 2 +|Final consumer focused set +|All final admission, trust-boundary and failure controls +|28 tests, 0 failures; exit 0 +|Actual paired producer/consumer delivery +|Direct configured-feed delivery, four attempts, receipt contracts and replay +|1 test, 0 failures +|=== + +The final 28-test set exercises actual ingest, including clean and adverse +unbound scans; exact failure criteria; distinct attempts and replay; +unknown/malformed versions; forged raw/public metadata; changed bytes, +bindings and removed versions; source/ledger symlink and hardlink aliases; +raw forged-marker ledger rows; nested and ambiguous IDs; persisted-byte +receipt digest and repair; missing scanner/category/root/target; malformed +scanner output; outcome failure before and after scanning; receipt failure +after commit; store switching during an actual scan; and incomplete-row/ +tail handling with count retention. An independent read-only source review +closed the alias, raw-row, receipt-selection and committed-acknowledgement +findings. Formatting and `git diff --check` passed; the final focused log +contained no compilation warnings. + +The coordinator executed the paired witness from the consumer checkout: + +[source,shell] +---- +cd /absolute/hypatia +NICKEL=/absolute/nickel \ + MIX_ENV=test mix run --no-start \ + /absolute/gitbot-fleet/tests/hypatia-single-admission-test.exs +---- + +Its disposable runner writes directly to the consumer's configured feed; +the original delivery requires no file copying into that feed. Four unique +IDs agree across source outcomes, canonical outcomes, receipts and start +records. Two failed attempts yield two qualified failures. Two success +claims yield clean/adverse unbound observations and two audit-only outcomes; +the totals remain zero successes, two failures, zero false positives and +two ignored outcomes. There are four receipts: two `credited_failure` and +two `audit_only`. All four validate against the unchanged schema using +Nickel 1.11.0. Injected duplicate transport plus warm and cold signature +replay leaves stored bytes and the two-scan count unchanged. The witness +uses the established disposable interlock-removal test seam; production +quarantine is unchanged. + +The fixer and scanner in that witness are controlled fixture executables. +The scanner runs through the consumer's real subprocess boundary and checks +its target argument. This validates invocation, interpretation and binding +rules; it does not measure the production scanner's effectiveness on repairs. + +Execution logs are retained in the task's +`notes/continuation/admission-red.log`, `admission-focused.log` and +`single-admission-green-delivery.log`. This note records only the executed +focused and paired results above. The broad-regression checkpoint is below; +hosted CI and deployment remain separate evidence. + +== Validation-fixture repair + +The first full run reported `3752 tests, 1 failure (246 excluded)`. The +failure was the existing Kin default-predictor timeout test's assumption +that the long-lived application neural cohort remained ready. The log shows +an application scheduler poll during an earlier E0-04 temporary-store test, +followed by a latched VAE source mismatch. Restoring the global path did not +clear that correctly retained refusal. These fixtures predate this change; +NS-03 does not itself repair this timeout fixture. + +A deterministic control reproduced the same failed post-resume ready barrier +using a test-owned prior cohort and an actual VAE source mismatch: one test, +one failure. The correction is confined to +`test/neural_source_store_lifecycle_test.exs`. It preserves and suspends the +application Coordinator PID, temporarily lends its registered name to owned +real cohorts, proves the prior cohort remains blocked, then supplies a fresh +complete cohort for the timeout check. Cleanup restores the original root, +registration and PID. The existing hold/deadline assertions and strict ready +barrier remain. The focused corrected control passed one test, zero failures. +No production source guard was reset or weakened. + +The corrected consumer head then passed `mix compile --warnings-as-errors`, +repository-wide `mix format --check-formatted` and `mix test --seed 0`: +`3752 tests, 0 failures (246 excluded)`, with Nickel available and no skipped +tests. README counts/local links, the no-active-Logtalk check and whitespace +checks passed. The 246 exclusions remain the repository's declared +`verisim_data`, `kyq_differential`, `yaml_test_suite`, `baseline_helper` and +`act_integration` groups. The earlier failed full run remains recorded above; +the green result follows an identified test-fixture correction. + +The coordinator also applied this admission slice and its fixture repair in a +separate checkout of #1224, together with the exact NS-01 commit +`7d4e8c35ea31c17a07635cdb447e1cc2c95abe91` and NS-03 commit +`ed7587eea1d0599d8199d454d976fc6ff79e3317`. Both patches applied cleanly. +Compilation with warnings as errors and repository-wide formatting passed. +`mix test --seed 0` then reported +`3770 tests, 0 failures (246 excluded)`, with no skipped tests and Nickel +available. The paired delivery witness was repeated on that combined code +and passed one test, zero failures, including its four receipt-contract +checks. These results establish local compatibility of the three slices; +they do not merge the separate review branches or certify excluded suites, +hosted CI, a qualified corpus or production deployment. + +== Programme dependencies and remaining limits + +NS-02 is based on #1224 and does not duplicate NS-01 or NS-03. The combined +programme also requires NS-01's scheduler recovery of committed fleet +receipts/derived state and NS-03's truthful neural contribution and advisory +readiness boundary. Their separate local combined regression is recorded +above; the published branches still require integration review. V1 replay +repair in this slice is not +a replacement for NS-01's scheduler recovery work. + +The import lock serializes this reader within one BEAM VM only. It does not +provide cross-VM writer atomicity, a multi-file transaction, power-loss +durability or exactly-once neural parameter updates. The stored raw digest +describes the captured/read source snapshot. Post-scan validation checks +source/store configuration; it does not re-hash source bytes or lock mutable +target bytes through append. Initial physical alias checks are not a +filesystem snapshot guarantee. Canonical shape validation assumes a trusted +destination ledger and is not cryptographic protection against an arbitrary +ledger writer. + +Snapshot-bound positive attribution, later evidence revision and withdrawal +remain subsequent work. The present implementation establishes bounded +single admission and correlated unbound audit evidence, with the qualified +failed/incomplete contributions and failure boundaries described above. diff --git a/lib/hypatia/fleet_admission.ex b/lib/hypatia/fleet_admission.ex new file mode 100644 index 000000000..578426594 --- /dev/null +++ b/lib/hypatia/fleet_admission.ex @@ -0,0 +1,401 @@ +# SPDX-License-Identifier: MPL-2.0 +defmodule Hypatia.FleetAdmission do + @moduledoc """ + Bounded fleet-attempt/1 admission from the configured fleet file. + + The outcome append commits an attempt. A later scan of a mutable checkout is + correlated, unbound audit evidence; it grants neither success nor blame. + The local import lock serializes this reader in one VM, not across VMs. + """ + + require Logger + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Paths, Receipt} + + @version "fleet-attempt/1" + @log "shared-context/learning/fix-outcomes.jsonl" + @assertion_fields ~w(attempt_contract event_id bot recipe_id pattern pattern_id match_kind repo repo_relative_path file line outcome verdict exit_code before_hits after_hits timestamp) + + @doc false + def import(line_number, expected_source, expected_digest, data_root, persist) + when is_integer(line_number) and line_number > 0 and is_function(persist, 6) do + # Explicitly local nodes: no distributed exactly-once promise. The callback + # is OutcomeTracker's private append path, not a caller-supplied trust flag. + :global.trans( + {{__MODULE__, :import}, self()}, + fn -> + with :ok <- source_unchanged(expected_source, data_root), + :ok <- distinct_source_ledger(expected_source, data_root), + {:ok, bytes} <- source_line(expected_source, line_number), + true <- sha(bytes) == expected_digest, + {:ok, raw} <- Jason.decode(bytes), + :ok <- valid_identity(raw) do + source = %{ + "path" => expected_source, + "log" => @log, + "line" => line_number, + "row_sha256" => expected_digest, + "bot" => Map.get(raw, "bot", "unknown") + } + + case committed(data_root, raw["event_id"]) do + {:ok, row} -> + if row["admission_version"] != @version and + not Map.has_key?(raw, "attempt_contract"), + do: {:replayed, row}, + else: replay(data_root, row, source, bytes) + + :missing -> + case validate(raw) do + :ok -> admit(data_root, raw, source, persist) + {:reject, reason} -> {:rejected, reason} + end + + {:error, _} = error -> + error + end + else + false -> {:error, :source_row_changed} + {:reject, reason} -> {:rejected, reason} + {:error, _} = error -> error + end + end, + [node()] + ) + end + + defp valid_identity(raw) when is_map(raw) do + if EventId.valid?(raw["event_id"]), do: :ok, else: {:reject, :invalid_event_id} + end + + defp valid_identity(_), do: {:reject, :invalid_attempt_record} + + defp source_unchanged(source, data_root) do + configured = Path.join(Path.expand(Paths.fleet()), @log) + + if source == configured and data_root == Path.expand(Paths.verisimdb_data()), + do: :ok, + else: {:error, :admission_store_or_source_changed} + end + + defp source_line(source, line_number) do + with {:ok, content} <- File.read(source) do + lines = String.split(content, "\n", trim: false) + + if line_number < length(lines), + do: {:ok, Enum.at(lines, line_number - 1)}, + else: {:error, :incomplete_source_row} + end + end + + defp distinct_source_ledger(source, data_root) do + with {:ok, source_stat} <- File.stat(source) do + alias? = + for( + directory <- ["outcomes", "receipts"], + path <- Path.wildcard(Path.join([data_root, directory, "*.jsonl"])), + do: path + ) + |> Enum.any?(fn path -> same_file_stat?(source_stat, path) end) + + if alias?, do: {:error, :source_outcome_alias}, else: :ok + end + end + + @doc false + def source_alias?(path) do + case File.stat(Path.join(Path.expand(Paths.fleet()), @log)) do + {:ok, source_stat} -> same_file_stat?(source_stat, path) + _ -> false + end + end + + defp same_file_stat?(source_stat, path) do + case File.stat(path) do + {:ok, stat} -> + {stat.major_device, stat.minor_device, stat.inode} == + {source_stat.major_device, source_stat.minor_device, source_stat.inode} + + _ -> + false + end + end + + defp validate(%{"attempt_contract" => @version, "bot" => "dispatch-runner"} = raw) do + recipe = raw["recipe_id"] || raw["pattern"] + + cond do + not EventId.valid?(raw["event_id"]) -> {:reject, :invalid_event_id} + not named?(recipe) or not named?(raw["repo"]) -> {:reject, :invalid_attempt_subject} + true -> :ok + end + end + + defp validate(%{"attempt_contract" => @version}), do: {:reject, :invalid_source_bot} + defp validate(_), do: {:reject, :unsupported_attempt_contract} + defp named?(text), do: is_binary(text) and String.trim(text) != "" + + defp committed(data_root, id) do + directory = Path.join(data_root, "outcomes") + + case File.ls(directory) do + {:ok, files} -> + files + |> Enum.filter(&String.ends_with?(&1, ".jsonl")) + |> Enum.sort() + |> Enum.reduce_while({:ok, []}, fn name, {:ok, matches} -> + with {:ok, bytes} <- File.read(Path.join(directory, name)), + true <- bytes == "" or String.ends_with?(bytes, "\n"), + {:ok, found} <- committed_rows(bytes, id) do + {:cont, {:ok, matches ++ found}} + else + reason -> {:halt, {:error, {:admission_log_unreadable, name, reason}}} + end + end) + |> case do + {:ok, []} -> :missing + {:ok, [row]} -> {:ok, row} + {:ok, _} -> {:error, {:duplicate_committed_identity, id}} + error -> error + end + + {:error, :enoent} -> + :missing + + {:error, reason} -> + {:error, {:admission_log_unreadable, reason}} + end + end + + defp committed_rows(bytes, id) do + bytes + |> String.split("\n", trim: true) + |> Enum.reduce_while({:ok, []}, fn line, {:ok, found} -> + case Jason.decode(line) do + {:ok, row} when is_map(row) -> + if row["event_id"] == id or row["fleet_import_id"] == id, + do: {:cont, {:ok, [row | found]}}, + else: {:cont, {:ok, found}} + + _ -> + {:halt, {:error, :invalid_outcome_row}} + end + end) + end + + defp replay(data_root, row, source, bytes) do + original = Map.get(row, "producer_source", %{}) + + if row["admission_version"] == @version and + Map.take(original, ~w(path row_sha256 bot)) == Map.take(source, ~w(path row_sha256 bot)) do + case ensure_receipt(data_root, row) do + :ok -> {:replayed, row} + {:error, reason} -> {:error, {:receipt_pending, row["event_id"], reason}} + end + else + Logger.warning( + "Fleet admission conflict for event_id=#{row["event_id"]}; no second admission" + ) + + with :ok <- preserve_conflict(data_root, row, source, bytes) do + {:conflict, row} + end + end + end + + defp preserve_conflict(data_root, row, source, bytes) do + conflict = %{ + "attempt_event_id" => row["event_id"], + "authorising" => false, + "committed_source" => Map.get(row, "producer_source"), + "source" => source, + "source_row_sha256" => source["row_sha256"], + "raw_source_bytes" => bytes, + "observed_at" => DateTime.to_iso8601(DateTime.utc_now()) + } + + path = + Path.join([data_root, "admission-conflicts", Date.to_iso8601(Date.utc_today()) <> ".jsonl"]) + + with :ok <- source_unchanged(source["path"], data_root), + :ok <- File.mkdir_p(Path.dirname(path)), + :ok <- File.write(path, Jason.encode!(conflict) <> "\n", [:append]) do + :ok + else + {:error, reason} -> {:error, {:conflict_evidence_write, reason}} + end + end + + defp admit(data_root, raw, source, persist) do + {_kind, recipe, repo, file, outcome, verification} = + LearningScheduler.classify_fleet_record(raw) + + metadata = + %{ + "admission_version" => @version, + "event_id" => raw["event_id"], + "source_bot" => "dispatch-runner", + "producer_assertion" => Map.take(raw, @assertion_fields), + "producer_source" => source + } + |> Map.merge( + Map.take(raw, ~w(verdict exit_code before_hits after_hits pattern_id match_kind)) + ) + |> Map.merge(observation(data_root, raw, recipe, file, source)) + + with :ok <- source_unchanged(source["path"], data_root), + {:ok, row} <- persist.(recipe, repo, file, outcome, verification, metadata) do + # Count only the row actually committed, not the pre-scan routing label. + case ensure_receipt(data_root, row) do + :ok -> {:stored, row} + {:error, reason} -> {:stored_pending, row, reason} + end + end + end + + defp ensure_receipt(data_root, row) do + if Receipt.exists?(data_root, row["event_id"]), do: :ok, else: Receipt.write(data_root, row) + rescue + error -> {:error, {:receipt_exception, Exception.message(error)}} + end + + defp observation(data_root, raw, recipe, file, source) do + # Rescans are useful only for otherwise eligible success assertions. They + # cannot upgrade no_op/unverified/invalid claims, or blame a later checkout. + eligible = + match?( + {:ok, _, _, _, :success, "verified"}, + LearningScheduler.classify_fleet_record(Map.delete(raw, "attempt_contract")) + ) + + if eligible do + with {:ok, target} <- target(raw["repo_relative_path"], file), + {:ok, category} <- category(data_root, recipe), + {:ran, result} <- + OutcomeTracker.observe_fleet_target(target, category, file, raw["line"]) do + %{ + "rescan_observation" => %{ + "observation_id" => EventId.generate(), + "attempt_event_id" => raw["event_id"], + "source_row_sha256" => source["row_sha256"], + "observer" => "hypatia", + "binding" => "unbound", + "observed_at" => DateTime.to_iso8601(DateTime.utc_now()), + "result" => Atom.to_string(result), + "target" => %{ + "repo_relative_path" => raw["repo_relative_path"], + "repo_path" => target, + "file" => file, + "line" => raw["line"], + "category" => category + } + } + } + else + {:error, reason} -> %{"rescan_not_run" => Atom.to_string(reason)} + {:not_run, reason} -> %{"rescan_not_run" => Atom.to_string(reason)} + end + else + %{"rescan_not_run" => "not_eligible_success"} + end + end + + defp target(relative, file) do + case System.get_env("HYPATIA_REPOS_DIR") do + root when is_binary(root) and root != "" -> + with true <- safe_relative?(relative), + true <- file == "." or safe_relative?(file), + root = Path.expand(root), + :ok <- directory_without_symlinks(root), + target = Path.join(root, relative), + :ok <- directory_without_symlinks(target), + :ok <- safe_file(target, file) do + {:ok, target} + else + false -> {:error, :unsafe_relative_target} + {:error, reason} -> {:error, reason} + end + + _ -> + {:error, :repos_root_not_configured} + end + end + + defp safe_relative?(path) when is_binary(path) do + path != "" and Path.type(path) == :relative and + not String.contains?(path, ["\\", ":", <<0>>]) and + Enum.all?(String.split(path, "/", trim: false), &(&1 not in ["", ".", ".."])) + end + + defp safe_relative?(_), do: false + + # Rejecting every symlink (including internal links) is deliberately stricter + # than lexical confinement. This preflight is not a post-state snapshot. + defp directory_without_symlinks(path) do + path + |> Path.split() + |> Enum.reduce_while({:ok, ""}, fn component, {:ok, parent} -> + current = if parent == "", do: component, else: Path.join(parent, component) + + case File.lstat(current) do + {:ok, %{type: :directory}} -> {:cont, {:ok, current}} + {:ok, %{type: :symlink}} -> {:halt, {:error, :symlink_target}} + _ -> {:halt, {:error, :target_unavailable}} + end + end) + |> case do + {:ok, _} -> :ok + error -> error + end + end + + defp safe_file(_target, "."), do: :ok + + defp safe_file(target, file) do + path = Path.join(target, file) + + with :ok <- directory_without_symlinks(Path.dirname(path)) do + case File.lstat(path) do + {:ok, %{type: :regular}} -> :ok + {:ok, %{type: :symlink}} -> {:error, :symlink_target} + _ -> {:error, :target_file_unavailable} + end + end + end + + defp category(data_root, recipe) do + directory = Path.join(data_root, "recipes") + + with {:ok, files} <- File.ls(directory) do + files + |> Enum.filter(&(String.starts_with?(&1, "recipe-") and String.ends_with?(&1, ".json"))) + |> Enum.reduce_while({:ok, []}, fn file, {:ok, found} -> + with {:ok, bytes} <- File.read(Path.join(directory, file)), + {:ok, item} when is_map(item) <- Jason.decode(bytes) do + {:cont, {:ok, if(item["id"] == recipe, do: [item | found], else: found)}} + else + _ -> {:halt, {:error, :recipe_registry_unreadable}} + end + end) + |> case do + {:ok, []} -> + {:error, :recipe_not_found} + + {:ok, [%{"target_categories" => [category]}]} when is_binary(category) -> + if String.trim(category) != "", do: {:ok, category}, else: {:error, :category_missing} + + {:ok, [_]} -> + {:error, :category_missing_or_ambiguous} + + {:ok, _} -> + {:error, :recipe_mapping_ambiguous} + + error -> + error + end + else + _ -> {:error, :recipe_registry_unavailable} + end + end + + defp sha(bytes), do: :crypto.hash(:sha256, bytes) |> Base.encode16(case: :lower) +end diff --git a/lib/hypatia/receipt.ex b/lib/hypatia/receipt.ex index ae78a6867..b4bde7998 100644 --- a/lib/hypatia/receipt.ex +++ b/lib/hypatia/receipt.ex @@ -137,6 +137,10 @@ defmodule Hypatia.Receipt do # The verification as the gate reads it. A rollback that the gate does not credit # (no batch fields) is "unqualified", so the verdict can be derived from the pair. + defp qualification_of(%{"admission_version" => "fleet-attempt/1"} = row, verdict) do + if verdict == "credited_failure", do: row["verification"], else: "unqualified" + end + defp qualification_of(row, verdict) do case Map.get(row, "verification") do v when v in @qualifications -> v @@ -168,8 +172,9 @@ defmodule Hypatia.Receipt do _ -> hits end - case {kind, Map.get(row, "verification")} do - {:local_rescan, v} when v in @rescans -> Map.put(base, "rescan", v) + case {Map.get(row, "admission_version"), kind, Map.get(row, "verification")} do + {"fleet-attempt/1", _, _} -> base + {_, :local_rescan, v} when v in @rescans -> Map.put(base, "rescan", v) _ -> base end end @@ -336,8 +341,8 @@ defmodule Hypatia.Receipt do def write(data_root, row, opts \\ []) when is_binary(data_root) and is_map(row) do with {:ok, event_id} <- fetch_event_id(row), :ok <- not_yet_written(data_root, event_id), - {:ok, ctx} <- context(data_root, row, opts), - receipt = build(row, ctx), + {:ok, stored_row, ctx} <- receipt_input(data_root, row, opts), + receipt = build(stored_row, ctx), :ok <- check(receipt), {:ok, line} <- encode(receipt) do append(data_root, line) @@ -403,6 +408,75 @@ defmodule Hypatia.Receipt do # ── Context: where the evidence sits ─────────────────────────────────── + # An admission receipt binds the canonical outcome, including its embedded + # unbound observation. Caller context and a caller's altered copy of that row + # cannot replace the persisted evidence. Legacy context remains unchanged. + defp receipt_input(data_root, row, opts) do + event_id = Map.fetch!(row, "event_id") + located = locate_admission(data_root, event_id) + + case located do + {:ok, log, line, bytes} -> + case Jason.decode(bytes) do + {:ok, %{"admission_version" => "fleet-attempt/1", "event_id" => ^event_id} = stored} -> + {:ok, stored, + %{ + kind: :fleet_import, + log: log, + line: Integer.to_string(line), + row_sha256: sha(bytes) + }} + + _ -> + legacy_receipt_input(data_root, row, opts) + end + + :error -> + legacy_receipt_input(data_root, row, opts) + + {:error, _} = error -> + error + end + end + + # Only root event identity counts. A public row's unrelated nested JSON may + # mention an ID; that mention is not the committed admission's location. + defp locate_admission(data_root, event_id) do + matches = + for path <- Path.wildcard(Path.join([data_root, "outcomes", "*.jsonl"])), + {bytes, line} <- path |> File.stream!() |> Stream.with_index(1), + bytes = String.trim_trailing(bytes, "\n"), + {:ok, %{"event_id" => ^event_id} = stored} <- [Jason.decode(bytes)] do + {path, line, bytes, stored} + end + + versioned? = + Enum.any?(matches, fn {_, _, _, stored} -> + Map.has_key?(stored, "admission_version") or Map.has_key?(stored, "attempt_contract") + end) + + case {versioned?, matches} do + {false, _} -> + :error + + {true, [{path, line, bytes, stored}]} -> + if OutcomeTracker.canonical_fleet_admission?(stored) and + not Hypatia.FleetAdmission.source_alias?(path), + do: {:ok, "outcomes/" <> Path.basename(path), line, bytes}, + else: {:error, :invalid_admission_row} + + {true, _} -> + {:error, :ambiguous_admission_identity} + end + end + + defp legacy_receipt_input(_data_root, %{"admission_version" => "fleet-attempt/1"}, _opts), + do: {:error, :row_not_in_log} + + defp legacy_receipt_input(data_root, row, opts) do + with {:ok, ctx} <- context(data_root, row, opts), do: {:ok, row, ctx} + end + defp context(data_root, row, opts) do case Keyword.fetch(opts, :ctx) do {:ok, ctx} -> {:ok, ctx} diff --git a/lib/learning_scheduler.ex b/lib/learning_scheduler.ex index 00f7e28b6..1731de831 100644 --- a/lib/learning_scheduler.ex +++ b/lib/learning_scheduler.ex @@ -753,6 +753,24 @@ defmodule Hypatia.LearningScheduler do # --- Fleet outcomes: verified evidence only, restart-safe replay --- @doc false + def classify_fleet_record( + %{"attempt_contract" => "fleet-attempt/1", "bot" => "dispatch-runner"} = record + ) do + if Hypatia.EventId.valid?(record["event_id"]) do + case classify_fleet_record(Map.delete(record, "attempt_contract")) do + {:ok, recipe, repo, file, :success, "verified"} -> + {:audit, recipe, repo, file, :success, "unqualified"} + + result -> + result + end + else + :skip + end + end + + def classify_fleet_record(%{"attempt_contract" => _}), do: :skip + def classify_fleet_record(record) when is_map(record) do recipe_id = Map.get(record, "recipe_id") || Map.get(record, "pattern") repo = Map.get(record, "repo") @@ -913,15 +931,32 @@ defmodule Hypatia.LearningScheduler do }) ) - if signature == previous_signature do + versioned? = + content + |> String.split("\n", trim: true) + |> Enum.any?(fn line -> + case Jason.decode(line) do + {:ok, row} when is_map(row) -> Map.has_key?(row, "attempt_contract") + _ -> false + end + end) + + if signature == previous_signature and not versioned? do {0, signature} else case Hypatia.OutcomeTracker.imported_fleet_ids() do {:ok, known_ids} -> - case import_fleet_lines(content, known_ids) do + case import_fleet_lines(content, known_ids, fleet_file, versioned?) do {:ok, imported} -> {imported, signature} + {:error, reason, committed_count} -> + Logger.warning( + "LearningScheduler: fleet source scan deferred; committed admissions retained: #{inspect(reason)}" + ) + + {committed_count, previous_signature} + {:error, reason} -> Logger.warning( "LearningScheduler: fleet import not acknowledged: #{inspect(reason)}" @@ -945,7 +980,7 @@ defmodule Hypatia.LearningScheduler do end end - defp import_fleet_lines(content, known_ids) do + defp import_fleet_lines(content, known_ids, fleet_file, versioned?) do lines = String.split(content, "\n", trim: false) final_line = length(lines) @@ -964,61 +999,82 @@ defmodule Hypatia.LearningScheduler do {:ok, %{"kind" => "start"}} -> {:cont, {:ok, seen, count}} + {:ok, %{"attempt_contract" => _}} -> + import_versioned_fleet_line(line, line_number, fleet_file, seen, count) + {:ok, record} -> - case classify_fleet_record(record) do - {kind, recipe_id, repo, file, outcome, verification} when kind in [:ok, :audit] -> - case fleet_identity(record, line, line_number) do - {:invalid, reason} -> - # Present and not valid: not imported, and the rows after it - # still are. It stays in the append-only source as evidence. - Logger.warning( - "LearningScheduler: fleet row #{line_number}: event_id is not a valid " <> - "ADR-008 version 8 id (#{reason}); not imported" - ) - - {:cont, {:ok, seen, count}} - - {:ok, id, producer_id} -> - if MapSet.member?(seen, id) do + # A v1 identity cannot escape conflict detection by removing its + # version field or damaging another field on replay. Historical + # identities retain their old duplicate interpretation. + if is_map(record) and Hypatia.EventId.valid?(record["event_id"]) and + MapSet.member?(seen, record["event_id"]) do + import_versioned_fleet_line(line, line_number, fleet_file, seen, count) + else + case classify_fleet_record(record) do + {kind, recipe_id, repo, file, outcome, verification} when kind in [:ok, :audit] -> + case fleet_identity(record, line, line_number) do + {:invalid, reason} -> + # Present and not valid: not imported, and the rows after it + # still are. It stays in the append-only source as evidence. + Logger.warning( + "LearningScheduler: fleet row #{line_number}: event_id is not a valid " <> + "ADR-008 version 8 id (#{reason}); not imported" + ) + {:cont, {:ok, seen, count}} - else - if kind == :audit and fleet_fields_disagree?(record) do - Logger.warning( - "LearningScheduler: fleet row #{line_number}: verdict " <> - "#{inspect(Map.get(record, "verdict"))} disagrees with outcome " <> - "#{inspect(Map.get(record, "outcome"))}; stored as an audit row" - ) - end - case Hypatia.OutcomeTracker.record_fleet_outcome( - recipe_id, - repo, - file, - outcome, - id, - verification, - fleet_receipt_context(record, line, line_number, producer_id) - ) do - # An audit row is stored and acknowledged, and it is not - # counted as a processed outcome. - {:ok, _record} -> - {:cont, - {:ok, MapSet.put(seen, id), count + if(kind == :ok, do: 1, else: 0)}} - - {:error, reason} -> - {:halt, {:error, {:write_failed, line_number, reason}}} + {:ok, id, producer_id} -> + if MapSet.member?(seen, id) do + {:cont, {:ok, seen, count}} + else + if kind == :audit and fleet_fields_disagree?(record) do + Logger.warning( + "LearningScheduler: fleet row #{line_number}: verdict " <> + "#{inspect(Map.get(record, "verdict"))} disagrees with outcome " <> + "#{inspect(Map.get(record, "outcome"))}; stored as an audit row" + ) + end + + case Hypatia.OutcomeTracker.record_fleet_outcome( + recipe_id, + repo, + file, + outcome, + id, + verification, + fleet_receipt_context(record, line, line_number, producer_id) + ) do + # An audit row is stored and acknowledged, and it is not + # counted as a processed outcome. + {:ok, _record} -> + {:cont, + {:ok, MapSet.put(seen, id), count + if(kind == :ok, do: 1, else: 0)}} + + {:error, reason} -> + {:halt, + fleet_import_failure( + {:write_failed, line_number, reason}, + count, + versioned? + )} + end end - end - end + end - :skip -> - {:cont, {:ok, seen, count}} + :skip -> + {:cont, {:ok, seen, count}} + end end {:error, reason} -> if line_number == final_line and not String.ends_with?(content, "\n") do # The producer may still be writing the last record. Retry it. - {:halt, {:error, {:incomplete_fleet_tail, line_number, reason}}} + {:halt, + fleet_import_failure( + {:incomplete_fleet_tail, line_number, reason}, + count, + versioned? + )} else # A permanently malformed historical row must not starve later # valid events. It remains in the append-only source as evidence. @@ -1037,6 +1093,31 @@ defmodule Hypatia.LearningScheduler do end end + defp fleet_import_failure(reason, count, true), do: {:error, reason, count} + defp fleet_import_failure(reason, _count, false), do: {:error, reason} + + defp import_versioned_fleet_line(line, line_number, fleet_file, seen, count) do + case Hypatia.OutcomeTracker.import_fleet_attempt(line, line_number, fleet_file) do + {:stored, row} -> + increment = if Hypatia.OutcomeTracker.qualified_outcome?(row), do: 1, else: 0 + {:cont, {:ok, MapSet.put(seen, row["event_id"]), count + increment}} + + {status, row} when status in [:replayed, :conflict] -> + {:cont, {:ok, MapSet.put(seen, row["event_id"]), count}} + + {:stored_pending, row, reason} -> + increment = if Hypatia.OutcomeTracker.qualified_outcome?(row), do: 1, else: 0 + {:halt, {:error, {:receipt_pending, row["event_id"], reason}, count + increment}} + + {:rejected, reason} -> + Logger.warning("LearningScheduler: fleet row #{line_number} rejected: #{inspect(reason)}") + {:cont, {:ok, seen, count}} + + {:error, reason} -> + {:halt, {:error, {:admission_failed, line_number, reason}, count}} + end + end + # --- Update confidence for all affected recipes --- defp update_affected_recipes(recipe_ids) do diff --git a/lib/outcome_tracker.ex b/lib/outcome_tracker.ex index af32ac620..7a4a43337 100644 --- a/lib/outcome_tracker.ex +++ b/lib/outcome_tracker.ex @@ -37,6 +37,9 @@ defmodule Hypatia.OutcomeTracker do "source_bot" ] + # Consumer-owned v1 evidence cannot be supplied through public metadata. + @admission_keys ~w(attempt_contract admission_version producer_assertion producer_source rescan_observation rescan_not_run observation_id attempt_event_id observer binding) + @doc """ Record an outcome from a fix attempt. @@ -64,7 +67,7 @@ defmodule Hypatia.OutcomeTracker do metadata |> canonical_fields() |> untrusted_verification() - |> Map.drop(@receipt_context_keys), + |> Map.drop(@receipt_context_keys ++ @admission_keys ++ ["fleet_import_id", "origin"]), true, :local_caller ) @@ -176,7 +179,7 @@ defmodule Hypatia.OutcomeTracker do repo, file, outcome, - Map.merge(canonical_fields(audit), %{ + Map.merge(Map.drop(canonical_fields(audit), @admission_keys), %{ "fleet_import_id" => source_id, "origin" => "gitbot-fleet", "verification" => verification @@ -186,6 +189,30 @@ defmodule Hypatia.OutcomeTracker do ) end + @doc false + def import_fleet_attempt(line, line_number, source_path) when is_binary(line) do + store = capture_outcome_store() + digest = :crypto.hash(:sha256, line) |> Base.encode16(case: :lower) + + # This entry accepts a file locator, never an admission map. The helper + # rereads that exact row from the configured feed before constructing facts. + Hypatia.FleetAdmission.import(line_number, source_path, digest, store.data_root, fn recipe, + repo, + file, + outcome, + verification, + metadata -> + fields = + Map.merge(metadata, %{ + "fleet_import_id" => metadata["event_id"], + "origin" => "gitbot-fleet", + "verification" => verification + }) + + do_persist_outcome(recipe, repo, file, outcome, fields, false, :fleet_import, store) + end) + end + @doc """ IDs already imported from fleet, read from the append-only destination so a scheduler restart cannot turn one attempt into repeated training examples. @@ -248,7 +275,28 @@ defmodule Hypatia.OutcomeTracker do publish_to_fleet?, kind \\ :local_caller ) do - store = capture_outcome_store() + do_persist_outcome( + recipe_id, + repo, + file, + outcome, + metadata, + publish_to_fleet?, + kind, + capture_outcome_store() + ) + end + + defp do_persist_outcome( + recipe_id, + repo, + file, + outcome, + metadata, + publish_to_fleet?, + kind, + store + ) do now = DateTime.utc_now() |> DateTime.to_iso8601() outcome_str = Atom.to_string(outcome) @@ -443,6 +491,46 @@ defmodule Hypatia.OutcomeTracker do result end + @doc false + def observe_fleet_target(repo_path, category, file, line) do + case System.find_executable("panic-attack") do + nil -> + {:not_run, :scanner_unavailable} + + executable -> + try do + result = + System.cmd(executable, ["assail", repo_path, "--output-format", "json", "--quiet"], + stderr_to_stdout: true + ) + + verdict = + case result do + {output, 0} -> + case Jason.decode(output) do + {:ok, %{"weak_points" => points}} when is_list(points) -> + if Enum.all?(points, &is_map/1), + do: judge(points, category, file, line), + else: :scan_failed + + _ -> + :scan_failed + end + + _ -> + :scan_failed + end + + {:ran, verdict} + rescue + error in ErlangError -> + if error.original in [:enoent, :eacces], + do: {:not_run, :scanner_unavailable}, + else: reraise(error, __STACKTRACE__) + end + end + end + defp do_verify_fix(repo_path, pattern_id, category, file, line) do # An absent scanner is an absent verifier: no verification, and no crash. result = @@ -670,7 +758,12 @@ defmodule Hypatia.OutcomeTracker do the map, so the map can add a field but cannot change what the rescan found. """ def record_and_verify(recipe_id, repo, file, outcome, opts \\ []) do - extra = opts |> Keyword.get(:metadata, %{}) |> canonical_fields() + extra = + opts + |> Keyword.get(:metadata, %{}) + |> canonical_fields() + |> Map.drop(@receipt_context_keys ++ @admission_keys ++ ["fleet_import_id", "origin"]) + category = Keyword.get(opts, :category, "") verify_requested? = Keyword.get(opts, :verify, false) and outcome == :success @@ -902,6 +995,20 @@ defmodule Hypatia.OutcomeTracker do Enum.reduce(outcomes, %{successes: 0, failures: 0, false_positives: 0, ignored: 0}, fn row, acc -> case row do + %{"attempt_contract" => _} -> + # Tagged producer bytes cannot stamp themselves as an admission. + %{acc | ignored: acc.ignored + 1} + + %{"admission_version" => "fleet-attempt/1"} -> + # v1 has no implemented snapshot binding. Neither a success claim nor + # an adverse current-target rescan can contribute positive/FP weight. + if canonical_fleet_admission?(row) and qualified_fleet_failure?(row), + do: %{acc | failures: acc.failures + 1}, + else: %{acc | ignored: acc.ignored + 1} + + %{"admission_version" => _} -> + %{acc | ignored: acc.ignored + 1} + %{"outcome" => "success", "verification" => "verified"} -> %{acc | successes: acc.successes + 1} @@ -928,6 +1035,52 @@ defmodule Hypatia.OutcomeTracker do end) end + defp qualified_fleet_failure?(%{ + "outcome" => "failure", + "verification" => "failed", + "producer_assertion" => %{ + "verdict" => "failed", + "outcome" => "failure", + "exit_code" => code + } + }) + when is_integer(code) and code != 0, do: true + + defp qualified_fleet_failure?(%{ + "outcome" => "failure", + "verification" => "incomplete", + "producer_assertion" => %{ + "verdict" => "incomplete", + "outcome" => outcome, + "after_hits" => hits + } + }) + when outcome in ["success", "failure"] and is_integer(hits) and hits > 0, do: true + + defp qualified_fleet_failure?(_), do: false + + @doc false + def canonical_fleet_admission?(row) when is_map(row) do + source = row["producer_source"] + assertion = row["producer_assertion"] + id = row["event_id"] + + row["admission_version"] == "fleet-attempt/1" and + not Map.has_key?(row, "attempt_contract") and Hypatia.EventId.valid?(id) and + row["event_id_source"] == "producer" and row["fleet_import_id"] == id and + row["bot"] == "hypatia" and row["origin"] == "gitbot-fleet" and + row["source_kind"] == "fleet_import" and is_map(assertion) and + assertion["attempt_contract"] == "fleet-attempt/1" and assertion["event_id"] == id and + assertion["bot"] == "dispatch-runner" and is_map(source) and + source["bot"] == "dispatch-runner" and is_binary(source["path"]) and + Path.type(source["path"]) == :absolute and + source["log"] == "shared-context/learning/fix-outcomes.jsonl" and + is_integer(source["line"]) and source["line"] > 0 and + is_binary(source["row_sha256"]) and Regex.match?(~r/\A[0-9a-f]{64}\z/, source["row_sha256"]) + end + + def canonical_fleet_admission?(_), do: false + @doc """ Bayesian confidence update using Beta distribution conjugate prior. diff --git a/test/fleet_admission_test.exs b/test/fleet_admission_test.exs new file mode 100644 index 000000000..5f3e937b7 --- /dev/null +++ b/test/fleet_admission_test.exs @@ -0,0 +1,694 @@ +# SPDX-License-Identifier: MPL-2.0 +defmodule Hypatia.FleetAdmissionTest do + use ExUnit.Case, async: false + + import ExUnit.CaptureLog + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + + setup do + app_keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path] + env_keys = ["PATH", "HYPATIA_REPOS_DIR", "FLEET_ADMISSION_CALLS", "FLEET_ADMISSION_SCAN"] + apps = for key <- app_keys, do: {key, Application.fetch_env(:hypatia, key)} + envs = for key <- env_keys, do: {key, System.get_env(key)} + root = Path.join(System.tmp_dir!(), "hypatia_admission_#{System.unique_integer([:positive])}") + data = Path.join(root, "data") + repos = Path.join(root, "repos") + target = Path.join(repos, "owner/repo") + bin = Path.join(root, "bin") + fleet = Path.join(root, "fleet") + feed = Path.join(fleet, "shared-context/learning/fix-outcomes.jsonl") + calls = Path.join(root, "scanner-calls") + scan = Path.join(root, "scan.json") + + for dir <- [target, bin, Path.join(data, "recipes"), Path.dirname(feed)], + do: File.mkdir_p!(dir) + + File.write!(Path.join(target, "a.txt"), "fixture\n") + File.write!(scan, Jason.encode!(%{"weak_points" => []})) + + File.write!(Path.join(bin, "panic-attack"), """ + #!/bin/sh + printf '%s\n' "$2" >> "$FLEET_ADMISSION_CALLS" + while test -f "$FLEET_ADMISSION_SCAN.pause"; do /bin/sleep 0.01; done + /bin/cat "$FLEET_ADMISSION_SCAN" + """) + + File.chmod!(Path.join(bin, "panic-attack"), 0o755) + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, Path.join(root, "annealing")) + Application.put_env(:hypatia, :fleet_path, fleet) + System.put_env("PATH", bin <> ":" <> (System.get_env("PATH") || "")) + System.put_env("HYPATIA_REPOS_DIR", repos) + System.put_env("FLEET_ADMISSION_CALLS", calls) + System.put_env("FLEET_ADMISSION_SCAN", scan) + recipe(data, "recipe-one.json", ["cat-x"]) + + on_exit(fn -> + for {key, value} <- apps do + case value do + {:ok, old} -> Application.put_env(:hypatia, key, old) + :error -> Application.delete_env(:hypatia, key) + end + end + + for {key, value} <- envs do + if value, do: System.put_env(key, value), else: System.delete_env(key) + end + + File.rm_rf!(root) + end) + + %{ + root: root, + data: data, + repos: repos, + target: target, + bin: bin, + feed: feed, + calls: calls, + scan: scan + } + end + + defp recipe(data, name, categories) do + File.write!( + Path.join([data, "recipes", name]), + Jason.encode!(%{ + "id" => "recipe-admission", + "confidence" => 0.5, + "target_categories" => categories + }) + ) + end + + defp attempt(extra \\ %{}) do + Map.merge( + %{ + "attempt_contract" => "fleet-attempt/1", + "event_id" => EventId.generate(), + "bot" => "dispatch-runner", + "recipe_id" => "recipe-admission", + "repo" => "owner/repo", + "repo_relative_path" => "owner/repo", + "file" => "a.txt", + "line" => 3, + "outcome" => "success", + "verdict" => "verified", + "exit_code" => 0, + "before_hits" => 2, + "after_hits" => 0 + }, + extra + ) + end + + defp feed(ctx, records) do + bytes = + Enum.map_join(records, "", fn row -> + if(is_binary(row), do: row, else: Jason.encode!(row)) <> "\n" + end) + + File.write!(ctx.feed, bytes) + end + + defp rows(ctx, directory \\ "outcomes") do + for path <- Path.wildcard(Path.join([ctx.data, directory, "*.jsonl"])), + line <- String.split(File.read!(path), "\n", trim: true), + do: Jason.decode!(line) + end + + defp scans(ctx) do + case File.read(ctx.calls) do + {:ok, bytes} -> String.split(bytes, "\n", trim: true) + {:error, :enoent} -> [] + end + end + + defp sha(bytes), do: :crypto.hash(:sha256, bytes) |> Base.encode16(case: :lower) + + test "v1 clean rescan is correlated unbound audit evidence, never positive credit", ctx do + raw = attempt() + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + assert row["event_id"] == raw["event_id"] + assert row["admission_version"] == "fleet-attempt/1" + assert row["producer_assertion"]["verdict"] == "verified" + assert row["producer_source"]["row_sha256"] == sha(Jason.encode!(raw)) + assert row["producer_source"]["path"] == ctx.feed + assert row["producer_source"]["bot"] == "dispatch-runner" + observation = row["rescan_observation"] + assert observation["binding"] == "unbound" + assert observation["result"] == "verified" + assert observation["observer"] == "hypatia" + assert observation["attempt_event_id"] == raw["event_id"] + assert observation["source_row_sha256"] == sha(Jason.encode!(raw)) + assert EventId.valid?(observation["observation_id"]) + refute observation["observation_id"] == raw["event_id"] + assert observation["target"]["repo_path"] == ctx.target + assert scans(ctx) == [ctx.target] + + assert OutcomeTracker.qualified_outcome_counts([row]) == %{ + successes: 0, + failures: 0, + false_positives: 0, + ignored: 1 + } + + assert [receipt] = Receipt.all(ctx.data) + assert receipt["verdict"] == "audit_only" + refute Map.has_key?(receipt["observations"], "rescan") + assert "rescan" in receipt["missing_evidence"] + assert receipt["parent_event_ids"] == [] + end + + test "still-present unbound rescan neither blames nor adds another outcome", ctx do + File.write!( + ctx.scan, + Jason.encode!(%{ + "weak_points" => [%{"category" => "cat-x", "file" => "a.txt", "line" => 3}] + }) + ) + + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + assert row["rescan_observation"]["result"] == "still_present" + assert row["outcome"] == "success" + assert row["verification"] == "unqualified" + assert OutcomeTracker.qualified_outcome_counts([row]).false_positives == 0 + + assert OutcomeTracker.qualified_outcome_counts([Map.put(row, "verification", "verified")]).successes == + 0 + end + + test "failure evidence retains the existing exact numerical criteria and counts once", ctx do + records = [ + attempt(%{"outcome" => "failure", "verdict" => "failed", "exit_code" => 2}), + attempt(%{"outcome" => "failure", "verdict" => "failed", "exit_code" => 0}), + attempt(%{"verdict" => "incomplete", "after_hits" => 1}), + attempt(%{"verdict" => "incomplete", "after_hits" => 0}), + attempt(%{"verdict" => "no_op"}), + attempt(%{"verdict" => "unverified"}) + ] + + feed(ctx, records) + assert {2, signature} = LearningScheduler.ingest_fleet_outcomes(nil) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(signature) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert length(rows(ctx)) == 6 + + assert OutcomeTracker.qualified_outcome_counts(rows(ctx)) == %{ + successes: 0, + failures: 2, + false_positives: 0, + ignored: 4 + } + + assert scans(ctx) == [] + end + + test "explicit unsupported versions and invalid identities are rejected before legacy routing", + ctx do + records = + for version <- [nil, "", "fleet-attempt/2", 1], + do: attempt(%{"attempt_contract" => version}) + + records = + records ++ + [ + attempt(%{"event_id" => "invalid"}), + Map.delete(attempt(), "event_id"), + attempt(%{"bot" => "other"}) + ] + + feed(ctx, records) + log = capture_log(fn -> assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) end) + assert log =~ "rejected" + assert rows(ctx) == [] + assert scans(ctx) == [] + end + + test "untagged E0-11 rows keep their existing qualification and source receipt", ctx do + raw = attempt() |> Map.delete("attempt_contract") + feed(ctx, [raw]) + assert {1, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + refute Map.has_key?(row, "admission_version") + assert OutcomeTracker.qualified_outcome?(row) + assert [receipt] = Receipt.all(ctx.data) + assert receipt["source"]["log"] == "shared-context/learning/fix-outcomes.jsonl" + assert receipt["proof_or_test_ref"]["row_sha256"] == sha(Jason.encode!(raw)) + assert scans(ctx) == [] + end + + test "producer-supplied admission and observation metadata never become consumer facts", ctx do + raw = + attempt(%{ + "admission_version" => "forged", + "producer_source" => %{"path" => "forged"}, + "rescan_observation" => %{ + "binding" => "bound", + "result" => "verified", + "observation_id" => EventId.generate() + }, + "source_kind" => "local_rescan", + "verification" => "verified", + "category" => "wrong-category" + }) + + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + assert row["admission_version"] == "fleet-attempt/1" + assert row["rescan_observation"]["binding"] == "unbound" + + refute row["rescan_observation"]["observation_id"] == + raw["rescan_observation"]["observation_id"] + + assert row["rescan_observation"]["target"]["category"] == "cat-x" + refute Map.has_key?(row["producer_assertion"], "rescan_observation") + assert row["source_kind"] == "fleet_import" + end + + test "public outcome entry points strip admission and observation identities", ctx do + forged = %{ + admission_version: "fleet-attempt/1", + producer_assertion: %{"verdict" => "verified"}, + producer_source: %{"path" => "forged"}, + rescan_observation: %{"binding" => "bound"}, + rescan_not_run: "forged", + attempt_contract: "fleet-attempt/1", + event_id: EventId.generate() + } + + assert {:ok, row} = + OutcomeTracker.record_outcome("recipe-admission", "repo", "a.txt", :success, forged) + + for key <- + ~w(admission_version producer_assertion producer_source rescan_observation rescan_not_run attempt_contract), + do: refute(Map.has_key?(row, key)) + + refute row["event_id"] == forged.event_id + + assert {:ok, scanned, :verified} = + OutcomeTracker.record_and_verify("recipe-admission", "repo", "a.txt", :success, + verify: true, + category: "cat-x", + repo_path: ctx.target, + metadata: forged + ) + + for key <- + ~w(admission_version producer_assertion producer_source rescan_observation rescan_not_run attempt_contract), + do: refute(Map.has_key?(scanned, key)) + end + + test "replay preserves the committed identity and observation, distinct attempts stay distinct", + ctx do + first = attempt() + second = Map.put(first, "event_id", EventId.generate()) + feed(ctx, [first, first, second]) + assert {0, signature} = LearningScheduler.ingest_fleet_outcomes(nil) + original = rows(ctx) + assert length(original) == 2 + assert length(scans(ctx)) == 2 + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(signature) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert rows(ctx) == original + assert length(scans(ctx)) == 2 + end + + test "same ID with different bytes is a preserved non-authorising conflict", ctx do + raw = attempt() + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + original = rows(ctx) + changed = Jason.encode!(Map.put(raw, "after_hits", 8)) + feed(ctx, [changed]) + log = capture_log(fn -> assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) end) + assert log =~ "conflict" + assert rows(ctx) == original + assert length(scans(ctx)) == 1 + assert [conflict] = rows(ctx, "admission-conflicts") + assert conflict["attempt_event_id"] == raw["event_id"] + assert conflict["raw_source_bytes"] == changed + assert conflict["source_row_sha256"] == sha(changed) + assert conflict["authorising"] == false + end + + test "receipt hashes the persisted admission, and replay repairs it without a new scan", ctx do + raw = attempt() + feed(ctx, [raw]) + assert {0, signature} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + assert {:ok, log, line, bytes} = Receipt.locate(ctx.data, raw["event_id"]) + assert [receipt] = Receipt.all(ctx.data) + + assert receipt["source"] == %{ + "kind" => "fleet_import", + "log" => log, + "line" => Integer.to_string(line) + } + + assert receipt["proof_or_test_ref"]["row_sha256"] == sha(bytes) + refute sha(bytes) == sha(Jason.encode!(raw)) + File.rm_rf!(Path.join(ctx.data, "receipts")) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(signature) + assert Receipt.all(ctx.data) == [receipt] + assert rows(ctx) == [row] + assert length(scans(ctx)) == 1 + end + + test "unsafe, missing and symlink targets do not scan or invent observation IDs", ctx do + outside = Path.join(ctx.root, "outside") + File.mkdir_p!(outside) + File.ln_s!(outside, Path.join(ctx.repos, "escape")) + + for relative <- ["../outside", outside, "escape", "missing", "owner/../repo", nil] do + feed(ctx, [attempt(%{"repo_relative_path" => relative})]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + end + + assert length(rows(ctx)) == 6 + + for row <- rows(ctx) do + assert is_binary(row["rescan_not_run"]) + refute Map.has_key?(row, "rescan_observation") + end + + assert scans(ctx) == [] + end + + test "missing configuration, scanner or unambiguous registry mapping leaves explicit gaps", + ctx do + System.delete_env("HYPATIA_REPOS_DIR") + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + System.put_env("HYPATIA_REPOS_DIR", ctx.repos) + + for categories <- [[], ["cat-x", "cat-y"]] do + recipe(ctx.data, "recipe-one.json", categories) + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + end + + recipe(ctx.data, "recipe-one.json", ["cat-x"]) + recipe(ctx.data, "recipe-two.json", ["cat-x"]) + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + File.rm!(Path.join([ctx.data, "recipes", "recipe-two.json"])) + File.rm!(Path.join(ctx.bin, "panic-attack")) + System.put_env("PATH", ctx.bin) + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert length(rows(ctx)) == 5 + + for row <- rows(ctx) do + assert is_binary(row["rescan_not_run"]) + refute Map.has_key?(row, "rescan_observation") + end + + assert scans(ctx) == [] + end + + test "concurrent public ingest requests serialize one admission", ctx do + feed(ctx, [attempt(%{"outcome" => "failure", "verdict" => "failed", "exit_code" => 7})]) + tasks = for _ <- 1..2, do: Task.async(fn -> LearningScheduler.ingest_fleet_outcomes(nil) end) + results = Enum.map(tasks, &Task.await(&1, 15_000)) + assert Enum.sum(Enum.map(results, &elem(&1, 0))) == 1 + assert length(rows(ctx)) == 1 + end + + test "changed configured source binding conflicts before any new scan", ctx do + raw = attempt() + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + original = rows(ctx) + other_fleet = Path.join(ctx.root, "other-fleet") + other_feed = Path.join(other_fleet, "shared-context/learning/fix-outcomes.jsonl") + File.mkdir_p!(Path.dirname(other_feed)) + File.write!(other_feed, Jason.encode!(raw) <> "\n") + Application.put_env(:hypatia, :fleet_path, other_fleet) + + assert capture_log(fn -> assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) end) =~ + "conflict" + + assert rows(ctx) == original + assert scans(ctx) == [ctx.target] + assert [conflict] = rows(ctx, "admission-conflicts") + assert conflict["source"]["path"] == other_feed + assert conflict["committed_source"]["path"] == ctx.feed + end + + test "changing or removing the version on a committed ID remains a preserved conflict", ctx do + raw = attempt() + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + original = rows(ctx) + + for changed <- [ + Map.delete(raw, "attempt_contract"), + Map.put(raw, "attempt_contract", "fleet-attempt/2") + ] do + feed(ctx, [changed]) + + assert capture_log(fn -> assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) end) =~ + "conflict" + end + + assert rows(ctx) == original + assert length(rows(ctx, "admission-conflicts")) == 2 + assert scans(ctx) == [ctx.target] + end + + test "the internal row locator cannot admit bytes absent from the actual configured feed", + ctx do + raw = attempt() + feed(ctx, [raw]) + + assert {:error, :source_row_changed} = + OutcomeTracker.import_fleet_attempt(Jason.encode!(attempt()), 1, ctx.feed) + + assert {:error, :admission_store_or_source_changed} = + OutcomeTracker.import_fleet_attempt( + Jason.encode!(raw), + 1, + Path.join(ctx.root, "forged.jsonl") + ) + + assert rows(ctx) == [] + assert scans(ctx) == [] + end + + test "an outcome append failure leaves source retryable and contributes nothing", ctx do + feed(ctx, [attempt(%{"outcome" => "failure", "verdict" => "failed", "exit_code" => 3})]) + File.write!(Path.join(ctx.data, "outcomes"), "blocked") + + assert capture_log(fn -> assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) end) =~ + "cannot read imported IDs" + + assert rows(ctx) == [] + assert Receipt.all(ctx.data) == [] + File.rm!(Path.join(ctx.data, "outcomes")) + assert {1, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert length(rows(ctx)) == 1 + assert length(Receipt.all(ctx.data)) == 1 + end + + test "receipt failure counts the committed failure once and repairs without readmission", ctx do + raw = attempt(%{"outcome" => "failure", "verdict" => "failed", "exit_code" => 3}) + feed(ctx, [raw]) + File.write!(Path.join(ctx.data, "receipts"), "blocked") + + assert capture_log(fn -> assert {1, nil} = LearningScheduler.ingest_fleet_outcomes(nil) end) =~ + "receipt_pending" + + assert [row] = rows(ctx) + assert row["event_id"] == raw["event_id"] + assert Receipt.all(ctx.data) == [] + File.rm!(Path.join(ctx.data, "receipts")) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert rows(ctx) == [row] + assert length(Receipt.all(ctx.data)) == 1 + assert OutcomeTracker.qualified_outcome_counts(rows(ctx)).failures == 1 + end + + test "a store switch during a real scan cannot append evidence to either destination", ctx do + pause = ctx.scan <> ".pause" + File.write!(pause, "wait") + feed(ctx, [attempt()]) + task = Task.async(fn -> LearningScheduler.ingest_fleet_outcomes(nil) end) + assert await_scan(ctx, 100) + other_data = Path.join(ctx.root, "other-data") + Application.put_env(:hypatia, :verisimdb_data_path, other_data) + File.rm!(pause) + assert {0, nil} = Task.await(task, 15_000) + assert rows(ctx) == [] + assert rows(%{ctx | data: other_data}) == [] + assert Receipt.all(ctx.data) == [] + assert Receipt.all(other_data) == [] + end + + defp await_scan(_ctx, 0), do: false + + defp await_scan(ctx, remaining) do + if scans(ctx) != [] do + true + else + Process.sleep(10) + await_scan(ctx, remaining - 1) + end + end + + test "receipt repair uses persisted admission even when caller supplies forged context", ctx do + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + original = Receipt.all(ctx.data) + File.rm_rf!(Path.join(ctx.data, "receipts")) + forged = row |> Map.put("verification", "verified") |> Map.put("source_kind", "local_rescan") + + assert :ok = + Receipt.write(ctx.data, forged, + ctx: %{ + kind: :local_rescan, + log: "forged", + line: "1", + row_sha256: String.duplicate("a", 64) + } + ) + + assert Receipt.all(ctx.data) == original + end + + test "malformed scanner output is a closed unbound failure, never blame", ctx do + File.write!(ctx.scan, Jason.encode!(%{"weak_points" => "not-an-array"})) + feed(ctx, [attempt()]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + assert row["rescan_observation"]["result"] == "scan_failed" + assert row["rescan_observation"]["binding"] == "unbound" + assert OutcomeTracker.qualified_outcome_counts([row]).ignored == 1 + end + + test "failure to append after a scan leaves no committed observation or receipt", ctx do + pause = ctx.scan <> ".pause" + File.write!(pause, "wait") + feed(ctx, [attempt()]) + task = Task.async(fn -> LearningScheduler.ingest_fleet_outcomes(nil) end) + assert await_scan(ctx, 100) + File.write!(Path.join(ctx.data, "outcomes"), "blocked") + File.rm!(pause) + assert {0, nil} = Task.await(task, 15_000) + assert rows(ctx) == [] + assert Receipt.all(ctx.data) == [] + File.rm!(Path.join(ctx.data, "outcomes")) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert length(rows(ctx)) == 1 + assert length(Receipt.all(ctx.data)) == 1 + assert length(scans(ctx)) == 2 + end + + test "a complete JSON value without its line terminator is not an admitted attempt", ctx do + raw = attempt() + File.write!(ctx.feed, Jason.encode!(raw)) + assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) + assert rows(ctx) == [] + assert scans(ctx) == [] + File.write!(ctx.feed, "\n", [:append]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert length(rows(ctx)) == 1 + end + + test "a nested ID mention cannot replace the admission's receipt source", ctx do + raw = attempt() + + assert {:ok, _} = + OutcomeTracker.record_outcome("other", "other", "other", :success, %{ + "unrelated" => %{"event_id" => raw["event_id"]} + }) + + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + receipt = Enum.find(Receipt.all(ctx.data), &(&1["event_id"] == raw["event_id"])) + assert receipt + assert receipt["source"]["line"] == "2" + assert receipt["verdict"] == "audit_only" + end + + test "source symlink or hardlink aliases into outcomes or receipts are refused", ctx do + for directory <- ["outcomes", "receipts"], link <- [:symlink, :hardlink] do + raw = attempt() + feed(ctx, [raw]) + File.mkdir_p!(Path.join(ctx.data, directory)) + destination = Path.join([ctx.data, directory, "alias.jsonl"]) + File.rename!(ctx.feed, destination) + + if link == :symlink, + do: File.ln_s!(destination, ctx.feed), + else: File.ln!(destination, ctx.feed) + + assert capture_log(fn -> assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) end) =~ + "source_outcome_alias" + + assert File.read!(destination) == Jason.encode!(raw) <> "\n" + assert scans(ctx) == [] + File.rm!(ctx.feed) + File.rm!(destination) + end + end + + test "tagged raw rows with forged consumer fields in the ledger cannot count or receive a receipt", + ctx do + raw = + attempt(%{ + "admission_version" => "fleet-attempt/1", + "verification" => "verified", + "source_kind" => "local_rescan" + }) + + File.mkdir_p!(Path.join(ctx.data, "outcomes")) + File.write!(Path.join([ctx.data, "outcomes", "raw.jsonl"]), Jason.encode!(raw) <> "\n") + feed(ctx, [raw]) + + assert capture_log(fn -> assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) end) =~ + "conflict" + + assert rows(ctx) == [raw] + assert OutcomeTracker.qualified_outcome_counts([raw]).ignored == 1 + assert {:error, :invalid_admission_row} = Receipt.write(ctx.data, raw) + + assert {:error, :invalid_admission_row} = + Receipt.write(ctx.data, Map.delete(raw, "admission_version")) + + assert Receipt.all(ctx.data) == [] + assert scans(ctx) == [] + end + + test "ambiguous persisted admission identity cannot fall back through stripped caller metadata", + ctx do + raw = attempt() + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + File.write!(Path.join([ctx.data, "outcomes", "other.jsonl"]), Jason.encode!(raw) <> "\n") + File.rm_rf!(Path.join(ctx.data, "receipts")) + + assert {:error, :ambiguous_admission_identity} = + Receipt.write(ctx.data, Map.delete(row, "admission_version")) + + assert Receipt.all(ctx.data) == [] + end + + test "a later incomplete tail does not erase the count of a committed v1 failure", ctx do + raw = attempt(%{"outcome" => "failure", "verdict" => "failed", "exit_code" => 9}) + File.write!(ctx.feed, Jason.encode!(raw) <> "\n{\"attempt_contract\":") + assert {1, nil} = LearningScheduler.ingest_fleet_outcomes(nil) + assert [row] = rows(ctx) + assert row["event_id"] == raw["event_id"] + feed(ctx, [raw]) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert rows(ctx) == [row] + end +end diff --git a/test/neural_source_store_lifecycle_test.exs b/test/neural_source_store_lifecycle_test.exs index 6beca9fef..2b47e91de 100644 --- a/test/neural_source_store_lifecycle_test.exs +++ b/test/neural_source_store_lifecycle_test.exs @@ -721,11 +721,31 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do end test "Kin's default predictor holds before its outer review deadline", ctx do - # Exercise the actual default named-server route, with the application's - # original source restored so its queued call cannot observe a test root. - Application.put_env(:hypatia, :verisimdb_data_path, ctx.original) - server = Process.whereis(Coordinator) - assert is_pid(server) + take_coordinator_name(ctx.original) + + # A prior cohort can stay blocked after another test restores the global + # source. Reproduce that state with owned processes, not application peers. + prior_cohort = isolated_cohort() + prior = named_coordinator(prior_cohort) + assert {:ok, %{source_status: :ready}} = barrier(prior, ctx.first) + vae = Keyword.fetch!(prior_cohort, :named_networks).vae + Application.put_env(:hypatia, :verisimdb_data_path, ctx.second) + + assert {:error, {:source_store_changed, first, second}} = + GenServer.call(vae, {:snapshot, ctx.first}) + + assert {first, second} == {ctx.first, ctx.second} + Application.put_env(:hypatia, :verisimdb_data_path, ctx.first) + + assert {:error, {:neural_source_unavailable, %{source_status: :blocked}}} = + barrier(prior, ctx.first) + + # The timeout fixture owns a fresh complete cohort under the production + # name; an inherited application cohort is not a readiness precondition. + stop_supervised!(Coordinator) + server = named_coordinator(isolated_cohort()) + assert Process.whereis(Coordinator) == server + assert {:ok, %{source_status: :ready}} = barrier(server, ctx.first) :ok = :sys.suspend(server) action = %{ @@ -742,9 +762,9 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do after if Process.alive?(task.pid), do: Task.shutdown(task, :brutal_kill) :sys.resume(server) - # Drain the ordinary dispatch request while the original root is - # still selected; a system-state query would bypass this mailbox. - assert {:ok, %{source_status: :ready}} = barrier(server, ctx.original) + # Drain the ordinary dispatch request while its source is still + # selected; a system-state query would bypass this mailbox. + assert {:ok, %{source_status: :ready}} = barrier(server, ctx.first) end assert {:ok, {:hold, reason}} = result @@ -841,6 +861,43 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do [named_networks: networks, blackboard: isolated_process(Blackboard, isolated: true)] end + # Keep the application child and its state intact while the real default-name + # API uses a test-supervised cohort. Register restoration before the handoff. + defp take_coordinator_name(original_source) do + original = Process.whereis(Coordinator) + assert is_pid(original) + + on_exit(fn -> + Application.put_env(:hypatia, :verisimdb_data_path, original_source) + + case Process.whereis(Coordinator) do + ^original -> + :ok + + other -> + if is_pid(other) do + :ok = :sys.resume(other) + :ok = GenServer.stop(other, :normal, 5_000) + end + + assert Process.register(original, Coordinator) + end + + :ok = :sys.resume(original) + end) + + :ok = :sys.suspend(original) + assert Process.unregister(Coordinator) + end + + defp named_coordinator(cohort) do + start_supervised!(%{ + id: Coordinator, + start: {GenServer, :start_link, [Coordinator, cohort, [name: Coordinator]]}, + restart: :temporary + }) + end + defp named_sequence(name) do start_supervised!(%{ id: make_ref(),