Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/agent_comms/team/team_heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,13 +464,20 @@ def failed(
),
))
current = retained_huds.get(thread.incarnation)
if current is not None:
changed_huds.append(replace(
open_pings = update.open_pings(actions)
stopped = update.stopped(snapshot)
changed_huds.append(
replace(
current,
packets=(update,),
open_pings=update.open_pings(actions),
stopped=update.stopped(snapshot),
))
open_pings=open_pings,
stopped=stopped,
)
if current is not None
else TeamHud.for_failure(
thread.incarnation, update, open_pings, stopped
)
)
publications.append((update, sections))
self._retained_board = None
TeamBoardPublicationStore.write_all(
Expand Down
33 changes: 31 additions & 2 deletions src/agent_comms/team/team_hud.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,27 @@ def hud_text(self, now: float, *, colour: bool = False) -> tuple[str, ...]:
def frame(self) -> tuple[str, ...]:
return self.hud_text(time.time())

@classmethod
def for_failure(
cls,
teammate: ThreadIncarnation,
packet: TeamUpdate,
open_pings: tuple[Ping, ...] = (),
stopped: frozenset[str] = frozenset(),
) -> TeamHud:
"""Retain a service-failure packet before any full board pass has published a HUD."""
return cls(
teammate=teammate,
units=(),
phases=(),
load=OverloadDegradation.from_orders((), 0, 0),
forks=(),
usage=CodexUsage(UnreadableUsage(reason="heartbeat failed")),
packets=(packet,),
open_pings=open_pings,
stopped=stopped,
)

def load_reading(self) -> TeamLoad:
return TeamLoad(self.load, services=self.services, heartbeat=self.heartbeat)

Expand Down Expand Up @@ -877,7 +898,11 @@ def retained(
publication: TeamBoardPublication | None = None,
) -> RetainedTeamBoard:
"""Decode one publication once and retain the source that makes reuse valid."""
publication = self.read() if publication is None else publication
if publication is None:
try:
publication = self.read()
except RecordProblems:
return RetainedTeamBoard(self.empty(), ())
return RetainedTeamBoard(
publication,
tuple(
Expand Down Expand Up @@ -987,7 +1012,11 @@ def write_all(
if not huds:
return frozenset()
store = cls.at(root)
publication = store.read()
try:
publication = store.read()
except RecordProblems:
publication = store.empty()
retained_board = RetainedTeamBoard(publication, ())
if retained_board is None or retained_board.publication != publication:
retained_board = store.retained(publication)
huds_before = retained_board.huds
Expand Down
80 changes: 41 additions & 39 deletions tests/test_team_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
)
from agent_comms.ui_model.observation_service import (
ObservationService,
RetryObservationStep,
TeamHudReading,
)
from agent_comms.ui_model.teammate_state import (
Expand Down Expand Up @@ -448,7 +449,7 @@ def test_each_team_gets_its_own_failure_packet(notification_bus):
for name in ("colleague", "worker"):
teammate = comms.registry.require(name).incarnation
update = TeamUpdate.report_failure(teammate, failure, (), published=(), now=now)
TeamUpdateStore.record(comms.root, update)
TeamBoardPublicationStore.write_all(comms.root, (TeamHud.for_failure(teammate, update),))
update.send(comms, ())
latest, = TeamUpdate.latest(comms, teammate)
assert latest.teammate == teammate
Expand Down Expand Up @@ -587,7 +588,7 @@ def test_a_recreated_team_inherits_no_board(notification_bus):
assert TeamUpdate.latest(comms, board.task.teammate) == (board.task,)
now = time.time()
update = TeamUpdate.report_failure(reborn, failing, (), published=(), now=now)
TeamUpdateStore.record(comms.root, update)
TeamBoardPublicationStore.write_all(comms.root, (TeamHud.for_failure(reborn, update),))
update.send(comms, ())
latest, = TeamUpdate.latest(comms, reborn)
assert latest.teammate == reborn and latest.handled == update.handled
Expand Down Expand Up @@ -709,7 +710,7 @@ def test_quiet_completion_is_per_teammate_even_when_a_later_recipient_fails(
failed_at=time.time())
observed = TeamObservation(capture_frame(comms, ProgressRead()), (failing,), ())
with monkeypatch.context() as patched:
patched.setattr(TeamHeartbeat, "served", classmethod(lambda cls, registry, goals: (colleague, missing)))
patched.setattr(TeamHeartbeat, "served", classmethod(lambda cls, registry, goals, snapshot=None: (colleague, missing)))
with pytest.raises(UnregisteredThreadError):
asyncio.run(ObservedHeartbeat(observed).run(lambda: nullcontext(comms)))
completed = ServicePassStore.at(comms.root).read().teammate_completed
Expand Down Expand Up @@ -858,7 +859,7 @@ def test_new_local_commit_on_an_unpushed_branch_is_not_a_resolution(notification
assert isinstance(repeated.task, TeamDecisions)
assert repeated.task.decisions == ()
assert aged(repeated.task.handled) == aged(original.task.handled)
retained, = TeamUpdateStore.for_team(comms.root, repeated.task.teammate).read()
retained, = TeamUpdate.latest(comms, repeated.task.teammate)
assert tuple(ping.text for ping in retained.handled) == tuple(
ping.text for ping in repeated.task.handled)
assert tuple(ping.text for ping in retained.handled) != tuple(
Expand Down Expand Up @@ -890,12 +891,10 @@ async def test_team_page_reads_each_beats_frame_and_nothing_between(notification
client, observer = Pipe()

async def observed() -> tuple[TeamHudObserved, ...]:
"""One service pass, as run takes it: the service advances its own revision, and the
board it prepares off the pass (in the task group only run enters) is awaited. The
pass's other results, such as RevisionObserved, are not the team page's."""
"""One service pass, as run takes it: the service advances its own revision and reads
the retained heartbeat publication synchronously. Other pass results, such as
RevisionObserved, are not the team page's."""
await watched_pass(service)
reading, = service.interest.observations.values()
await asyncio.gather(*reading.preparation)
sent = []
while client.poll():
sent.append(client.recv())
Expand All @@ -907,8 +906,7 @@ async def observed() -> tuple[TeamHudObserved, ...]:
async with service.tasks:
service.accept(ObserveTeamHud())
first, = await observed()
assert first.huds == (expected,)
assert len(await observed()) == 1 # the page's own preparation, once
assert first.cut.huds == (expected,)
assert await observed() == ()
await asyncio.to_thread(beat, comms, states=states)
assert len(await observed()) == 1
Expand All @@ -932,60 +930,64 @@ def test_a_frame_this_reader_cannot_decode_reaches_the_page_not_the_observer(not
assert "field_from_a_newer_build" in str(unreadable.error)
beat(comms, states=state_cards(comms, TeammateState))
recovered, = reading.read(comms, comms.views.revision())
assert pickle.loads(pickle.dumps(recovered)).huds == TeamBoardPublicationStore.read_all(comms.root)
assert pickle.loads(pickle.dumps(recovered)).cut.huds == TeamBoardPublicationStore.read_all(comms.root)


@dataclass
class PreparedInterest:
readings: list = field(default_factory=list)
class RecordingHost(observation.ObservationHost):
"""Minimal ObservationHost recording busy/publish effects of one ObservationStep."""

def prepared(self, reading, service) -> None:
self.readings.append(reading)


@dataclass
class PreparingService:
"""The parts of ObservationService a board preparation touches, recording what it sends."""

comms: object
revision: object
sent: list = field(default_factory=list)
interest: PreparedInterest = field(default_factory=PreparedInterest)
busy: int = 0
again: int = 0

def send(self, result) -> None:
self.sent.append(result)

def retire_pending(self, request_id: int) -> None:
pass

def mark_busy(self) -> None:
self.busy += 1

def observe_again(self) -> None:
self.again += 1


@pytest.mark.parametrize("failure, outcome", [
(DeferredRead("the board's stores are mid-write"), "again"),
(ValueError("a heartbeat frame this build cannot decode"), "unreadable"),
(RuntimeError("a defect in the board read"), "raised"),
])
def test_preparing_the_board_answers_each_read_outcome_through_its_owner(
notification_bus, failure, outcome):
"""prepare() caught every Exception and called it unreadable history: a deferred read was
shown as broken instead of retried, and a real defect was rendered as a saved-data error.
It now reads through UnreadableHistory.outcome, the owner read() already uses."""
notification_bus, monkeypatch, failure, outcome):
"""prepare() maps each board read outcome through UnreadableHistory.outcome and
_TeamHudReadOutcome: a deferred read yields RetryObservationStep (invalidating read_revision
and marking the host busy), an undecodable frame yields TeamHudUnreadable, and a real
defect propagates."""
comms = notification_bus
revision = comms.views.revision()
reading = TeamHudReading(ObserveTeamHud())
service = PreparingService(comms, comms.views.revision())
reading.prepared_revision = service.revision
reading.read_revision = revision
host = RecordingHost()

def failing_board(_comms, selection):
def failing_cut(cls, root, selection):
raise failure

reading.read_board = failing_board
monkeypatch.setattr(TeamBoardPublicationStore, "read_cut", classmethod(failing_cut))
if outcome == "raised":
with pytest.raises(RuntimeError, match="a defect in the board read"):
asyncio.run(reading.prepare(service))
list(reading.prepare(comms, revision))
return
asyncio.run(reading.prepare(service))
assert service.interest.readings == []
step, = reading.prepare(comms, revision)
step.publish(host)
if outcome == "again":
assert service.sent == []
assert isinstance(reading.prepared_revision, NoRevision)
assert isinstance(step, RetryObservationStep)
assert host.sent == []
assert host.busy == 1
assert isinstance(reading.read_revision, NoRevision)
else:
unreadable, = service.sent
unreadable, = host.sent
assert isinstance(unreadable, observation.TeamHudUnreadable)
assert "cannot decode" in str(unreadable.error)

Expand Down
Loading