diff --git a/docs/reference/protocols/periodic-report-v0.md b/docs/reference/protocols/periodic-report-v0.md index f7f2e7e95a..93bb8d13fd 100644 --- a/docs/reference/protocols/periodic-report-v0.md +++ b/docs/reference/protocols/periodic-report-v0.md @@ -105,9 +105,13 @@ verified publication cursor does so. Registration reordering retains the frozen reporter. A subscription edit can supersede an unprepared window: admission archives the predecessor before -replacing it, under the same lock used by editorial preparation. Restarting -between those writes repeats the replacement safely; it does not record a -publication. The replacement uses the current subscription and elected reporter. +replacing it, under the same lock used by editorial preparation. New archive +references identify the complete admission record. Returning to the same +configuration in the same window retains distinct admissions. The journal +reader also accepts earlier references based on window IDs. A restart between +the archive and replacement writes reuses the same predecessor archive. This +transition leaves publication unset. The replacement uses the current +subscription and elected reporter. Admission resolves registration, lifecycle and subscription again under its journal lock; a previously constructed hook is not current authority. diff --git a/loopx/capabilities/periodic_report/cadence_journal.py b/loopx/capabilities/periodic_report/cadence_journal.py index 1986cf4e9f..47838e0d19 100644 --- a/loopx/capabilities/periodic_report/cadence_journal.py +++ b/loopx/capabilities/periodic_report/cadence_journal.py @@ -21,6 +21,7 @@ CADENCE_WINDOW_SCHEMA = "periodic_report_cadence_window_v0" JOURNAL_SCHEMA = "periodic_report_cadence_journal_v0" +_ADMISSION_ARCHIVE_PREFIX = "cadence_admission_" def _digest(value: object) -> str: @@ -80,7 +81,7 @@ def _read_journal(path: Path, goal_id: str) -> dict[str, Any] | None: } if not isinstance(value, dict) or set(value) - {"supersedes", "retirement", "task_completion"} != fields or value["schema_version"] != JOURNAL_SCHEMA or value["goal_id"] != goal_id: raise ValueError("cadence journal contract is invalid") - if "supersedes" in value and not re.fullmatch(r"cadence_[0-9a-f]{64}", str(value["supersedes"])): + if "supersedes" in value and not re.fullmatch(r"cadence_(?:admission_)?[0-9a-f]{64}", str(value["supersedes"])): raise ValueError("cadence journal predecessor is invalid") window = validate_cadence_window(value["window"]) if window["goal_id"] != goal_id: @@ -174,8 +175,13 @@ def _retire_failed_cadence_window_locked(*, runtime_root: Path, goal_id: str, return current +def _admission_archive_id(entry: Mapping[str, object]) -> str: + # Returning to an earlier configuration can reuse its window ID. + return _ADMISSION_ARCHIVE_PREFIX + _digest(entry).removeprefix("sha256:") + + def _archive_predecessor(path: Path, previous: dict[str, Any]) -> str: - identity = previous["window"]["window_id"] + identity = _admission_archive_id(previous) archive = path.parent / "superseded-cadence" / (identity + ".json") if archive.exists(): if json.loads(archive.read_text(encoding="utf-8")) != previous: @@ -213,8 +219,15 @@ def missed_cadence_bounds(*, runtime_root: Path, window: dict[str, Any]) -> dict first_due_at = None while predecessor := current.get("supersedes"): previous = _read_journal(path.parent / "superseded-cadence" / (predecessor + ".json"), goal_id) - if not previous or previous["window"]["window_id"] != predecessor: + if previous is None: raise ValueError("cadence predecessor archive is unavailable") + identity = ( + _admission_archive_id(previous) + if predecessor.startswith(_ADMISSION_ARCHIVE_PREFIX) + else previous["window"]["window_id"] + ) + if identity != predecessor: + raise ValueError("cadence predecessor archive identity does not match its reference") if not (_missed_windows(previous, current["window"]) or _next_window_due(previous, current["window"])): break first_due_at = previous["window"]["due_at"] diff --git a/regression/PeriodicReportCadenceArchive.lean b/regression/PeriodicReportCadenceArchive.lean new file mode 100644 index 0000000000..7d98e0f5ef --- /dev/null +++ b/regression/PeriodicReportCadenceArchive.lean @@ -0,0 +1,137 @@ +import Std + +/- +Run with Lean 4.22.0 using +`lean -DwarningAsError=true regression/PeriodicReportCadenceArchive.lean`. + +The model starts with a valid, unprepared cadence window and serializes each +switch under the journal lock. `archivePredecessor` models the first durable +write. `replace` models the two writes in order. The full admission record in +Python also includes the Goal, retirement, and task-completion fields. + +`identify` abstracts the digest of the complete predecessor record. Retry +and preservation do not assume collision freedom. The liveness theorem +requires distinct retained records to have distinct keys. SHA-256 makes that +a practical assumption and the journal rejects a conflicting stored record. +The model assumes atomic file replacement and does not model the filesystem. +-/ + +namespace PeriodicReportCadenceArchive + +structure Admission (Key : Type) where + window : Nat + admittedAt : Nat + predecessor : Option Key + publication : Option Nat + deriving DecidableEq + +abbrev Archive (Key : Type) := Key → Option (Admission Key) + +variable {Key : Type} [DecidableEq Key] + +def archivePredecessor (identify : Admission Key → Key) (history : Archive Key) + (active : Admission Key) : Option (Archive Key) := + match history (identify active) with + | none => some (fun key => if key = identify active then some active else history key) + | some saved => if saved = active then some history else none + +def replace (identify : Admission Key → Key) (history : Archive Key) + (active : Admission Key) (window now : Nat) : Option (Archive Key × Admission Key) := do + let archived ← archivePredecessor identify history active + pure (archived, ⟨window, now, some (identify active), none⟩) + +theorem archive_readback (identify : Admission Key → Key) (before after : Archive Key) + (active : Admission Key) (saved : archivePredecessor identify before active = some after) : + after (identify active) = some active := by + cases lookup : before (identify active) with + | none => + simp [archivePredecessor, lookup] at saved + subst after + simp + | some entry => + by_cases same : entry = active + · simp [archivePredecessor, lookup, same] at saved + subst after + simpa [same] using lookup + · simp [archivePredecessor, lookup, same] at saved + +theorem archive_preserves (identify : Admission Key → Key) (before after : Archive Key) + (active old : Admission Key) (key : Key) + (retained : before key = some old) + (saved : archivePredecessor identify before active = some after) : + after key = some old := by + cases lookup : before (identify active) with + | none => + simp [archivePredecessor, lookup] at saved + subst after + have different : key ≠ identify active := by + intro equal + rw [equal, lookup] at retained + contradiction + simp [different, retained] + | some entry => + by_cases same : entry = active + · simp [archivePredecessor, lookup, same] at saved + subst after + exact retained + · simp [archivePredecessor, lookup, same] at saved + +theorem archive_conflict_refused (identify : Admission Key → Key) (history : Archive Key) + (active saved : Admission Key) (lookup : history (identify active) = some saved) + (different : saved ≠ active) : archivePredecessor identify history active = none := by + simp [archivePredecessor, lookup, different] + +theorem archive_total_when_keys_distinguish (identify : Admission Key → Key) + (history : Archive Key) (active : Admission Key) + (distinguish : ∀ saved, history (identify active) = some saved → saved = active) : + ∃ after, archivePredecessor identify history active = some after := by + cases lookup : history (identify active) with + | none => simp [archivePredecessor, lookup] + | some entry => simp [archivePredecessor, lookup, distinguish entry lookup] + +theorem restart_after_archive (identify : Admission Key → Key) (before after : Archive Key) + (active : Admission Key) (window now : Nat) + (saved : archivePredecessor identify before active = some after) : + replace identify after active window now = + some (after, ⟨window, now, some (identify active), none⟩) := by + simp [replace, archivePredecessor, archive_readback identify before after active saved] + +theorem replacement_retains_predecessor (identify : Admission Key → Key) + (before after : Archive Key) (active next : Admission Key) (window now : Nat) + (saved : replace identify before active window now = some (after, next)) : + after (identify active) = some active ∧ next.predecessor = some (identify active) ∧ + next.publication = none := by + cases replay : archivePredecessor identify before active with + | none => simp [replace, replay] at saved + | some archived => + simp [replace, replay] at saved + obtain ⟨rfl, rfl⟩ := saved + exact ⟨archive_readback identify before archived active replay, rfl, rfl⟩ + +private def switchBackAndForth (identify : Admission Nat → Nat) := do + let first : Admission Nat := ⟨0, 0, none, none⟩ + let (history, other) ← replace identify (fun _ => none) first 1 0 + let (history, sameWindow) ← replace identify history other 0 0 + replace identify history sameWindow 1 0 + +theorem old_window_key_conflicts : switchBackAndForth Admission.window = none := by rfl + +-- For this two-window example the record key also encodes the predecessor. +private def exampleKey (entry : Admission Nat) : Nat := + entry.window + 2 * entry.predecessor.getD 0 + 1 + +theorem four_admissions_keep_three_distinct_predecessors : + (switchBackAndForth exampleKey).map (fun (history, latest) => + (latest, history 1, history 4, history 9)) = + some (⟨1, 0, some 9, none⟩, some ⟨0, 0, none, none⟩, + some ⟨1, 0, some 1, none⟩, some ⟨0, 0, some 4, none⟩) := by rfl + +#print axioms archive_preserves +#print axioms archive_conflict_refused +#print axioms archive_total_when_keys_distinguish +#print axioms restart_after_archive +#print axioms replacement_retains_predecessor +#print axioms old_window_key_conflicts +#print axioms four_admissions_keep_three_distinct_predecessors + +end PeriodicReportCadenceArchive diff --git a/tests/capabilities/test_periodic_report_cadence_journal.py b/tests/capabilities/test_periodic_report_cadence_journal.py index 9741901fdc..eb3bfa167e 100644 --- a/tests/capabilities/test_periodic_report_cadence_journal.py +++ b/tests/capabilities/test_periodic_report_cadence_journal.py @@ -1,3 +1,4 @@ +import json from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from datetime import datetime @@ -6,6 +7,7 @@ from loopx.capabilities.periodic_report.cadence_journal import ( admit_cadence_window, + cadence_journal_path, cadence_intent, read_cadence_journal, validate_cadence_window, @@ -65,13 +67,16 @@ def test_cadence_is_eligible_without_a_fake_stage_or_user(tmp_path): def test_configuration_change_supersedes_only_unprepared_window(tmp_path): first = admit(tmp_path) + original = read_cadence_journal(runtime_root=tmp_path, goal_id="example") updated = {**config(), "effective_revision": "sha256:" + "b" * 64} second = admit(tmp_path, subscription=updated) assert second["status"] == "pending" assert second["window"]["window_id"] != first["window"]["window_id"] assert second["mutated"] is True persisted = read_cadence_journal(runtime_root=tmp_path, goal_id="example") - assert persisted["supersedes"] == first["window"]["window_id"] + journal = cadence_journal_path(tmp_path, "example") + predecessor = journal.parent / "superseded-cadence" / f"{persisted['supersedes']}.json" + assert json.loads(predecessor.read_text()) == original assert persisted["publication"] is None assert admit(tmp_path, subscription=updated)["mutated"] is False from loopx.capabilities.periodic_report.pending_intent import _attempt_dir diff --git a/tests/capabilities/test_periodic_report_pending_intent.py b/tests/capabilities/test_periodic_report_pending_intent.py index 7c2f0aaba4..c7b27a16b3 100644 --- a/tests/capabilities/test_periodic_report_pending_intent.py +++ b/tests/capabilities/test_periodic_report_pending_intent.py @@ -200,6 +200,37 @@ def test_calendar_hook_to_editorial_to_delivery_todo_preserves_window(tmp_path: assert read_cadence_journal(runtime_root=runtime, goal_id=GOAL_ID)["publication"]["publication_id"] == "fixture-verified-publication" +def test_calendar_route_can_switch_back_and_forth_in_one_window(tmp_path): + from datetime import datetime + from loopx.capabilities.periodic_report.cadence_journal import cadence_journal_path, read_cadence_journal + from loopx.capabilities.periodic_report.cadence_runtime import extend_cadence_turn_start_dispatch + from loopx.configure_goal import configure_goal + + registry, runtime = _calendar_fixture(tmp_path) + config = json.loads(registry.read_text())["goals"][0]["control_plane"]["periodic_report"] + journal_path = cadence_journal_path(runtime, GOAL_ID) + now = datetime.fromisoformat("2026-09-11T10:00:00Z") + documents = [] + for route in ("route-a", "route-b", "route-a", "route-b"): + configure_goal(registry_path=registry, goal_id=GOAL_ID, + periodic_report_configuration={**config, "route_ref": route}, execute=True) + dispatch = extend_cadence_turn_start_dispatch({}, registry_path=registry, runtime_root=runtime, + goal_id=GOAL_ID, agent_id=AGENT_ID, now=now) + assert dispatch["failures"] == [] + assert dispatch["results"][0]["agent_read_required"] is True + current = read_cadence_journal(runtime_root=runtime, goal_id=GOAL_ID) + if documents: + archive = journal_path.parent / "superseded-cadence" / f"{current['supersedes']}.json" + assert json.loads(archive.read_text()) == documents[-1] + documents.append(current) + + assert documents[0]["window"] == documents[2]["window"] + assert documents[1]["window"] == documents[3]["window"] + assert len({entry["admitted_at"] for entry in documents}) == 1 + assert len({entry["supersedes"] for entry in documents[1:]}) == 3 + assert all(entry["publication"] is None for entry in documents) + + @pytest.mark.parametrize("prepared", [False, True]) def test_calendar_reporter_replacement_uses_admitted_window_state(tmp_path, prepared): from datetime import datetime @@ -230,7 +261,8 @@ def test_calendar_reporter_replacement_uses_admitted_window_state(tmp_path, prep else: assert result["error_code"] is None assert result["agent_read_required"] is True - assert current["supersedes"] == original["window"]["window_id"] + archive = runtime / "goals" / GOAL_ID / "periodic_reports/superseded-cadence" / f"{current['supersedes']}.json" + assert json.loads(archive.read_text()) == original assert current["window"]["agent_id"] == "replacement-peer" assert current["publication"] is None diff --git a/tests/test_native_steward_reports.py b/tests/test_native_steward_reports.py index ef93bc8277..4c45e31d0d 100644 --- a/tests/test_native_steward_reports.py +++ b/tests/test_native_steward_reports.py @@ -1926,7 +1926,9 @@ def starts(): assert done["loopx_request"]["todo_id"] != original["loopx_request"]["todo_id"] assert done["loopx_request"]["report_window_id"] == latest["window_id"] assert "report_quota_recovery" not in done["loopx_request"] - assert json.loads((cadence.parent / "superseded-cadence" / (old["window_id"] + ".json")).read_text()) == previous + active = json.loads(cadence.read_text()) + predecessor = cadence.parent / "superseded-cadence" / f"{active['supersedes']}.json" + assert json.loads(predecessor.read_text()) == previous assert [path.read_bytes() for path in old_artifacts] == original_bytes assert failure_proof.read_bytes() == retained_bytes assert reports.delivery_current(owner, old) is False @@ -2329,9 +2331,10 @@ def starts(): assert reports.current_window(ctx["owner"])[1]["window_id"] == old["window_id"] -def test_consecutive_missed_windows_keep_the_first_unreported_deadline(tmp_path): +@pytest.mark.parametrize("previous_archive_uses_window_id", [False, True]) +def test_consecutive_missed_windows_keep_the_first_unreported_deadline(tmp_path, previous_archive_uses_window_id): from datetime import timezone - from loopx.capabilities.periodic_report.cadence_journal import admit_cadence_window, missed_cadence_bounds + from loopx.capabilities.periodic_report.cadence_journal import admit_cadence_window, cadence_journal_path, missed_cadence_bounds schedule = {"schema_version": "periodic_report_schedule_v0", "schedule_id": "daily-report", "timezone": "Asia/Shanghai", "rrule": "FREQ=DAILY;BYHOUR=9;BYMINUTE=0", "start_date": "2001-01-01"} @@ -2346,11 +2349,27 @@ def admit(day): first = admit(1) attempt_directory(tmp_path, first).mkdir(parents=True) middle = admit(3) + journal = cadence_journal_path(tmp_path, "example") + archives = journal.parent / "superseded-cadence" + if previous_archive_uses_window_id: + # The old writer named the predecessor file after its window. + active = json.loads(journal.read_text()) + (archives / f"{active['supersedes']}.json").rename(archives / f"{first['window_id']}.json") + active["supersedes"] = first["window_id"] + journal.write_text(json.dumps(active)) attempt_directory(tmp_path, middle).mkdir(parents=True) latest = admit(5) assert missed_cadence_bounds(runtime_root=tmp_path, window=latest) == { "first_due_at": "2026-01-01T01:00:00Z", "last_due_at": "2026-01-04T01:00:00Z"} + active = json.loads(journal.read_text()) + predecessor = archives / f"{active['supersedes']}.json" + archived = json.loads(predecessor.read_text()) + archived["admitted_at"] = "2026-01-03T03:01:00Z" + predecessor.write_text(json.dumps(archived)) + with pytest.raises(ValueError, match="archive identity does not match"): + missed_cadence_bounds(runtime_root=tmp_path, window=latest) + def test_distinct_due_daily_windows_keep_normal_native_replan_and_quota_rules(steward, tmp_path, monkeypatch): from datetime import timezone diff --git a/tests/test_steward_report_recovery_and_validator.py b/tests/test_steward_report_recovery_and_validator.py index d5d86b1d96..ab420f6301 100644 --- a/tests/test_steward_report_recovery_and_validator.py +++ b/tests/test_steward_report_recovery_and_validator.py @@ -908,7 +908,10 @@ def fake_turn(self, message, event_sink=None, **_kwargs): assert latest["due_at"] == old["next_due_at"] assert done["loopx_request"]["report_window_id"] == latest["window_id"] assert done["loopx_request"]["todo_id"] != old_todo_id - superseded = json.loads((reports.root / "goals" / actor["goal_id"] / "periodic_reports" / "superseded-cadence" / f"{old['window_id']}.json").read_text()) + latest_journal = read_cadence_journal(runtime_root=reports.root, goal_id=actor["goal_id"]) + archive_dir = reports.root / "goals" / actor["goal_id"] / "periodic_reports/superseded-cadence" + archive = archive_dir / f"{latest_journal['supersedes']}.json" + superseded = json.loads(archive.read_text()) assert superseded == previous_journal proof = json.loads((old_folder / REPORT_FAILURE_PROOF).read_text()) assert proof["adapter_kind"] == "antigravity_ls"