From 7d4e8c35ea31c17a07635cdb447e1cc2c95abe91 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:51:12 +0000 Subject: [PATCH] fix(learning): recover fleet receipts and derived state after partial writes --- .../NS-01-fleet-recovery.adoc | 133 +++++++ lib/hypatia/receipt.ex | 39 +- lib/learning_scheduler.ex | 26 +- lib/outcome_tracker.ex | 24 +- test/fleet_recovery_scheduler_test.exs | 373 ++++++++++++++++++ test/learning_scheduler_test.exs | 4 +- test/receipt_test.exs | 53 +++ 7 files changed, 625 insertions(+), 27 deletions(-) create mode 100644 docs/operations/nesy-reinforcement/NS-01-fleet-recovery.adoc create mode 100644 test/fleet_recovery_scheduler_test.exs diff --git a/docs/operations/nesy-reinforcement/NS-01-fleet-recovery.adoc b/docs/operations/nesy-reinforcement/NS-01-fleet-recovery.adoc new file mode 100644 index 000000000..ba51ad053 --- /dev/null +++ b/docs/operations/nesy-reinforcement/NS-01-fleet-recovery.adoc @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += NS-01: Fleet receipt and derived-state recovery +:toc: + +Date: 2026-11-23. Baseline: `d158aed87f76b93e4f291e995bef9f26559c7fb2`. +Scope: recovery of already committed fleet outcome rows by the existing +LearningScheduler. This is a bounded reinforcement of the E0 consumer path, +not an E0 closeout or a new Kautz classification. + +== Demonstrated failure + +Fleet import appends the destination outcome before writing its receipt and +derived annealing/recipe state. Those later writes can fail without undoing the +committed outcome. The fleet signature cache and persisted import IDs then +correctly suppress re-import, but the local scheduler reader also discarded the +fleet row's recipe ID. A fleet-only workload therefore had no path selecting +that recipe for repair, including after a scheduler restart. + +Selecting the recipe exposed a second failure: successful scalar recomputation +hid a failed receipt repair, so the scheduler dropped pending work after its +destination cursor advanced. The regression demonstrated both failures before +the corresponding fixes. + +== Change + +* The local reader retains fleet recipe IDs for reconciliation without counting + their events again. Imported-event counts and reconciliation targets remain + separate. +* `OutcomeTracker.update_recipe_confidence/1` captures one store for receipt + repair and derived recomputation. A retryable receipt error remains an error + even when scalar persistence succeeds; recomputation still runs. +* `Receipt.repair_with_status/2` distinguishes written, pending and refused + receipts. The existing `repair/2` tuple remains compatible: its failed count + includes both pending failures and final refusals. +* The existing final reasons, `duplicate_event_id` and + `verified_without_evidence`, are shared with `report_failure/2`. They remain + visible refusals and do not alone keep a recipe pending. Other failures retain + the existing pending classification. No evidence or receipt is invented. + +No event ID, qualification rule, fleet quarantine or neural learning guard is +relaxed. Existing fixed-prior confidence and annealing reconciliation perform +the recovery; repeated computation is allowed, repeated evidence credit is not. + +== Executed evidence + +All runs used `MIX_ENV=test`, Elixir 1.19.4, Erlang/OTP 27.3.4.19 and seed 0. +The scheduler fixture uses actual GenServer cycles, temporary outcome/recipe/ +receipt/fleet stores, disabled service and peer polling, and a fresh temporary +action-SHA cache. Application-owned scheduler/anomaly timers are suspended and +the neural coordinator is unavailable during each fixture, then restored. + +[cols="2,3,1",options="header"] +|=== +|Stage |Observation |Result +|Baseline production code, initial three-test regression +|Receipt retry lost; cold restart unrepaired; audit receipts absent +|3 tests, 3 failures +|Fleet recipe selection only +|Cold recovery passes; receipt-only and audit retries still lost +|3 tests, 2 failures +|Recipe selection plus receipt retry status +|The original three scheduler scenarios pass +|3 tests, 0 failures +|Independent review: terminal refusal plus transient failure for one recipe +|After the I/O obstacle clears, provisional code retains the final refusal in pending work +|1 test, 1 failure +|Final focused set, including receipt model mirrors and compatibility control +|Recovery, refusal distinction, source boundaries and existing qualification controls pass +|195 tests, 0 failures, 3 skipped +|=== + +The original three-test before/after command was: + +[source,shell] +---- +mix test test/fleet_recovery_scheduler_test.exs --seed 0 +---- + +The coordinator subsequently combined the reviewed NS-01 and NS-03 source +patches in a separate checkout of the same base. With the CI-pinned Nickel +1.11.0 binary (SHA-256 +`d40cd32b8374636fda8939a8e479616c7a1db57acb5ef5a9621e242ed8f5a361`), +`mix test --seed 0` reported `3742 tests, 0 failures (246 excluded)` and no +skips. All three receipt-contract checks therefore ran in that combined run. +Compilation with warnings as errors, repository-wide formatting, README +claims, the no-active-Logtalk check and diff whitespace checks also passed. +The 246 exclusions remain those declared in `test/test_helper.exs`; this is +local evidence for the combined source, not a hosted-CI or deployment result. + +The terminal-refusal failing-before command was +`mix test test/fleet_recovery_scheduler_test.exs:243 --seed 0`, after adding that +fourth test and before distinguishing final refusals. The final command was: + +[source,shell] +---- +mix test test/fleet_recovery_scheduler_test.exs \ + test/learning_scheduler_test.exs test/receipt_test.exs \ + test/receipt_model_mirror_test.exs test/outcome_tracker_runtime_store_test.exs \ + test/learning_runtime_store_test.exs test/outcome_tracker_test.exs \ + test/confidence_annealing_test.exs --seed 0 +---- + +The actual scheduler controls cover: + +* Unchanged fleet bytes, an advanced destination cursor, and a receipt path + still blocked when scalar recomputation succeeds. Removing the obstacle + repairs the receipt from pending work. +* Receipt and annealing write failures followed by a fresh scheduler whose + cursor, signature and pending set are empty. The fleet-only committed row and + persisted producer ID suffice to recover without manual recipe selection. +* Repeated polls preserve outcome, receipt, recipe and annealing bytes, with one + qualified observation, no duplicate append and no additional reheat. +* Unverified/no-op audit rows gain receipts without positive or negative credit; + start rows are skipped. Audit-only recipes acquire no annealing evidence. +* A final refusal and a retryable I/O failure on the same recipe remain distinct. + The valid receipt recovers, the refused row and warning remain, and a later + idle poll neither repeats the refusal nor recomputes the recipe. + +== Claim boundary + +These are controlled write-failure and fresh-process tests. They establish +recovery and idempotent evidence credit for the tested consumer paths. They do +not prove filesystem power-loss durability, an atomic multi-file transaction, +concurrent-writer safety, exactly-once neural parameter updates, or fleet +producer conformance. Scheduler diagnostic counters remain process-local. + +Final refusals can be reported again on restart or when new outcomes select the +recipe. Rows without event IDs keep the existing no-backfill behaviour. Other +invalid evidence or an unregistered recipe may require intervention; not every +pending entry is guaranteed to clear. The focused run's three skips are +recorded above; the subsequent combined run executed those Nickel checks. +Neither run establishes production rollout or the excluded external-data +and integration capabilities. diff --git a/lib/hypatia/receipt.ex b/lib/hypatia/receipt.ex index ae78a6867..620c3b2c1 100644 --- a/lib/hypatia/receipt.ex +++ b/lib/hypatia/receipt.ex @@ -42,6 +42,7 @@ defmodule Hypatia.Receipt do @fleet_log "shared-context/learning/fix-outcomes.jsonl" @rescans ~w(verified still_present scan_failed scan_skipped) @qualifications ~w(verified failed incomplete still_present) + @terminal_refusals [:duplicate_event_id, :verified_without_evidence] # ── Building ─────────────────────────────────────────────────────────── @@ -372,7 +373,7 @@ defmodule Hypatia.Receipt do # receipt (the row is stored and the log says why); any other failure is pending and # is written when the recipe is next recomputed. def report_failure(event_id, reason) - when reason in [:duplicate_event_id, :verified_without_evidence] do + when reason in @terminal_refusals do Logger.warning( "receipt_refused event_id=#{event_id} reason=#{inspect(reason)}: the row is stored; " <> "no receipt is written for it" @@ -497,30 +498,52 @@ defmodule Hypatia.Receipt do @doc """ Write the receipt of every row of a recipe that has an `event_id` and no receipt. Rows with no `event_id` (written before E0-09) get none: nothing is back-filled. - Returns `{written, failed}`. A receipt whose `event_id` has no row in the log is - not touched; `orphans/1` reports it. + Returns `{written, failed}`; `failed` includes both retryable failures and final + refusals. Call `repair_with_status/2` when deciding whether to retry. A receipt + whose `event_id` has no row in the log is not touched; `orphans/1` reports it. """ @spec repair(String.t(), String.t()) :: {non_neg_integer(), non_neg_integer()} def repair(data_root, recipe_id) do + result = repair_with_status(data_root, recipe_id) + {result.written, result.pending + result.refused} + end + + @doc """ + Repair missing receipts, distinguishing retryable failures (`pending`) from + the final refusals logged by `report_failure/2` (`refused`). A refused row is + still stored and reported; it never receives a fabricated receipt or, by + itself, schedules another retry. Existing receipts and rows without an event + id are skipped, as in `repair/2`. + """ + @spec repair_with_status(String.t(), String.t()) :: %{ + written: non_neg_integer(), + pending: non_neg_integer(), + refused: non_neg_integer() + } + def repair_with_status(data_root, recipe_id) do rows_of_recipe(data_root, recipe_id) - |> Enum.reduce({0, 0}, fn row, {written, failed} -> + |> Enum.reduce(%{written: 0, pending: 0, refused: 0}, fn row, result -> id = Map.get(row, "event_id") cond do not is_binary(id) -> - {written, failed} + result exists?(data_root, id) -> - {written, failed} + result true -> case write(data_root, row) do :ok -> - {written + 1, failed} + %{result | written: result.written + 1} + + {:error, reason} when reason in @terminal_refusals -> + report_failure(id, reason) + %{result | refused: result.refused + 1} {:error, reason} -> report_failure(id, reason) - {written, failed + 1} + %{result | pending: result.pending + 1} end end end) diff --git a/lib/learning_scheduler.ex b/lib/learning_scheduler.ex index 00f7e28b6..dd24b3f61 100644 --- a/lib/learning_scheduler.ex +++ b/lib/learning_scheduler.ex @@ -683,19 +683,19 @@ defmodule Hypatia.LearningScheduler do else case Jason.decode(line) do {:ok, record} when is_map(record) -> - # Imported fleet entries are already handled by the fleet - # poll. Do not re-count them on the local poll. - if Map.get(record, "origin") == "gitbot-fleet" do - {count, recipes, quarantined} - else - recipe_ids = - record - |> Map.get("recipe_id") - |> List.wrap() - |> Enum.reject(&is_nil/1) - - {count + 1, MapSet.union(recipes, MapSet.new(recipe_ids)), quarantined} - end + recipe_ids = + record + |> Map.get("recipe_id") + |> List.wrap() + |> Enum.reject(&is_nil/1) + + # Fleet import already counted the event, but may have committed + # its row before a receipt or derived write failed. Keep its recipe + # eligible for reconciliation, including after a scheduler restart. + local_count = + if Map.get(record, "origin") == "gitbot-fleet", do: count, else: count + 1 + + {local_count, MapSet.union(recipes, MapSet.new(recipe_ids)), quarantined} {:ok, _not_a_map} -> Logger.warning( diff --git a/lib/outcome_tracker.ex b/lib/outcome_tracker.ex index af32ac620..f59dae27e 100644 --- a/lib/outcome_tracker.ex +++ b/lib/outcome_tracker.ex @@ -387,12 +387,15 @@ defmodule Hypatia.OutcomeTracker do # Write the receipts that a failed write left missing, into the store that the # recipe is recomputed in. It never raises. - defp repair_receipts(recipe_id) do - store = capture_outcome_store() - Hypatia.Receipt.repair(store.data_root, recipe_id) + defp repair_receipts(recipe_id, store) do + case Hypatia.Receipt.repair_with_status(store.data_root, recipe_id) do + %{pending: 0} -> :ok + %{pending: failed} -> {:error, {:receipt_repair_pending, failed}} + end rescue error -> Logger.warning("receipt repair failed for #{recipe_id}: #{Exception.message(error)}") + {:error, {:receipt_repair_failed, Exception.message(error)}} end # A row that the fleet import stored without qualifying it. @@ -799,10 +802,21 @@ defmodule Hypatia.OutcomeTracker do Write failures remain errors. The annealing and recipe writes are not an atomic multi-file transaction; a later refusal can leave an earlier A write, but cannot redirect that operation to B. + + Missing receipts are repaired before recomputation. A retryable repair failure + does not block the derived update, but remains an error so the scheduler keeps + the recipe pending even when its scalar confidence was successfully persisted. + Final receipt refusals remain logged and do not themselves schedule retries. """ def update_recipe_confidence(recipe_id) do - repair_receipts(recipe_id) - update_recipe_confidence(recipe_id, fn -> :ok end) + store = capture_outcome_store() + receipt_result = repair_receipts(recipe_id, store) + confidence_result = do_update_recipe_confidence(recipe_id, store, fn -> :ok end) + + case receipt_result do + :ok -> confidence_result + error -> error + end end # The barrier is a deterministic control seam; production uses the same diff --git a/test/fleet_recovery_scheduler_test.exs b/test/fleet_recovery_scheduler_test.exs new file mode 100644 index 000000000..2de78fb8c --- /dev/null +++ b/test/fleet_recovery_scheduler_test.exs @@ -0,0 +1,373 @@ +# SPDX-License-Identifier: MPL-2.0 +# NS-01: drive the real scheduler over isolated fleet and destination stores. +defmodule Hypatia.FleetRecoverySchedulerTest do + use ExUnit.Case, async: false + + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + alias Hypatia.Neural.Coordinator + + @moduletag timeout: 120_000 + @moduletag capture_log: true + @scheduler_id :fleet_recovery_scheduler + + setup do + original_root = Application.fetch_env!(:hypatia, :verisimdb_data_path) + assert String.contains?(Path.expand(original_root), "/_build/test/verisim-data") + + keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path, :cross_org_policies] + original = Map.new(keys, &{&1, Application.fetch_env(:hypatia, &1)}) + urls = Map.new(~w(HYPATIA_VERISIM_URL HYPATIA_ECHIDNABOT_URL), &{&1, System.get_env(&1)}) + cwd = File.cwd!() + + root = + Path.join(System.tmp_dir!(), "hypatia-fleet-recovery-#{System.unique_integer([:positive])}") + + data = Path.join(root, "data") + fleet = Path.join(root, "fleet") + annealing = Path.join(data, "annealing-states") + + # An application-owned scheduler or anomaly timer must not use this test's + # temporary global roots. The neural coordinator is unavailable during the + # test: a scheduler cycle must not train or block that unrelated cohort. + paused = + for module <- [LearningScheduler, Hypatia.Watcher.AnomalyDetector], + pid = Process.whereis(module), + is_pid(pid), + do: pid + + coordinator_running? = + is_pid(Process.whereis(Hypatia.Supervisor)) and is_pid(Process.whereis(Coordinator)) + + on_exit(fn -> + File.cd!(cwd) + + for {key, value} <- original do + case value do + {:ok, previous} -> Application.put_env(:hypatia, key, previous) + :error -> Application.delete_env(:hypatia, key) + end + end + + for {key, value} <- urls do + if value == nil, do: System.delete_env(key), else: System.put_env(key, value) + end + + if coordinator_running? do + case Supervisor.restart_child(Hypatia.Supervisor, Coordinator) do + {:ok, _pid} -> :ok + {:error, :running} -> :ok + other -> raise "could not restore neural coordinator: #{inspect(other)}" + end + end + + for pid <- paused, Process.alive?(pid), do: :sys.resume(pid) + File.rm_rf!(root) + end) + + for pid <- paused, do: :ok = :sys.suspend(pid) + + if coordinator_running?, + do: :ok = Supervisor.terminate_child(Hypatia.Supervisor, Coordinator) + + for part <- ["outcomes", "recipes"], do: File.mkdir_p!(Path.join(data, part)) + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, annealing) + Application.put_env(:hypatia, :fleet_path, fleet) + Application.put_env(:hypatia, :cross_org_policies, []) + for key <- Map.keys(urls), do: System.delete_env(key) + + # The scheduler's daily SHA job uses this relative cache. A fresh file in + # the isolated cwd prevents it from spawning a network-capable Mix task. + File.write!(Path.join(data, "verified-action-shas.json"), "{}\n") + File.cd!(root) + + %{root: root, data: data, fleet: fleet, annealing: annealing} + end + + test "unchanged fleet bytes retain receipt work after the destination cursor advances", ctx do + id = "recipe-fleet-receipt-retry" + recipe_path = write_recipe(ctx, id) + row = fleet_row(id, "verified") + fleet_path = write_fleet(ctx, [row]) + fleet_bytes = File.read!(fleet_path) + receipts_path = Path.join(ctx.data, "receipts") + File.write!(receipts_path, "blocked") + server = start_scheduler() + + first = cycle(server) + assert first.total_outcomes_processed == 1 + assert [stored] = rows(ctx) + assert stored["event_id"] == row["event_id"] + assert stored["event_id_source"] == "producer" + assert stored["origin"] == "gitbot-fleet" + assert Receipt.all(ctx.data) == [] + assert read_json(recipe_path)["successful_fixes"] == 1 + initial_annealing = read_json(Path.join(ctx.annealing, id <> ".json")) + + # The source signature now skips importing; local replay must still select + # the committed fleet row for repair without counting another outcome. + blocked = cycle(server) + assert blocked.last_fleet_signature == first.last_fleet_signature + assert blocked.total_outcomes_processed == 1 + assert map_size(blocked.last_outcome_positions) == 1 + assert MapSet.member?(blocked.pending_confidence_recipes, id) + assert blocked.total_confidence_updates == 0 + assert Receipt.all(ctx.data) == [] + assert read_json(recipe_path)["successful_fixes"] == 1 + + File.rm!(receipts_path) + recovered = cycle(server) + assert recovered.last_outcome_positions == blocked.last_outcome_positions + assert recovered.last_fleet_signature == first.last_fleet_signature + assert recovered.total_outcomes_processed == 1 + assert recovered.total_confidence_updates == 1 + assert recovered.pending_confidence_recipes == MapSet.new() + assert [%{"event_id" => event_id}] = Receipt.all(ctx.data) + assert event_id == row["event_id"] + assert read_json(Path.join(ctx.annealing, id <> ".json")) == initial_annealing + + before_replay = persisted_bytes(ctx) + replayed = cycle(server) + assert replayed.total_outcomes_processed == 1 + assert replayed.total_confidence_updates == 1 + assert persisted_bytes(ctx) == before_replay + assert File.read!(fleet_path) == fleet_bytes + end + + test "a fresh scheduler repairs receipt and derived writes from a fleet-only committed row", + ctx do + id = "recipe-fleet-cold-recovery" + recipe_path = write_recipe(ctx, id) + row = fleet_row(id, "verified") + fleet_path = write_fleet(ctx, [row]) + fleet_bytes = File.read!(fleet_path) + receipts_path = Path.join(ctx.data, "receipts") + File.write!(receipts_path, "blocked") + File.write!(ctx.annealing, "blocked") + server = start_scheduler() + + first = cycle(server) + checkpoint = cycle(server) + assert first.total_outcomes_processed == 1 + assert checkpoint.total_outcomes_processed == 1 + assert map_size(checkpoint.last_outcome_positions) == 1 + assert [stored] = rows(ctx) + assert stored["origin"] == "gitbot-fleet" + assert stored["event_id"] == row["event_id"] + assert {:ok, imported_ids} = OutcomeTracker.imported_fleet_ids() + assert imported_ids == MapSet.new([row["event_id"]]) + assert Receipt.all(ctx.data) == [] + refute Map.has_key?(read_json(recipe_path), "successful_fixes") + + # No manual recipe selection and no unrelated local event can rescue this. + # A new process loses all pending work and cursors; only the log survives. + :ok = stop_supervised(@scheduler_id) + restarted = start_scheduler() + fresh = GenServer.call(restarted, :status) + assert fresh.last_outcome_positions == %{} + assert fresh.last_fleet_signature == nil + assert fresh.pending_confidence_recipes == MapSet.new() + File.rm!(receipts_path) + File.rm!(ctx.annealing) + + repaired = cycle(restarted) + assert repaired.total_outcomes_processed == 0 + assert repaired.last_fleet_signature == first.last_fleet_signature + assert repaired.pending_confidence_recipes == MapSet.new() + assert [%{"event_id" => event_id}] = Receipt.all(ctx.data) + assert event_id == row["event_id"] + assert MapSet.member?(checkpoint.pending_confidence_recipes, id) + assert repaired.total_confidence_updates == 1 + recipe = read_json(recipe_path) + assert recipe["successful_fixes"] == 1 + assert recipe["failed_fixes"] == 0 + assert recipe["total_attempts"] == 1 + assert recipe["unqualified_attempts"] == 0 + annealing = read_json(Path.join(ctx.annealing, id <> ".json")) + assert annealing["outcome_count"] == 1 + assert annealing["last_reheat"] == nil + + before_replay = persisted_bytes(ctx) + assert cycle(restarted).total_outcomes_processed == 0 + assert cycle(restarted).total_outcomes_processed == 0 + assert persisted_bytes(ctx) == before_replay + assert rows(ctx) == [stored] + assert File.read!(fleet_path) == fleet_bytes + end + + test "repairing audit receipts gives unverified, no-op and start rows no learning credit", + ctx do + ids = ["recipe-fleet-unverified", "recipe-fleet-no-op"] + recipe_paths = Enum.map(ids, &write_recipe(ctx, &1)) + audit_rows = Enum.zip_with(ids, ["unverified", "no_op"], &fleet_row/2) + start = fleet_row("recipe-fleet-start", "verified") |> Map.put("kind", "start") + write_fleet(ctx, audit_rows ++ [start]) + receipts_path = Path.join(ctx.data, "receipts") + File.write!(receipts_path, "blocked") + server = start_scheduler() + + assert cycle(server).total_outcomes_processed == 0 + blocked = cycle(server) + assert blocked.total_outcomes_processed == 0 + File.rm!(receipts_path) + recovered = cycle(server) + assert recovered.total_outcomes_processed == 0 + assert recovered.pending_confidence_recipes == MapSet.new() + assert length(Receipt.all(ctx.data)) == 2 + + assert Enum.map(Receipt.all(ctx.data), & &1["event_id"]) |> Enum.sort() == + Enum.map(audit_rows, & &1["event_id"]) |> Enum.sort() + + stored = rows(ctx) + assert length(stored) == 2 + + assert OutcomeTracker.qualified_outcome_counts(stored) == + %{successes: 0, failures: 0, false_positives: 0, ignored: 2} + + for path <- recipe_paths do + recipe = read_json(path) + assert recipe["confidence"] == 0.6 + assert recipe["successful_fixes"] == 0 + assert recipe["failed_fixes"] == 0 + assert recipe["false_positives"] == 0 + assert recipe["unqualified_attempts"] == 1 + assert recipe["annealing"]["outcome_count"] == 0 + end + + refute File.exists?(ctx.annealing) + before_replay = persisted_bytes(ctx) + assert cycle(server).total_outcomes_processed == 0 + assert persisted_bytes(ctx) == before_replay + end + + test "a terminal receipt refusal does not mask a retryable failure for the same recipe", ctx do + id = "recipe-fleet-mixed-receipt-status" + recipe_path = write_recipe(ctx, id) + refused_id = EventId.generate() + + # A historical, inconsistent fleet row cannot satisfy the receipt contract: + # it claims verified without any observations. Its unknown outcome remains + # audit-only under the unchanged qualification gate. + refused_row = %{ + "event_id" => refused_id, + "event_id_source" => "producer", + "fleet_import_id" => refused_id, + "origin" => "gitbot-fleet", + "source_kind" => "fleet_import", + "recipe_id" => id, + "repo" => "fixture/repo", + "file" => "src/legacy.ex", + "outcome" => "unknown", + "verification" => "verified" + } + + File.write!( + Path.join([ctx.data, "outcomes", "legacy.jsonl"]), + Jason.encode!(refused_row) <> "\n" + ) + + valid_row = fleet_row(id, "verified") + write_fleet(ctx, [valid_row]) + receipts_path = Path.join(ctx.data, "receipts") + File.write!(receipts_path, "blocked") + server = start_scheduler() + + blocked_log = + ExUnit.CaptureLog.capture_log(fn -> + blocked = cycle(server) + assert blocked.total_outcomes_processed == 1 + assert MapSet.member?(blocked.pending_confidence_recipes, id) + assert blocked.total_confidence_updates == 0 + end) + + assert blocked_log =~ "receipt_refused event_id=#{refused_id}" + assert blocked_log =~ "verified_without_evidence" + assert blocked_log =~ "receipt_pending event_id=#{valid_row["event_id"]}" + assert Receipt.all(ctx.data) == [] + + File.rm!(receipts_path) + + recovered_log = + ExUnit.CaptureLog.capture_log(fn -> + recovered = cycle(server) + assert recovered.pending_confidence_recipes == MapSet.new() + assert recovered.total_confidence_updates == 1 + assert recovered.total_outcomes_processed == 1 + end) + + assert recovered_log =~ "receipt_refused event_id=#{refused_id}" + assert [%{"event_id" => event_id}] = Receipt.all(ctx.data) + assert event_id == valid_row["event_id"] + assert refused_row in rows(ctx) + assert read_json(recipe_path)["successful_fixes"] == 1 + assert read_json(recipe_path)["unqualified_attempts"] == 1 + + before_replay = persisted_bytes(ctx) + + replay_log = + ExUnit.CaptureLog.capture_log(fn -> + replayed = cycle(server) + assert replayed.pending_confidence_recipes == MapSet.new() + assert replayed.total_confidence_updates == 1 + end) + + refute replay_log =~ "receipt_refused" + assert persisted_bytes(ctx) == before_replay + end + + defp start_scheduler do + start_supervised!(%{ + id: @scheduler_id, + start: {GenServer, :start_link, [LearningScheduler, [], []]} + }) + end + + defp cycle(server) do + GenServer.cast(server, :run_cycle) + GenServer.call(server, :status, 30_000) + end + + defp write_recipe(ctx, id) do + path = Path.join([ctx.data, "recipes", id <> ".json"]) + File.write!(path, Jason.encode!(%{"id" => id, "confidence" => 0.6}) <> "\n") + path + end + + defp fleet_row(id, verdict) do + %{ + "event_id" => EventId.generate(), + "recipe_id" => id, + "repo" => "fixture/repo", + "file" => "src/fixture.ex", + "bot" => "robot-repo-automaton", + "outcome" => "success", + "verdict" => verdict, + "exit_code" => 0, + "before_hits" => 2, + "after_hits" => 0 + } + end + + defp write_fleet(ctx, rows) do + path = Path.join([ctx.fleet, "shared-context/learning/fix-outcomes.jsonl"]) + File.mkdir_p!(Path.dirname(path)) + File.write!(path, Enum.map_join(rows, "", &(Jason.encode!(&1) <> "\n"))) + path + end + + defp rows(ctx) do + Path.wildcard(Path.join([ctx.data, "outcomes", "*.jsonl"])) + |> Enum.flat_map(fn path -> + path |> File.read!() |> String.split("\n", trim: true) |> Enum.map(&Jason.decode!/1) + end) + end + + defp read_json(path), do: path |> File.read!() |> Jason.decode!() + + defp persisted_bytes(ctx) do + for path <- Path.wildcard(Path.join(ctx.data, "**/*")), + File.regular?(path), + into: %{}, + do: {Path.relative_to(path, ctx.data), File.read!(path)} + end +end diff --git a/test/learning_scheduler_test.exs b/test/learning_scheduler_test.exs index 486f71eb0..f3f390fe2 100644 --- a/test/learning_scheduler_test.exs +++ b/test/learning_scheduler_test.exs @@ -483,9 +483,11 @@ defmodule Hypatia.LearningSchedulerTest do {_positions, count, recipes} = LearningScheduler.ingest_new_outcomes(%{}) - # Only the local record is counted. + # Only the local record is counted. Both recipes still need receipt and + # derived-state reconciliation in case an earlier write was interrupted. assert count == 1 assert MapSet.member?(recipes, "recipe-a") + assert MapSet.member?(recipes, "recipe-b") end end diff --git a/test/receipt_test.exs b/test/receipt_test.exs index 4811bc11e..bf14d4ab0 100644 --- a/test/receipt_test.exs +++ b/test/receipt_test.exs @@ -646,6 +646,59 @@ defmodule Hypatia.ReceiptTest do end describe "the failure rule" do + test "repair distinguishes final refusal from pending I/O while preserving the tuple contract", + %{data: data} do + recipe_id = "recipe-repair-status" + + valid = %{ + "event_id" => EventId.generate(), + "recipe_id" => recipe_id, + "repo" => "o/r", + "file" => "f", + "outcome" => "failure", + "verification" => "failed", + "source_kind" => "local_caller" + } + + refused = + Map.merge(valid, %{ + "event_id" => EventId.generate(), + "outcome" => "unknown", + "verification" => "verified" + }) + + File.mkdir_p!(Path.join(data, "outcomes")) + + File.write!( + Path.join([data, "outcomes", "repair-status.jsonl"]), + Enum.map_join([valid, refused], "", &(Jason.encode!(&1) <> "\n")) + ) + + receipts_path = Path.join(data, "receipts") + File.write!(receipts_path, "blocked") + + log = + capture_log(fn -> + assert {0, 2} = Receipt.repair(data, recipe_id) + + assert %{written: 0, pending: 1, refused: 1} = + Receipt.repair_with_status(data, recipe_id) + + File.rm!(receipts_path) + + assert %{written: 1, pending: 0, refused: 1} = + Receipt.repair_with_status(data, recipe_id) + + assert {0, 1} = Receipt.repair(data, recipe_id) + end) + + assert log =~ "receipt_refused event_id=#{refused["event_id"]}" + assert log =~ "receipt_pending event_id=#{valid["event_id"]}" + assert [%{"event_id" => id}] = Receipt.all(data) + assert id == valid["event_id"] + assert length(rows(data)) == 2 + end + test "the row write fails: nothing else runs and no receipt is written", %{ root: root, data: data