diff --git a/docs/architecture/tui.md b/docs/architecture/tui.md index 9c21810..00877be 100644 --- a/docs/architecture/tui.md +++ b/docs/architecture/tui.md @@ -120,6 +120,11 @@ scope stays equal to the room goal it was copied from. EVERY poll path is degrade-guarded (`_ROOM_POLL_ERRORS`/`_SESSION_POLL_ERRORS`/ `_JOB_POLL_ERRORS`) — an unguarded read escapes the interval callback and kills the app, so a store failure must show DEGRADED and keep the last good view. +One candidate that cannot be read is not a store failure: a `RoomError` from +that candidate's own row, artifact or round binding becomes its pane's text +("unreadable", never cached) while the room's other panes refresh. The +candidate cache key includes the round's binding (`RoomStore.round_room_id`), +so a round deleted or moved away after the candidate was shown is checked again. `JobStore.control` likewise converts everything to `JobError` (its callers catch only that): the manager can vanish between the poll and the keypress, taking the token file and leaving a truncated socket reply. diff --git a/src/syncmill/cli.py b/src/syncmill/cli.py index 68f2b29..049c430 100644 --- a/src/syncmill/cli.py +++ b/src/syncmill/cli.py @@ -3339,8 +3339,20 @@ def room_candidates(room_id: str, repo: Path) -> None: _, _, coordinator = _room_coordinator(repo) try: coordinator.store.get_room(room_id) + damaged = 0 for candidate in coordinator.store.list_candidates(room_id): - manifest = coordinator.store.load_candidate(candidate["id"]) + try: + manifest = coordinator.store.load_candidate(candidate["id"]) + except RoomError as exc: + # One unreadable candidate (its artifact, or its round + # binding) is reported on its own line; the rest still list, + # and the command fails at the end rather than passing silently. + damaged += 1 + echo( + f"{_shown(candidate['id'])} {_shown(candidate['member_id']):10} " + f"damaged: {_shown(str(exc))}" + ) + continue # The read model's verdict: a candidate that never completed is # "not run", and a null gate is "no gate report" — never one `n/a`. gate = _gate_verdict( @@ -3357,6 +3369,10 @@ def room_candidates(room_id: str, repo: Path) -> None: f"patch:{_shown(manifest['patch_bytes'])}B" + (f" {usage}" if usage else "") ) + if damaged: + raise click.ClickException( + f"{damaged} candidate(s) in room {_shown(room_id)} could not be read" + ) # A pager/`head` exiting early raises BrokenPipeError (an OSError) out of # click.echo — re-raise it so Click's own EPIPE handling silences it, # instead of printing a spurious "Error: Broken pipe". diff --git a/src/syncmill/room_compare.py b/src/syncmill/room_compare.py index 6140f9d..fb19079 100644 --- a/src/syncmill/room_compare.py +++ b/src/syncmill/room_compare.py @@ -1078,6 +1078,19 @@ def build_room_comparison( for candidate in store.list_candidates(room_id): by_round.setdefault(str(candidate["round_id"]), []).append(candidate) candidate_rows[str(candidate["id"])] = candidate + # A candidate whose round is not one of this room's (gone, or another + # room's) belongs to no round group; say so rather than let it vanish. + room_round_ids = {str(round_row.get("id")) for round_row in rounds} + for candidate in candidate_rows.values(): + if str(candidate["round_id"]) not in room_round_ids: + damaged.append( + { + "round_id": str(candidate["round_id"]), + "reason": ( + f"candidate {candidate['id']} names a round outside this room" + ), + } + ) members = room.get("members") member_ids = ( [m["member_id"] for m in members if isinstance(m, dict) and "member_id" in m] diff --git a/src/syncmill/rooms.py b/src/syncmill/rooms.py index 3bb927d..c7cb147 100644 --- a/src/syncmill/rooms.py +++ b/src/syncmill/rooms.py @@ -1444,22 +1444,9 @@ def malformed(reason: str) -> ProvenanceCheck: if set(tree) != {"kind"}: return malformed("provenance tree keys are not the v1 set") elif kind == "branch": - if set(tree) != {"kind", "base_candidate_id", "base_patch_sha256", "base_round_number"}: - return malformed("provenance tree keys are not the v1 set") - base_id = tree["base_candidate_id"] - base = candidates.get(base_id) if isinstance(base_id, str) else None - if base is None: - return malformed("branch base candidate is not a candidate of this room") - base_round = tree["base_round_number"] - if not _plain_int(base_round) or base_round != base.get("round_number"): - return malformed("branch base round differs from the candidate's") - if base_round >= round_number: - return malformed("branch base is not from an earlier round") - if not base.get("eligible"): - return malformed("branch base candidate is not eligible") - digest = tree["base_patch_sha256"] - if not _sha256_hex(digest) or digest != base.get("patch_sha256"): - return malformed("branch base digest differs from the candidate's") + reason = _branch_tree_problem(tree, round_number, candidates) + if reason is not None: + return malformed(reason) elif kind == "repair": reason = _repair_tree_problem(tree, round_number, member_ids, candidates) if reason is not None: @@ -1496,42 +1483,121 @@ def malformed(reason: str) -> ProvenanceCheck: return ProvenanceCheck("recorded", record=record) -def _repair_tree_problem( +def _branch_tree_problem( tree: dict[str, Any], round_number: int, + candidates: dict[str, dict[str, Any]], +) -> str | None: + """Why a branch tree cannot be believed, or ``None``: its base must be an + eligible candidate of this room from an earlier round, with the recorded + number and digest. ``run_round`` checks a proposed tree with this before + it removes any workspace, so it never starts what this would reject.""" + if set(tree) != {"kind", "base_candidate_id", "base_patch_sha256", "base_round_number"}: + return "provenance tree keys are not the v1 set" + base_id = tree["base_candidate_id"] + base = candidates.get(base_id) if isinstance(base_id, str) else None + if base is None: + return "branch base candidate is not a candidate of this room" + base_round = tree["base_round_number"] + if not _plain_int(base_round) or base_round != base.get("round_number"): + return "branch base round differs from the candidate's" + if base_round >= round_number: + return "branch base is not from an earlier round" + if not base.get("eligible"): + return "branch base candidate is not eligible" + digest = tree["base_patch_sha256"] + if not _sha256_hex(digest) or digest != base.get("patch_sha256"): + return "branch base digest differs from the candidate's" + return None + + +def _newer_completed( + candidates: dict[str, dict[str, Any]], + member_id: str, + *, + after: int, + before: int, +) -> list[dict[str, Any]] | None: + """The member's completed candidates from rounds after ``after`` and before + ``before``, or ``None`` when one of its completed candidates has no + recorded round (the order is then unknown). The one definition of "a newer + completed candidate" for the repair guard and the repair record validator. + """ + newer = [] + for row in candidates.values(): + if row.get("member_id") != member_id or row.get("state") != "completed": + continue + number = row.get("round_number") + if not _plain_int(number): + return None + if after < number < before: + newer.append(row) + return newer + + +def _repair_parent_tree_problem( + *, + member_id: object, + parent_id: object, + parent_round: object, + parent_patch_sha256: object, + round_number: int, member_ids: list[str], candidates: dict[str, dict[str, Any]], ) -> str | None: - """Why a repair tree cannot be believed, or ``None``. It must name a member - of the room and that member's newest completed candidate as of this round.""" - if set(tree) != _REPAIR_TREE_KEYS: - return "provenance tree keys are not the v3 repair set" - member_id = tree["member_id"] + """Why a repair parent cannot be believed for round ``round_number``, or + ``None``: it must be a completed candidate of a room member, from an + earlier round, with the recorded number and digest, and that member's + newest completed candidate. A completed candidate of the member whose + round is not recorded makes the order unknown, so nothing can be its + newest. The record validator and the repair guard both decide with this. + """ if not isinstance(member_id, str) or member_id not in member_ids: return "repair member is not a member of this room" - parent_id = tree["parent_candidate_id"] parent = candidates.get(parent_id) if isinstance(parent_id, str) else None if parent is None or parent.get("member_id") != member_id: return "repair parent is not that member's candidate" if parent.get("state") != "completed": return "repair parent is not a completed candidate" - parent_round = tree["parent_round_number"] if not _plain_int(parent_round) or parent_round != parent.get("round_number"): return "repair parent round differs from the candidate's" if parent_round >= round_number: return "repair parent is not from an earlier round" - digest = tree["parent_patch_sha256"] - if not _sha256_hex(digest) or digest != parent.get("patch_sha256"): + if not _sha256_hex(parent_patch_sha256) or parent_patch_sha256 != parent.get( + "patch_sha256" + ): return "repair parent digest differs from the candidate's" - for row in candidates.values(): - number = row.get("round_number") - if ( - row.get("member_id") == member_id - and row.get("state") == "completed" - and _plain_int(number) - and parent_round < number < round_number - ): - return "repair parent is not that member's newest completed candidate" + newer = _newer_completed( + candidates, member_id, after=parent_round, before=round_number + ) + if newer is None: + return "repair parent's order among that member's candidates is unknown" + if newer: + return "repair parent is not that member's newest completed candidate" + return None + + +def _repair_tree_problem( + tree: dict[str, Any], + round_number: int, + member_ids: list[str], + candidates: dict[str, dict[str, Any]], +) -> str | None: + """Why a repair tree cannot be believed, or ``None``. It must name a member + of the room and that member's newest completed candidate as of this round.""" + if set(tree) != _REPAIR_TREE_KEYS: + return "provenance tree keys are not the v3 repair set" + reason = _repair_parent_tree_problem( + member_id=tree["member_id"], + parent_id=tree["parent_candidate_id"], + parent_round=tree["parent_round_number"], + parent_patch_sha256=tree["parent_patch_sha256"], + round_number=round_number, + member_ids=member_ids, + candidates=candidates, + ) + if reason is not None: + return reason feedback = tree["feedback_ids"] if not isinstance(feedback, list) or not all(_canonical_uuid(f) for f in feedback): return "repair feedback ids are not canonical uuids" @@ -2677,20 +2743,30 @@ def _repair_parent_problem( number = parent["round_number"] if not _plain_int(number): return "candidate's round is not recorded" - newer = [ - value - for value in rows.values() - if value["member_id"] == parent["member_id"] - and value["state"] == "completed" - and _plain_int(value["round_number"]) - and value["round_number"] > number - ] + next_round = int(room["round_count"]) + 1 + newer = _newer_completed( + rows, parent["member_id"], after=number, before=next_round + ) if newer: newest = max(newer, key=lambda value: value["round_number"]) return ( f"candidate {newest['id']} is its member's newer completed candidate; " "repair that one, or use `room round --lineage branch-from` for this one" ) + # The rule the round's provenance record will be validated by, on the + # record this repair would write: whatever the checks above let + # through, the guard never starts a repair that record would reject. + problem = _repair_parent_tree_problem( + member_id=parent["member_id"], + parent_id=candidate_id, + parent_round=number, + parent_patch_sha256=parent["patch_sha256"], + round_number=next_round, + member_ids=[m["member_id"] for m in json.loads(room["members_json"])], + candidates=rows, + ) + if problem is not None: + return problem workspace = conn.execute( "SELECT base_commit FROM room_workspaces WHERE room_id=? AND member_id=?", (room["id"], parent["member_id"]), @@ -3409,10 +3485,14 @@ def list_candidates(self, room_id: str) -> list[dict[str, Any]]: @staticmethod def _list_candidates(conn: sqlite3.Connection, room_id: str) -> list[dict[str, Any]]: # round_number rides along so callers (the resume-aware delta prefix) - # can filter by round without a per-candidate get_round query. + # can filter by round without a per-candidate get_round query. It is + # NULL when the candidate's round is not a round of this room (gone, + # or another room's): the candidate stays listed, and every reader + # that orders by round treats it as a round that is not recorded, + # never as another round's number. rows = conn.execute( """SELECT c.*, r.number AS round_number FROM candidates c - JOIN rounds r ON r.id = c.round_id + LEFT JOIN rounds r ON r.id = c.round_id AND r.room_id = c.room_id WHERE c.room_id=? ORDER BY c.created_at,c.attempt""", (room_id,), ).fetchall() @@ -3429,6 +3509,13 @@ def _candidate_rows( def candidate_rows(self, room_id: str) -> dict[str, dict[str, Any]]: return self._candidate_rows(self._conn, room_id) + def round_room_id(self, round_id: object) -> str | None: + """The room a round belongs to, or ``None`` when there is no such round.""" + row = self._conn.execute( + "SELECT room_id FROM rounds WHERE id=?", (round_id,) + ).fetchone() + return None if row is None else row["room_id"] + def get_candidate(self, candidate_id: str) -> dict[str, Any]: row = self._conn.execute( "SELECT * FROM candidates WHERE id=?", (candidate_id,) @@ -3643,6 +3730,11 @@ def _candidate_location(self, candidate_id: str) -> tuple[dict[str, Any], Path]: ).resolve() if Path(row["artifact_path"]).resolve() != expected_path: raise RoomError(f"candidate artifact path mismatch: {candidate_id}") + # The manifest binds the candidate to its row; this binds the row to + # a round of the same room. A round that is gone or belongs to another + # room leaves the candidate with no round to stand in. + if self.round_room_id(row["round_id"]) != row["room_id"]: + raise RoomError(f"candidate round binding mismatch: {candidate_id}") return row, expected_path def _validate_candidate_bindings( @@ -4823,6 +4915,9 @@ def preflight_round( if row["room_id"] != room_id or not row["eligible"]: raise RoomError("base candidate must be eligible and belong to the room") self.store.load_candidate(str(base_candidate_id)) + self._branch_tree( + room_id, str(base_candidate_id), int(room["round_count"]) + 1 + ) round_prompt = prompt or room["prompt"] _validate_prompt_text(round_prompt) # A fork that cannot actually resume a conversation would silently run @@ -5036,6 +5131,26 @@ def build_repair_plan( ), ) + def _branch_tree( + self, room_id: str, base_candidate_id: str, round_number: int + ) -> dict[str, Any]: + """The provenance tree a branch-from round records, checked with the + validator that will read it; ``RoomError`` when it would be rejected.""" + rows = self.store.candidate_rows(room_id) + base = rows.get(base_candidate_id) + if base is None: + raise RoomError("base candidate must be eligible and belong to the room") + tree = { + "kind": "branch", + "base_candidate_id": base_candidate_id, + "base_patch_sha256": base["patch_sha256"], + "base_round_number": base["round_number"], + } + problem = _branch_tree_problem(tree, round_number, rows) + if problem is not None: + raise RoomError(f"cannot branch from {base_candidate_id}: {problem}") + return tree + def _continued_parents(self, room: dict[str, Any]) -> dict[str, dict[str, Any] | None]: """Each member's candidate in the previous round: the attempt whose retained worktree a continue-own round continues. ``None`` when that @@ -5240,13 +5355,11 @@ def owned() -> None: if row["room_id"] != room_id or not row["eligible"]: raise RoomError("base candidate must be eligible and belong to the room") seed_patch = self.store.load_candidate(str(base_candidate_id))["patch"] - base_row = self.store.candidate_rows(room_id)[str(base_candidate_id)] - tree = { - "kind": "branch", - "base_candidate_id": str(base_candidate_id), - "base_patch_sha256": base_row["patch_sha256"], - "base_round_number": base_row["round_number"], - } + # Before _cleanup_workspaces: a base the round's record would + # reject must leave the existing workspaces in place. + tree = self._branch_tree( + room_id, str(base_candidate_id), int(room["round_count"]) + 1 + ) if existing: self._cleanup_workspaces(room_id) # The records (and their run roots) are gone — refresh so no @@ -5312,7 +5425,7 @@ def owned() -> None: # never erase the accepted round's sessions. `fresh` clears too, not # just `--fresh-session`: leaving the ids behind lets a cold attempt # that reports no new session resurrect the PRE-fresh conversation - # on the next continue-own round, while `last_round_by_member` has + # on the next continue-own round, while the delta watermark has # already advanced — a delta prompt against a session that never saw # those rounds. A successful cold turn repopulates them below. if fresh_session or lineage == "fresh": @@ -5374,18 +5487,14 @@ def owned() -> None: # before its last round's prompt was built — re-sending them is pure # uncached input. Its delta is peers' outputs from its last round # onward, minus its own candidates. A cold member (no seeded - # session) still gets the full checkpoint. - last_round_by_member: dict[str, int] = {} - for row in self.store.list_candidates(room_id): - number = row.get("round_number") - # COMPLETED turns only: a failed/timed-out member never - # consumed that round's prompt, but its stored session id - # survives — advancing the watermark would make the next - # resume omit peer outputs its conversation never received. - if isinstance(number, int) and row.get("state") == "completed": - last_round_by_member[row["member_id"]] = max( - last_round_by_member.get(row["member_id"], 0), number - ) + # session) still gets the full checkpoint. The watermark is the + # member's last round with a COMPLETED candidate (a failed or + # timed-out member never consumed that round's prompt, but its + # stored session id survives — advancing the watermark would make + # the next resume omit peer outputs its conversation never + # received), read with the function the record is validated by. + round_number = int(round_row["number"]) + candidate_rows = self.store.candidate_rows(room_id) # Shared-memory context is member-independent — search once per # round, strictly BEFORE the fan-out (the shared-loop rule), and # apply it only to the AGENT prompts (the stored rounds.prompt row @@ -5408,19 +5517,25 @@ def owned() -> None: conversation: dict[str, dict[str, Any]] = {} for member in members: member_id = member["member_id"] - last_seen = last_round_by_member.get(member_id) + last_seen = last_completed_round( + candidate_rows, member_id, before=round_number + ) seeded = bool(seed_sessions.get(member_id)) if seeded and last_seen is not None: agent_prompt, included, omitted = self._checkpoint( room_id, round_task, + round_number=round_number, exclude_member=member_id, min_round_number=last_seen, lessons=delivered_lessons, ) else: agent_prompt, included, omitted = self._checkpoint( - room_id, round_task, lessons=delivered_lessons + room_id, + round_task, + round_number=round_number, + lessons=delivered_lessons, ) composed, delivered = self._memory_prefixed(memory_context, agent_prompt) # Final-argv guarantee: the checkpoint embeds candidate OUTPUTS @@ -5700,6 +5815,7 @@ def _prompt_with_checkpoint( room_id: str, prompt: str, *, + round_number: int, exclude_member: str | None = None, min_round_number: int | None = None, lessons: list[str] | tuple[str, ...] = (), @@ -5707,6 +5823,7 @@ def _prompt_with_checkpoint( return self._checkpoint( room_id, prompt, + round_number=round_number, exclude_member=exclude_member, min_round_number=min_round_number, lessons=lessons, @@ -5717,6 +5834,7 @@ def _checkpoint( room_id: str, prompt: str, *, + round_number: int, exclude_member: str | None = None, min_round_number: int | None = None, lessons: list[str] | tuple[str, ...] = (), @@ -5735,6 +5853,11 @@ def _checkpoint( before that round's prompt was built has been seen; its peers' outputs FROM that round onward are the genuinely new information). + ``round_number`` is the round being built. The candidates come from + :func:`checkpoint_eligible`, the function the conversation record is + validated with, so the record this prompt produces always lists + exactly the candidates its validator expects. + ``lessons`` are approved lesson texts that already fit beside the prompt (:func:`round_lessons_fit`). They go after the excerpts, with the task, and the excerpts are budgeted around them; every fallback @@ -5743,20 +5866,18 @@ def _checkpoint( prompt_bytes = prompt.encode("utf-8", errors="surrogateescape") if len(prompt_bytes) > _ROOM_PROMPT_MAX_BYTES: raise RoomError("room prompt exceeds the safe process argument byte limit") - candidates = [ - row - for row in self.store.list_candidates(room_id) - if (exclude_member is None or row["member_id"] != exclude_member) - and ( - min_round_number is None - or ( - isinstance(row.get("round_number"), int) - and row["round_number"] >= min_round_number - ) + rows = {row["id"]: row for row in self.store.list_candidates(room_id)} + ordered = [ + rows[candidate_id] + for candidate_id in checkpoint_eligible( + rows, + round_number=round_number, + exclude_member=exclude_member, + min_round_number=min_round_number, ) ] bare = _bare_prompt(prompt, lessons) - if not candidates: + if not ordered: return bare, [], False preamble = _CHECKPOINT_PREAMBLE_WITH_LESSONS if lessons else _CHECKPOINT_PREAMBLE suffix = f"\n\n{_task_section(prompt, lessons)}" @@ -5766,10 +5887,6 @@ def _checkpoint( # would cross the argv boundary. return bare, [], True - ordered = sorted( - candidates, - key=lambda value: (value["created_at"], value["member_id"], value["id"]), - ) available = _ROOM_PROMPT_MAX_BYTES - len(fixed_bytes) separator = b"\n\n" marker = _CHECKPOINT_TRUNCATION_MARKER.encode() diff --git a/src/syncmill/tui.py b/src/syncmill/tui.py index 01cf969..d778a0f 100644 --- a/src/syncmill/tui.py +++ b/src/syncmill/tui.py @@ -308,6 +308,14 @@ def _read_artifact_result(run_id: str, *, store: ArtifactStore) -> dict | None: return value +def _unreadable_candidate(candidate_id: str, exc: Exception) -> str: + """The candidate pane for a candidate that cannot be read.""" + return ( + f"Candidate {printable_name(candidate_id)} unreadable: " + f"{printable_name(str(exc))}" + ) + + def _one_line(value: object) -> str: """A stored value in a one-line field, as the CLI shows it.""" return printable_name(str(value)) @@ -2700,11 +2708,22 @@ def _stage_candidate( ) assert candidate_id is not None reset = view is None - row = self._rooms.store.get_candidate(candidate_id) + # A RoomError from reading the candidate itself (its row, artifact or + # round binding) is that candidate's damage: it is staged as this + # pane's text, so the room's other panes still refresh. Store failures + # (sqlite3.Error and the rest) still raise and degrade the whole room. + # The unreadable text is never cached (key None): a view change or a + # repair is read again on the next stage. + try: + row = self._rooms.store.get_candidate(candidate_id) + except RoomError as exc: + return None, _unreadable_candidate(candidate_id, exc), view or "output", pages, False if view is None: view = "diff" if row.get("state") == "completed" else "output" # Candidates are immutable (digest-bound), so this key makes a - # poll tick a no-op instead of re-streaming the patch. + # poll tick a no-op instead of re-streaming the patch. The round's + # binding is part of it: a round deleted or moved to another room + # after the candidate was shown must be validated again. key = ( candidate_id, view, @@ -2712,14 +2731,24 @@ def _stage_candidate( row.get("patch_sha256"), row.get("output_sha256"), row.get("state"), + row.get("round_id"), + self._rooms.store.round_room_id(row.get("round_id")), ) truncated = False if reset else self._diff_truncated if key == self._candidate_detail_key: return key, None, view, pages, truncated + try: + if view == "diff": + manifest = self._rooms.store.load_candidate_patch_head( + candidate_id, pages * _DIFF_DISPLAY_BYTES + ) + else: + manifest = self._rooms.store.load_candidate_checkpoint( + candidate_id, _CANDIDATE_OUTPUT_BYTES + ) + except RoomError as exc: + return None, _unreadable_candidate(candidate_id, exc), view, pages, False if view == "diff": - manifest = self._rooms.store.load_candidate_patch_head( - candidate_id, pages * _DIFF_DISPLAY_BYTES - ) truncated = bool(manifest["patch_truncated"]) text = render_candidate_diff( manifest, @@ -2728,9 +2757,6 @@ def _stage_candidate( binary=manifest.get("patch_binary"), ) else: - manifest = self._rooms.store.load_candidate_checkpoint( - candidate_id, _CANDIDATE_OUTPUT_BYTES - ) text = render_candidate_output(manifest) return key, text, view, pages, truncated diff --git a/tests/test_room_lessons.py b/tests/test_room_lessons.py index ebdcb74..1e963d5 100644 --- a/tests/test_room_lessons.py +++ b/tests/test_room_lessons.py @@ -73,8 +73,8 @@ def frozen(git_repo, tmp_path, monkeypatch): def test_lessons_sit_after_the_untrusted_checkpoint_next_to_the_task(frozen): coordinator, room_id = frozen - prompt, included, omitted = coordinator._checkpoint(room_id, "next", lessons=TEXTS) - plain, plain_included, _ = coordinator._checkpoint(room_id, "next") + prompt, included, omitted = coordinator._checkpoint(room_id, "next", round_number=3, lessons=TEXTS) + plain, plain_included, _ = coordinator._checkpoint(room_id, "next", round_number=3) assert included == plain_included and not omitted assert prompt.startswith(rooms_module._CHECKPOINT_PREAMBLE_WITH_LESSONS) assert "Continue to follow only the task" not in prompt @@ -91,19 +91,19 @@ def test_lessons_sit_after_the_untrusted_checkpoint_next_to_the_task(frozen): def test_without_candidates_the_lessons_still_lead_the_task(frozen): coordinator, room_id = frozen prompt, included, omitted = coordinator._checkpoint( - room_id, "next", min_round_number=9, lessons=TEXTS + room_id, "next", round_number=3, min_round_number=9, lessons=TEXTS ) assert (prompt, included, omitted) == (TAIL, [], False) - assert coordinator._checkpoint(room_id, "next", min_round_number=9) == ("next", [], False) + assert coordinator._checkpoint(room_id, "next", round_number=3, min_round_number=9) == ("next", [], False) def test_the_checkpoint_makes_room_for_the_lessons(frozen, monkeypatch): coordinator, room_id = frozen - full, every, _ = coordinator._checkpoint(room_id, "next") + full, every, _ = coordinator._checkpoint(room_id, "next", round_number=3) # Room for the whole checkpoint, not for the checkpoint plus the lessons. cap = len(full.encode()) + 10 monkeypatch.setattr(rooms_module, "_ROOM_PROMPT_MAX_BYTES", cap) - prompt, included, omitted = coordinator._checkpoint(room_id, "next", lessons=TEXTS) + prompt, included, omitted = coordinator._checkpoint(room_id, "next", round_number=3, lessons=TEXTS) assert omitted and included == every[len(every) - len(included):] assert len(included) < len(every) assert len(prompt.encode()) <= cap @@ -113,10 +113,10 @@ def test_the_checkpoint_makes_room_for_the_lessons(frozen, monkeypatch): def test_multibyte_lessons_are_budgeted_in_bytes(frozen, monkeypatch): coordinator, room_id = frozen korean = ["작은 diff를 선호한다 " * 40, "벤더 코드는 고치지 않는다 " * 40] - full, _, _ = coordinator._checkpoint(room_id, "next") + full, _, _ = coordinator._checkpoint(room_id, "next", round_number=3) cap = len(full.encode()) + 10 monkeypatch.setattr(rooms_module, "_ROOM_PROMPT_MAX_BYTES", cap) - prompt, _, omitted = coordinator._checkpoint(room_id, "next", lessons=korean) + prompt, _, omitted = coordinator._checkpoint(room_id, "next", round_number=3, lessons=korean) assert omitted assert len(prompt.encode()) <= cap # a character count would overshoot assert prompt.endswith("--- CURRENT USER TASK ---\nnext") @@ -143,7 +143,7 @@ def test_every_excerpt_fallback_keeps_the_lessons_and_the_task(frozen, monkeypat ) with patch("_ROOM_PROMPT_MAX_BYTES", cap), patch("_prompt_arg_units", units): assert round_lessons_fit("next", TEXTS) - prompt, included, omitted = coordinator._checkpoint(room_id, "next", lessons=TEXTS) + prompt, included, omitted = coordinator._checkpoint(room_id, "next", round_number=3, lessons=TEXTS) # The excerpts are dropped together with their ids; eligible ones existed. assert (prompt, included, omitted) == (TAIL, [], True) diff --git a/tests/test_room_round_binding.py b/tests/test_room_round_binding.py new file mode 100644 index 0000000..1d67ee9 --- /dev/null +++ b/tests/test_room_round_binding.py @@ -0,0 +1,349 @@ +"""A candidate is read with its own room's round, or with no round at all. + +A candidate row whose ``round_id`` names a round that is gone, belongs to +another room, or was renumbered must never lend a borrowed number to the +readers that order candidates by round. These tests damage a real store the +way a direct ``rooms.db`` edit would. +""" + +from __future__ import annotations + +import uuid +from pathlib import Path + +import pytest + +from syncmill.room_compare import build_room_comparison +from syncmill.rooms import ( + RoomCoordinator, + RoomError, + _repair_tree_problem, + round_conversation_status, +) +from test_rooms import SessionAgent, WritingAgent, _config + + +def _sql(coordinator: RoomCoordinator, statement: str, *params) -> None: + conn = coordinator.store._conn + conn.execute("PRAGMA foreign_keys=OFF") + conn.execute(statement, params) + conn.commit() + + +def _candidates(coordinator, room_id, member_id): + """The member's candidates, oldest first.""" + return [ + row + for row in coordinator.store.list_candidates(room_id) + if row["member_id"] == member_id + ] + + +def _round_id(coordinator, room_id, number): + return next( + r["id"] for r in coordinator.store.list_rounds(room_id) if r["number"] == number + ) + + +@pytest.fixture +def coordinator(git_repo, tmp_path): + made = RoomCoordinator( + _config(tmp_path), git_repo, agents=[WritingAgent("claude"), WritingAgent("codex")] + ) + yield made + made.close() + + +# ------------------------------------------------------------- read model + + +def test_a_candidate_never_borrows_another_rooms_round_number(coordinator): + """The issue's reproduction: room A's candidate pointed at room B's round 2.""" + room_a = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room_a, "one") + (candidate,) = _candidates(coordinator, room_a, "claude") + assert candidate["round_number"] == 1 + coordinator.close_room(room_a) + room_b = coordinator.create("b", ["claude"])["id"] + coordinator.run_round(room_b, "one") + coordinator.run_round(room_b, "two") + _sql( + coordinator, + "UPDATE candidates SET round_id=?, attempt=99 WHERE id=?", + _round_id(coordinator, room_b, 2), + candidate["id"], + ) + + rows = coordinator.store.candidate_rows(room_a) + assert rows[candidate["id"]]["round_number"] is None + assert candidate["id"] not in coordinator.store.candidate_rows(room_b) + with pytest.raises(RoomError): + coordinator.store.load_candidate(candidate["id"]) + + +def test_a_candidate_of_a_vanished_round_stays_listed_without_a_number(coordinator): + room = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room, "one") + (candidate,) = _candidates(coordinator, room, "claude") + _sql( + coordinator, + "UPDATE candidates SET round_id=? WHERE id=?", + str(uuid.uuid4()), + candidate["id"], + ) + rows = coordinator.store.candidate_rows(room) + assert rows[candidate["id"]]["round_number"] is None + + +@pytest.mark.parametrize("damage", ["moved", "deleted"]) +def test_the_artifact_refuses_a_candidate_whose_round_left_the_room(coordinator, damage): + """The manifest still matches the candidate row; the round does not.""" + room = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room, "one") + (candidate,) = _candidates(coordinator, room, "claude") + coordinator.store.load_candidate(candidate["id"]) # readable before + round_id = _round_id(coordinator, room, 1) + if damage == "moved": + _sql(coordinator, "UPDATE rounds SET room_id='elsewhere' WHERE id=?", round_id) + else: + _sql(coordinator, "DELETE FROM rounds WHERE id=?", round_id) + with pytest.raises(RoomError, match="round binding mismatch"): + coordinator.store.load_candidate(candidate["id"]) + with pytest.raises(RoomError): + coordinator.select(room, candidate["id"]) + + +# ---------------------------------------------------- generator == validator + + +def _round_ran_cleanly(coordinator, room_id, number): + room = coordinator.store.get_room(room_id) + assert room["state"] == "awaiting_decision", room.get("recovery_path") + round_row = next( + r for r in coordinator.store.list_rounds(room_id) if r["number"] == number + ) + check = round_conversation_status( + round_row["conversation_json"], + round_number=number, + members=room["members"], + candidates=coordinator.store.candidate_rows(room_id), + ) + assert check.status == "recorded", check.reason + + +@pytest.mark.parametrize("damage", ["dangling", "renumbered"]) +def test_a_cold_round_runs_beside_a_damaged_candidate(coordinator, damage): + """The checkpoint used to include a candidate its validator excluded; the + round then froze as recovery_required before any provider ran.""" + room = coordinator.create("a", ["claude", "codex"])["id"] + coordinator.run_round(room, "one") + if damage == "dangling": + (candidate,) = _candidates(coordinator, room, "codex") + _sql( + coordinator, + "UPDATE candidates SET round_id=? WHERE id=?", + str(uuid.uuid4()), + candidate["id"], + ) + else: + # Round 1 now claims to be round 100; the next round is still 2. + _sql(coordinator, "UPDATE rounds SET number=100 WHERE id=?", _round_id(coordinator, room, 1)) + coordinator.run_round(room, "two") + _round_ran_cleanly(coordinator, room, 2) + + +def test_a_resumed_round_ignores_a_round_numbered_past_it(git_repo, tmp_path): + """The delta watermark used to take any completed round's number; a round + renumbered to 100 made it 100, which the record's validator rejected.""" + made = RoomCoordinator( + _config(tmp_path), git_repo, agents=[SessionAgent("claude"), SessionAgent("codex")] + ) + try: + room = made.create("a", ["claude", "codex"])["id"] + made.run_round(room, "one") + made.run_round(room, "two") + _sql(made, "UPDATE rounds SET number=100 WHERE id=?", _round_id(made, room, 2)) + made.run_round(room, "three") + _round_ran_cleanly(made, room, 3) + finally: + made.close() + + +# ------------------------------------------------------------- repair + + +def test_repair_refuses_when_the_members_order_is_unknown(coordinator): + room = coordinator.create("a", ["claude", "codex"])["id"] + coordinator.run_round(room, "one") + coordinator.run_round(room, "two") + older, newer = _candidates(coordinator, room, "claude") + codex_newest = _candidates(coordinator, room, "codex")[-1] + _sql( + coordinator, + "UPDATE candidates SET round_id=? WHERE id=?", + str(uuid.uuid4()), + newer["id"], + ) + problem = coordinator.store.repair_parent_problem(room, older["id"]) + assert problem is not None and "order" in problem + assert coordinator.store.repair_parent_problem(room, newer["id"]) is not None + # The other member's order is intact. + assert coordinator.store.repair_parent_problem(room, codex_newest["id"]) is None + + +def test_repair_refuses_a_parent_numbered_past_the_next_round(coordinator): + room = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room, "one") + coordinator.run_round(room, "two") + newest = _candidates(coordinator, room, "claude")[-1] + assert coordinator.store.repair_parent_problem(room, newest["id"]) is None + _sql(coordinator, "UPDATE rounds SET number=100 WHERE id=?", _round_id(coordinator, room, 2)) + problem = coordinator.store.repair_parent_problem(room, newest["id"]) + assert problem == "repair parent is not from an earlier round" + + +def test_the_repair_guard_and_its_record_agree_past_the_next_round(coordinator): + """A candidate numbered past the next round is not "newer" for either: the + guard used to send the operator to it, a parent the record rejects.""" + room = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room, "one") + coordinator.run_round(room, "two") + older, newer = _candidates(coordinator, room, "claude") + _sql(coordinator, "UPDATE rounds SET number=100 WHERE id=?", _round_id(coordinator, room, 2)) + assert coordinator.store.repair_parent_problem(room, older["id"]) is None + assert coordinator.store.repair_parent_problem(room, newer["id"]) == ( + "repair parent is not from an earlier round" + ) + + +def test_the_repair_record_validator_shares_the_unknown_order_rule(): + digest = "a" * 64 + tree = { + "kind": "repair", + "member_id": "claude", + "parent_candidate_id": "p", + "parent_patch_sha256": digest, + "parent_round_number": 1, + "feedback_ids": [], + "agent_task_sha256": digest, + } + parent = {"member_id": "claude", "state": "completed", "round_number": 1, "patch_sha256": digest} + assert _repair_tree_problem(tree, 3, ["claude"], {"p": parent}) is None + lost = {"member_id": "claude", "state": "completed", "round_number": None} + assert _repair_tree_problem(tree, 3, ["claude"], {"p": parent, "q": lost}) == ( + "repair parent's order among that member's candidates is unknown" + ) + + +# ------------------------------------------------------------- branch-from + + +def _workspace_state(coordinator, room_id): + rows = coordinator.store.list_workspaces(room_id) + return [(row["member_id"], row["path"]) for row in rows] + + +def test_branch_from_a_renumbered_base_keeps_the_workspaces(coordinator): + room = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room, "one") + coordinator.run_round(room, "two") + base = _candidates(coordinator, room, "claude")[0] + before = _workspace_state(coordinator, room) + assert before and all(Path(path).is_dir() for _, path in before) + _sql(coordinator, "UPDATE rounds SET number=100 WHERE id=?", _round_id(coordinator, room, 1)) + with pytest.raises(RoomError, match="not from an earlier round"): + coordinator.preflight_round( + room, "three", lineage="branch-from", base_candidate_id=base["id"] + ) + with pytest.raises(RoomError, match="not from an earlier round"): + coordinator.run_round( + room, "three", lineage="branch-from", base_candidate_id=base["id"] + ) + assert _workspace_state(coordinator, room) == before + assert all(Path(path).is_dir() for _, path in before) + + +def test_branch_from_checks_the_base_again_before_removing_workspaces( + coordinator, monkeypatch +): + """A base damaged after the preflight passed is still refused before any + workspace is removed.""" + room = coordinator.create("a", ["claude"])["id"] + coordinator.run_round(room, "one") + coordinator.run_round(room, "two") + base = _candidates(coordinator, room, "claude")[0] + before = _workspace_state(coordinator, room) + real_preflight = coordinator.preflight_round + + def preflight_then_damage(*args, **kwargs): + room_row = real_preflight(*args, **kwargs) + _sql(coordinator, "UPDATE rounds SET number=100 WHERE id=?", _round_id(coordinator, room, 1)) + return room_row + + monkeypatch.setattr(coordinator, "preflight_round", preflight_then_damage) + with pytest.raises(RoomError, match="not from an earlier round"): + coordinator.run_round( + room, "three", lineage="branch-from", base_candidate_id=base["id"] + ) + assert _workspace_state(coordinator, room) == before + assert all(Path(path).is_dir() for _, path in before) + + +# ------------------------------------------------------------- compare + + +def test_compare_reports_a_candidate_outside_the_rooms_rounds(coordinator): + room = coordinator.create("a", ["claude", "codex"])["id"] + coordinator.run_round(room, "one") + (candidate,) = _candidates(coordinator, room, "codex") + stray = str(uuid.uuid4()) + _sql(coordinator, "UPDATE candidates SET round_id=? WHERE id=?", stray, candidate["id"]) + comparison = build_room_comparison(coordinator.store, room, all_rounds=True) + assert { + "round_id": stray, + "reason": f"candidate {candidate['id']} names a round outside this room", + } in list(comparison.damaged_rounds) + rows = [row.candidate_id for group in comparison.groups for row in group.rows] + assert candidate["id"] not in rows + + +# ------------------------------------------------------------- CLI + + +def _cli_env(monkeypatch, tmp_path): + monkeypatch.setenv("SYNCMILL_ROOMS__ENABLED", "true") + monkeypatch.setenv("SYNCMILL_PROJECT__ID", "room-tests") + monkeypatch.setenv("SYNCMILL_RUNS__ROOT", str(tmp_path / "runs")) + monkeypatch.setenv("SYNCMILL_WORKSPACE__ROOT", str(tmp_path / "workspaces")) + + +def test_room_candidates_lists_the_readable_rest_and_fails( + coordinator, monkeypatch, git_repo, tmp_path +): + from click.testing import CliRunner + + from syncmill.cli import cli + + room = coordinator.create("a", ["claude", "codex"])["id"] + coordinator.run_round(room, "one") + _cli_env(monkeypatch, tmp_path) + runner = CliRunner() + healthy = runner.invoke(cli, ["room", "candidates", room, "--repo", str(git_repo)]) + assert healthy.exit_code == 0, healthy.output + + (damaged,) = _candidates(coordinator, room, "codex") + _sql( + coordinator, + "UPDATE candidates SET round_id=? WHERE id=?", + str(uuid.uuid4()), + damaged["id"], + ) + res = runner.invoke(cli, ["room", "candidates", room, "--repo", str(git_repo)]) + assert res.exit_code == 1, res.output + lines = res.output.splitlines() + codex_line = next(line for line in lines if line.startswith(damaged["id"])) + assert "damaged:" in codex_line and "binding mismatch" in codex_line + # The readable candidate still lists, in its usual shape. + claude_line = next(line for line in lines if line.split()[1:2] == ["claude"]) + assert "gate:" in claude_line and "damaged" not in claude_line + assert f"1 candidate(s) in room {room} could not be read" in res.output diff --git a/tests/test_rooms.py b/tests/test_rooms.py index 51c587a..3c8c753 100644 --- a/tests/test_rooms.py +++ b/tests/test_rooms.py @@ -1336,6 +1336,7 @@ def test_checkpoint_prompt_has_deterministic_utf8_aggregate_byte_cap( "id": f"candidate-{index:03d}", "created_at": f"2026-01-01T00:00:{index:02d}+00:00", "member_id": f"member-{index % 3}", + "round_number": 1, } for index in range(40) ] @@ -1359,10 +1360,10 @@ def load_checkpoint(candidate_id: str, max_output_bytes: int): coordinator.store, "load_candidate_checkpoint", load_checkpoint ) try: - first = coordinator._prompt_with_checkpoint("room", "현재 작업🙂") + first = coordinator._prompt_with_checkpoint("room", "현재 작업🙂", round_number=2) first_loaded = list(loaded) loaded.clear() - second = coordinator._prompt_with_checkpoint("room", "현재 작업🙂") + second = coordinator._prompt_with_checkpoint("room", "현재 작업🙂", round_number=2) encoded = first.encode("utf-8") assert len(encoded) <= rooms_module._ROOM_PROMPT_MAX_BYTES @@ -2648,18 +2649,18 @@ def test_delta_prefix_filters_by_round_and_member_directly(git_repo, tmp_path): coordinator.run_round(room["id"], "one") coordinator.run_round(room["id"], "two") - full = coordinator._prompt_with_checkpoint(room["id"], "next") + full = coordinator._prompt_with_checkpoint(room["id"], "next", round_number=3) assert full.count("[claude |") == 2 and full.count("[codex |") == 2 delta = coordinator._prompt_with_checkpoint( - room["id"], "next", exclude_member="claude", min_round_number=2 + room["id"], "next", round_number=3, exclude_member="claude", min_round_number=2 ) assert "[claude |" not in delta assert delta.count("[codex |") == 1 # Nothing new for the member → the bare prompt, no checkpoint framing. bare = coordinator._prompt_with_checkpoint( - room["id"], "next", exclude_member="claude", min_round_number=3 + room["id"], "next", round_number=3, exclude_member="claude", min_round_number=3 ) assert bare == "next" finally: diff --git a/tests/test_round_conversation.py b/tests/test_round_conversation.py index d82b391..4c60cb5 100644 --- a/tests/test_round_conversation.py +++ b/tests/test_round_conversation.py @@ -100,8 +100,8 @@ def test_builder_reports_exactly_the_candidates_in_its_prompt(git_repo, tmp_path monkeypatch.setattr(rooms_module, "_ROOM_PROMPT_MAX_BYTES", cap) rows = coordinator.store.candidate_rows(room["id"]) for kwargs in ({}, {"exclude_member": "claude", "min_round_number": 1}): - prompt, included, omitted = coordinator._checkpoint(room["id"], "next", **kwargs) - assert prompt == coordinator._prompt_with_checkpoint(room["id"], "next", **kwargs) + prompt, included, omitted = coordinator._checkpoint(room["id"], "next", round_number=3, **kwargs) + assert prompt == coordinator._prompt_with_checkpoint(room["id"], "next", round_number=3, **kwargs) assert _BLOCK.findall(prompt) == included eligible = checkpoint_eligible(rows, round_number=3, **kwargs) if omitted: @@ -472,7 +472,7 @@ def test_bare_prompt_fallbacks_report_no_candidates(git_repo, tmp_path, monkeypa with monkeypatch.context() as patch: # Framing alone over the cap. patch.setattr(rooms_module, "_ROOM_PROMPT_MAX_BYTES", 50) - assert coordinator._checkpoint(room["id"], "next") == ("next", [], True) + assert coordinator._checkpoint(room["id"], "next", round_number=2) == ("next", [], True) with monkeypatch.context() as patch: # Room for the framing but not for the truncation marker. framing = len( @@ -481,7 +481,7 @@ def test_bare_prompt_fallbacks_report_no_candidates(git_repo, tmp_path, monkeypa "after the separator.\n\n\n\n--- CURRENT USER TASK ---\nnext".encode() ) patch.setattr(rooms_module, "_ROOM_PROMPT_MAX_BYTES", framing + 1) - assert coordinator._checkpoint(room["id"], "next") == ("next", [], True) + assert coordinator._checkpoint(room["id"], "next", round_number=2) == ("next", [], True) real = rooms_module._prompt_arg_units def units(text, name): @@ -493,7 +493,7 @@ def units(text, name): # The composed prompt fits the byte budget but not the platform # accounting (the Windows quoting path): bare prompt, nothing in it. patch.setattr(rooms_module, "_prompt_arg_units", units) - assert coordinator._checkpoint(room["id"], "next") == ("next", [], True) + assert coordinator._checkpoint(room["id"], "next", round_number=2) == ("next", [], True) finally: coordinator.close() @@ -609,7 +609,7 @@ def test_prompts_are_byte_identical_to_the_pre_change_builder(git_repo, tmp_path room_id = _frozen_room(coordinator.store, clock) cases = checkpoint_cases( rooms_module, - lambda **kw: coordinator._checkpoint(room_id, "next", **kw)[0], + lambda **kw: coordinator._checkpoint(room_id, "next", round_number=3, **kw)[0], lambda ctx, prompt: RoomCoordinator._memory_prefixed(ctx, prompt)[0], _patcher(monkeypatch, rooms_module), ) diff --git a/tests/test_tui.py b/tests/test_tui.py index 72c9d28..189a42c 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -605,6 +605,9 @@ def get_room(self, room_id): def get_candidate(self, candidate_id): return {"id": candidate_id} + def round_room_id(self, round_id): + return "room-1" + def load_candidate(self, candidate_id): return {"candidate_id": candidate_id, "patch_sha256": "abc123"} @@ -1261,6 +1264,9 @@ def events(self, room_id): def get_candidate(self, candidate_id): return dict(self.rows[candidate_id]) + def round_room_id(self, round_id): + return "room-1" + def get_round(self, round_id): return {"id": round_id, "number": 3} @@ -2257,6 +2263,222 @@ async def scenario(): drive(scenario()) +def test_an_unreadable_candidate_marks_its_pane_and_the_room_still_refreshes( + tmp_path, git_repo, monkeypatch +): + """A RoomError from the candidate's own artifact is that candidate's + damage: the room's other panes refresh, the candidate pane says it is + unreadable, and nothing is cached, so a repair shows on the next poll.""" + from syncmill.rooms import RoomError + + class _DamagedArtifactStore(_FakeCandidateRoomStore): + def __init__(self): + super().__init__() + self.broken = False + self.patch_reads = 0 + + def get_room(self, room_id): + room = super().get_room(room_id) + if self.broken: + room["state"] = "awaiting_decision" # the room pane changes + return room + + def load_candidate_patch_head(self, candidate_id, max_patch_bytes): + self.patch_reads += 1 + if self.broken: + raise RoomError(f"candidate round binding mismatch: {candidate_id}") + return super().load_candidate_patch_head(candidate_id, max_patch_bytes) + + async def scenario(): + app = _room_apply_app(tmp_path, git_repo) + store = _DamagedArtifactStore() + async with app.run_test() as pilot: + await pilot.pause() + app._rooms = _FakeRooms(store=store) + monkeypatch.setattr(app, "_reload_config", lambda: True) + await pilot.press("7") + await pilot.pause() + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + store.broken = True + store.rows["cand-ok"]["patch_sha256"] = "p-new" # key changes → re-read + app._poll() + await pilot.pause() + status = str(app.query_one("#room-status").render()) + assert "DEGRADED" not in status and "rooms:" in status + assert "awaiting_decision" in str(app.query_one("#room-detail").render()) + detail = str(app.query_one("#candidate-detail").render()) + assert "unreadable" in detail and "cand-ok" in detail + assert app._selected_candidate_id == "cand-ok" + # Never cached: the next poll reads again, and a repair shows. + reads = store.patch_reads + app._poll() + await pilot.pause() + assert store.patch_reads == reads + 1 + store.broken = False + app._poll() + await pilot.pause() + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + + drive(scenario()) + + +def test_a_round_that_leaves_the_room_invalidates_the_cached_pane( + tmp_path, git_repo, monkeypatch +): + """The cache key carries the round's binding: a candidate shown while its + round was intact is validated again once the round moves or vanishes.""" + from syncmill.rooms import RoomError + + class _MovingRoundStore(_FakeCandidateRoomStore): + def __init__(self): + super().__init__() + self.round_room = "room-a" + + def round_room_id(self, round_id): + return self.round_room + + def load_candidate_patch_head(self, candidate_id, max_patch_bytes): + if self.round_room != "room-a": + raise RoomError(f"candidate round binding mismatch: {candidate_id}") + return super().load_candidate_patch_head(candidate_id, max_patch_bytes) + + async def scenario(): + app = _room_apply_app(tmp_path, git_repo) + store = _MovingRoundStore() + async with app.run_test() as pilot: + await pilot.pause() + app._rooms = _FakeRooms(store=store) + monkeypatch.setattr(app, "_reload_config", lambda: True) + await pilot.press("7") + await pilot.pause() + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + store.round_room = None # the round is gone; the row is unchanged + app._poll() + await pilot.pause() + assert "unreadable" in str(app.query_one("#candidate-detail").render()) + store.round_room = "room-a" + app._poll() + await pilot.pause() + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + + drive(scenario()) + + +def test_a_candidate_moved_to_another_round_invalidates_the_cached_pane( + tmp_path, git_repo, monkeypatch +): + """The candidate's own round id is in the key too: a row pointed at another + round of the same room is validated again, then shows once restored.""" + from syncmill.rooms import RoomError + + class _RepointedStore(_FakeCandidateRoomStore): + def __init__(self): + super().__init__() + for row in self.rows.values(): + row["round_id"] = "round-1" + + def load_candidate_patch_head(self, candidate_id, max_patch_bytes): + if self.rows[candidate_id]["round_id"] != "round-1": + raise RoomError(f"candidate round_id binding mismatch: {candidate_id}") + return super().load_candidate_patch_head(candidate_id, max_patch_bytes) + + async def scenario(): + app = _room_apply_app(tmp_path, git_repo) + store = _RepointedStore() + async with app.run_test() as pilot: + await pilot.pause() + app._rooms = _FakeRooms(store=store) + monkeypatch.setattr(app, "_reload_config", lambda: True) + await pilot.press("7") + await pilot.pause() + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + store.rows["cand-ok"]["round_id"] = "round-2" # same room, digests unchanged + app._poll() + await pilot.pause() + assert "unreadable" in str(app.query_one("#candidate-detail").render()) + store.rows["cand-ok"]["round_id"] = "round-1" + app._poll() + await pilot.pause() + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + + drive(scenario()) + + +def test_a_candidate_row_that_cannot_be_read_marks_only_its_pane( + tmp_path, git_repo, monkeypatch +): + from syncmill.rooms import RoomError + + class _VanishingRowStore(_FakeCandidateRoomStore): + def __init__(self): + super().__init__() + self.broken = False + self.row_reads = 0 + + def get_room(self, room_id): + room = super().get_room(room_id) + if self.broken: + room["state"] = "awaiting_decision" + return room + + def get_candidate(self, candidate_id): + self.row_reads += 1 + if self.broken: + raise RoomError(f"unknown candidate: {candidate_id}") + return super().get_candidate(candidate_id) + + async def scenario(): + app = _room_apply_app(tmp_path, git_repo) + store = _VanishingRowStore() + async with app.run_test() as pilot: + await pilot.pause() + app._rooms = _FakeRooms(store=store) + monkeypatch.setattr(app, "_reload_config", lambda: True) + await pilot.press("7") + await pilot.pause() + store.broken = True + app._poll() + await pilot.pause() + assert "DEGRADED" not in str(app.query_one("#room-status").render()) + assert "awaiting_decision" in str(app.query_one("#room-detail").render()) + detail = str(app.query_one("#candidate-detail").render()) + assert "unreadable" in detail and "unknown candidate" in detail + reads = store.row_reads + store.broken = False + app._poll() + await pilot.pause() + assert store.row_reads > reads + assert "[Diff]" in str(app.query_one("#candidate-detail").render()) + + drive(scenario()) + + +def test_switching_view_after_an_unreadable_diff_reads_the_output( + tmp_path, git_repo, monkeypatch +): + from syncmill.rooms import RoomError + + class _BadPatchStore(_FakeCandidateRoomStore): + def load_candidate_patch_head(self, candidate_id, max_patch_bytes): + raise RoomError(f"candidate patch digest mismatch: {candidate_id}") + + async def scenario(): + app = _room_apply_app(tmp_path, git_repo) + async with app.run_test() as pilot: + await pilot.pause() + app._rooms = _FakeRooms(store=_BadPatchStore()) + monkeypatch.setattr(app, "_reload_config", lambda: True) + await pilot.press("7") + await pilot.pause() + assert "unreadable" in str(app.query_one("#candidate-detail").render()) + assert "DEGRADED" not in str(app.query_one("#room-status").render()) + assert app._show_candidate_as("cand-ok", "output", 1) + await pilot.pause() + assert "provider said hi" in str(app.query_one("#candidate-detail").render()) + + drive(scenario()) + + def test_rooms_late_failure_keeps_selection_matching_visible_panes( tmp_path, git_repo, monkeypatch ):