diff --git a/infra/systemd/check-continuation-snapshot.py b/infra/systemd/check-continuation-snapshot.py index 3185c93..d1dd2b6 100644 --- a/infra/systemd/check-continuation-snapshot.py +++ b/infra/systemd/check-continuation-snapshot.py @@ -38,7 +38,22 @@ def inspect_snapshot(path, root, now, max_age): projects=len(report["projects"])) -def remember(fact, path): +def confirm_queue_sample(fact, previous, progress, invocation): + """Replay the open incident until two distinct samples confirm the same recovery.""" + at = fact["occurred_at"] + last_seen = progress["seen_at"] if progress else previous["occurred_at"] + if datetime.fromisoformat(at) <= datetime.fromisoformat(last_seen): + return previous, progress + latest = {"seen_at": at} + if previous.get("status") == "failure" and fact["status"] == "success": + pending = progress.get("pending") if progress else None + if not pending or pending["invocation"] == invocation or pending["evidence"] != fact["evidence"]: + latest["pending"] = {"invocation": invocation, "observed_at": at, "evidence": fact["evidence"]} + return previous, latest + return fact, latest + + +def remember(fact, path, *, recovery_invocation=None): """Atomically retain the original event identity while the same evidence persists.""" with path.with_suffix(path.suffix + ".lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) @@ -46,13 +61,24 @@ def remember(fact, path): previous = json.loads(path.read_bytes()) except FileNotFoundError: previous = None - identity = ("event_type", "repository", "operation", "task_id", "failure_code", "status", "evidence") - if isinstance(previous, dict) and all(previous.get(key) == fact[key] for key in identity): - return previous + subject = ("event_type", "repository", "operation", "task_id", "failure_code") + same_subject = isinstance(previous, dict) and all(previous.get(k) == fact[k] for k in subject) + previous_progress = previous.pop("_queue_recovery", None) if isinstance(previous, dict) else None + progress = None + if recovery_invocation is not None: + if same_subject: + fact, progress = confirm_queue_sample(fact, previous, previous_progress, recovery_invocation) + else: + progress = {"seen_at": fact["occurred_at"]} + if same_subject and previous.get("status") == fact["status"] and previous.get("evidence") == fact["evidence"]: + fact = previous + if previous_progress == progress: + return previous + stored = dict(fact, _queue_recovery=progress) if progress is not None else fact with tempfile.NamedTemporaryFile(dir=path.parent, mode="w", delete=False) as tmp: name = Path(tmp.name) try: - json.dump(fact, tmp) + json.dump(stored, tmp) tmp.flush() os.fsync(tmp.fileno()) name.replace(path) @@ -94,7 +120,11 @@ def main(): cli.add_argument("--target", required=True, help="Stable check target in this workspace") cli.add_argument("--max-age-seconds", type=int) cli.add_argument("--last-observation", type=Path, help="Private state file for replay of unchanged evidence") + cli.add_argument("--confirm-queue-recovery", action="store_true", + help="Keep an incident open until two independent queue checks succeed") args = cli.parse_args() + if args.confirm_queue_recovery and (args.planfile_queue_url is None or args.last_observation is None): + cli.error("--confirm-queue-recovery requires --planfile-queue-url and --last-observation") if args.snapshot is not None: if args.root is None or args.max_age_seconds is None or args.max_age_seconds <= 0: cli.error("--snapshot requires --root and positive --max-age-seconds") @@ -117,7 +147,9 @@ def main(): "task_id": args.target, "failure_code": code, "failure_category": reason, "occurred_at": now.isoformat(), "source_event_id": f"{prefix}-{invocation}-{now.isoformat()}", "status": "success" if success else "failure", "summary": f"{label}: {reason}", "evidence": proof} - print(json.dumps(remember(fact, args.last_observation) if args.last_observation else fact)) + if args.last_observation: + fact = remember(fact, args.last_observation, recovery_invocation=invocation if args.confirm_queue_recovery else None) + print(json.dumps(fact)) if __name__ == "__main__": diff --git a/infra/systemd/test_continuation_queue_check.py b/infra/systemd/test_continuation_queue_check.py index 04072d5..e9edc9a 100644 --- a/infra/systemd/test_continuation_queue_check.py +++ b/infra/systemd/test_continuation_queue_check.py @@ -13,9 +13,9 @@ "scope": {"mode": "queue", "queue": "coding-agent", "state": "ready"}} -def sample(monkeypatch, capsys, tmp_path, response, url=URL): +def sample(monkeypatch, capsys, tmp_path, response, url=URL, *, confirm=False): monkeypatch.setattr(sys, "argv", [str(SCRIPT), "--planfile-queue-url", url, "--target", "central-coding-ready", - "--last-observation", str(tmp_path / "ready.json")]) + "--last-observation", str(tmp_path / "ready.json")] + (["--confirm-queue-recovery"] if confirm else [])) with patch("monag.autonomy_probes._http_probe", return_value=response): runpy.run_path(str(SCRIPT), run_name="__main__") return json.loads(capsys.readouterr().out) @@ -48,3 +48,40 @@ def test_unqualified_binding_cannot_recover_a_queue(monkeypatch, capsys, tmp_pat def test_failure_status_cannot_be_labeled_healthy_by_the_backend(monkeypatch, capsys, tmp_path): observation = sample(monkeypatch, capsys, tmp_path, (503, {"detail": "queue_ready"})) assert observation["status"] == "failure" and observation["evidence"]["http_status"] == 503 + +def test_flapping_queue_keeps_original_failure_until_two_independent_successes(monkeypatch, capsys, tmp_path): + failure = (503, {"detail": "ticket_index_stale"}) + success = (200, PAGE) + + def observe(invocation, response): + monkeypatch.setenv("INVOCATION_ID", invocation) + return sample(monkeypatch, capsys, tmp_path, response, confirm=True) + + # Start from a flat checkpoint created by the original producer. + opened = sample(monkeypatch, capsys, tmp_path, failure) + for invocation, response in [("a", success), ("a", success), ("b", failure), ("c", success), ("c", success)]: + assert observe(invocation, response) == opened + recovered = observe("d", success) + assert recovered["status"] == "success" + assert observe("e", success) == recovered + reopened = observe("f", failure) + assert reopened["status"] == "failure" + assert reopened["source_event_id"] != opened["source_event_id"] + + +def test_healthy_start_is_visible_without_waiting_for_a_second_sample(monkeypatch, capsys, tmp_path): + assert sample(monkeypatch, capsys, tmp_path, (200, PAGE), confirm=True)["status"] == "success" + +def test_older_success_does_not_confirm_a_newer_incident(tmp_path): + remember = runpy.run_path(str(SCRIPT))["remember"] + state = tmp_path / "ready.json" + def write(second, outcome): + at = f"2026-11-25T00:00:{second:02d}+00:00" + fact = {"event_type": "check.fact", "repository": "semcod/planfile", "operation": "ops.planfile-queue", + "task_id": "ready", "failure_code": "queue-not-ready", "status": outcome, + "evidence": {"queue": "coding-agent"}, "occurred_at": at, "source_event_id": f"sample-{second}"} + return remember(fact, state, recovery_invocation=f"invocation-{second}") + opened = write(10, "failure") + assert write(9, "success") == opened + assert write(11, "success") == opened + assert write(12, "success")["status"] == "success" diff --git a/project/TICKETS.md b/project/TICKETS.md index 890e253..cd0f25d 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -156,4 +156,5 @@ | **ticket-167** | [`README.md`](./ticket-167/README.md) | - | - | - | - | - | | **ticket-168** | [`README.md`](./ticket-168/README.md) | - | - | - | - | - | | **ticket-169** | [`README.md`](./ticket-169/README.md) | - | - | - | - | - | +| **ticket-170** | [`README.md`](./ticket-170/README.md) | - | - | - | - | - | diff --git a/project/ticket-170/README.md b/project/ticket-170/README.md new file mode 100644 index 0000000..81be990 --- /dev/null +++ b/project/ticket-170/README.md @@ -0,0 +1,36 @@ +# Ticket 170: PLF-29796 Require independent consecutive queue recovery samples + +- **ID**: ticket-170 +- **Owner**: unresolved:human +- **Status**: IN_PROGRESS +- **Workflow state**: EDIT +- **Created**: 2026-11-24 + +## Goal and scope + +To be completed from human-owned input. + +## Acceptance criteria + +- [ ] AC-01: Scope is approved by a human owner. + +## Tracking boundary + +This directory contains the minimal reviewed intent. Optional participant prose +and raw command logs are not required delivery output. + + +## Ticket Radar + +Initial planned-scope estimate; advisory only, not execution or merge approval. + +| Measure | Initial assessment | +| --- | --- | +| Impact score | 48/100 | +| Complexity | M | +| Estimated effort | 47 min | +| Planning budget | 30 min | +| Split recommended | yes | + +Diagnostics: RADAR-ACCEPTANCE-MISSING, RADAR-BUDGET-EXCEEDED. + diff --git a/project/ticket-170/intent.json b/project/ticket-170/intent.json new file mode 100644 index 0000000..6b8ec69 --- /dev/null +++ b/project/ticket-170/intent.json @@ -0,0 +1,25 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-170", + "summary": "PLF-29796 Require independent consecutive queue recovery samples", + "workstream": "infrastructure", + "classification": { + "kind": "BUG", + "priority": "P1", + "origin": "requested" + }, + "allowedPaths": [ + "project/ticket-170/**", + "TODO.md", + "project/TICKETS.md", + "infra/systemd/check-continuation-snapshot.py", + "infra/systemd/test_continuation_queue_check.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null +}