From 566c85a82d823d37a77d6e6be52f336956192ea5 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 13:39:56 -0500 Subject: [PATCH] Hold a background task's ACP prompt into the next turn instead of cancelling it #5264 bounded BackgroundTaskWaitPhase with a 180 s silence budget whose expiry sent session/cancel and failed the turn with ModelStalled. On agy, "reply, then silence while a background task runs" is how a model waits on its own pytest or NRA, so every wait over 3 min killed the task (agy: "All your subagents and background tasks have been stopped due to user force cancellation") and the failed attempt left the goal in BlockedGeneration. Live on ts-gaming: pm-pbt idle 3h53m after 08:25, pm-neuro-arch blocked since 13:09. agy takes concurrent session/prompt on a live session (AcpLivePrompt.steer) and routes frames per session, so a held-open prompt never wedges agy; it only kept Core's turn from ending. The wedge 12314 asked to remove was the thread, never the task. - TurnPhase.silence_ending: past its budget a phase picks its ending through SilenceEndings; the default stalls, BackgroundTaskWaitPhase holds. Its stall_message and stall_reason go. - AcpTurnEnding family (Settled, Held, Stalled) owns how a turn releases its live prompt and which terminal events it reports; the stall copy of the settle path goes. - AcpTurnPrompt (NoLivePrompt, AcpLivePrompt): the next turn continues a held prompt with its input as a steer, or opens one. - AcpLivePrompt keeps one read across next_frames calls, so a turn that stops reading never takes a frame with it. - POST_REPLY_STALL_SECONDS -> POST_REPLY_HOLD_SECONDS. --- src/agent_comms/execution/antigravity_acp.py | 64 +++++++-- .../execution/antigravity_backend.py | 100 ++++++++++--- src/agent_comms/execution/turn_phase.py | 32 ++++- tests/test_antigravity_acp_backend.py | 136 ++++++++++-------- 4 files changed, 233 insertions(+), 99 deletions(-) diff --git a/src/agent_comms/execution/antigravity_acp.py b/src/agent_comms/execution/antigravity_acp.py index c0d435023e..9af8006c75 100644 --- a/src/agent_comms/execution/antigravity_acp.py +++ b/src/agent_comms/execution/antigravity_acp.py @@ -551,7 +551,37 @@ def resolve_agy_binary() -> str: return "agy" -class AcpLivePrompt: +class AcpTurnPrompt(ABC): + """The ``session/prompt`` a backend's next turn continues: a held live prompt or none.""" + + @abstractmethod + async def continue_with( + self, + process: AntigravityAcpProcess, + session_id: AcpSessionId, + blocks: Sequence[Mapping[str, object]], + ) -> AcpLivePrompt: ... + + @abstractmethod + def close(self) -> None: ... + + +class NoLivePrompt(AcpTurnPrompt): + """No prompt outlived the previous turn; the next turn opens its own.""" + + async def continue_with( + self, + process: AntigravityAcpProcess, + session_id: AcpSessionId, + blocks: Sequence[Mapping[str, object]], + ) -> AcpLivePrompt: + return await process.open_prompt(session_id, blocks) + + def close(self) -> None: + pass + + +class AcpLivePrompt(AcpTurnPrompt): """One live ``session/prompt`` turn on ``agy acp`` supporting concurrent mid-turn steers.""" def __init__( @@ -565,6 +595,9 @@ def __init__( self._session_id = session_id self._queue = queue self._in_flight: set[Task[dict[str, JsonValue]]] = {initial_task} + # One read outlives each next_frames call: a turn that stops reading a held + # prompt never takes a frame with it. + self._reading: Task[AcpQueueItem] = asyncio.create_task(queue.get()) self._last_stop_reason: str = "" self._finished = False @@ -582,6 +615,17 @@ def steer(self, blocks: Sequence[Mapping[str, object]]) -> None: ) self._in_flight.add(task) + async def continue_with( + self, + process: AntigravityAcpProcess, + session_id: AcpSessionId, + blocks: Sequence[Mapping[str, object]], + ) -> AcpLivePrompt: + """A prompt held open by agy past its reply takes the next turn's input as a steer.""" + del process, session_id + self.steer(blocks) + return self + def _drain_queued_nowait(self) -> list[AcpPromptFrame]: frames: list[AcpPromptFrame] = [] while not self._queue.empty(): @@ -600,24 +644,21 @@ async def next_frames(self) -> tuple[AcpPromptFrame, ...]: result = AcpPromptResultWire.model_validate(await task) if result.stop_reason: self._last_stop_reason = result.stop_reason + if self._reading.done(): + frames = [*self._reading.result().frames(), *self._drain_queued_nowait()] + self._reading = asyncio.create_task(self._queue.get()) + return tuple(frames) if not self._in_flight: self._finished = True + self._reading.cancel() queued = self._drain_queued_nowait() queued.append(AcpResultFrame(self._last_stop_reason)) return tuple(queued) - if not self._queue.empty(): - return tuple(self._drain_queued_nowait()) - get_task: Task[AcpQueueItem] = asyncio.create_task(self._queue.get()) - wait_set: set[Task[object]] = {*self._in_flight, get_task} - done, _ = await asyncio.wait(wait_set, return_when=asyncio.FIRST_COMPLETED) - if get_task in done: - return tuple(get_task.result().frames()) - get_task.cancel() - with suppress(asyncio.CancelledError): - await get_task + await asyncio.wait({*self._in_flight, self._reading}, return_when=asyncio.FIRST_COMPLETED) async def cancel_and_close(self) -> None: self._finished = True + self._reading.cancel() with suppress(AcpRpcError): await self._process.cancel(self._session_id) for task in list(self._in_flight): @@ -632,6 +673,7 @@ async def cancel_and_close(self) -> None: def close(self) -> None: self._finished = True + self._reading.cancel() self._process._session_queues.pop(self._session_id, None) diff --git a/src/agent_comms/execution/antigravity_backend.py b/src/agent_comms/execution/antigravity_backend.py index d6865a59fc..201713e009 100644 --- a/src/agent_comms/execution/antigravity_backend.py +++ b/src/agent_comms/execution/antigravity_backend.py @@ -11,8 +11,10 @@ import asyncio import uuid +from abc import abstractmethod from collections.abc import AsyncIterator from contextlib import suppress +from dataclasses import dataclass from pathlib import Path from typing import ClassVar, Self @@ -29,12 +31,15 @@ ) from agent_comms.execution.agent_event import AgentEvent from agent_comms.execution.antigravity_acp import ( + AcpLivePrompt, AcpRpcError, + AcpTurnPrompt, AntigravityAcpPool, AntigravityAcpProcess, AntigravityConversationId, AntigravitySessionFiles, AntigravitySessionStorage, + NoLivePrompt, ) from agent_comms.execution.antigravity_acp_events import ( ANTIGRAVITY_ACP_EVENT_KINDS, @@ -49,7 +54,7 @@ AntigravitySessionDeclaration, ) from agent_comms.execution.backend_query import TurnInputContent -from agent_comms.execution.process_identity import ProcessState +from agent_comms.execution.process_identity import ProcessIdentity, ProcessState from agent_comms.execution.launch_runtime import LaunchRuntime from agent_comms.execution.runtime_observations import ( AgentInfo, @@ -61,6 +66,7 @@ from agent_comms.execution.turn_phase import ( NativePhaseChanged, SettlingStatsPhase, + SilenceEndings, TurnPhase, ) from agent_comms.cli_bridges.history import AntigravityAcpSession @@ -118,6 +124,61 @@ def _selected_model_name(*, provider: object = "", model_id: object = "") -> str return str(model_id) +class AcpTurnEnding(SilenceEndings["AcpTurnEnding"]): + """How one ACP turn leaves its live prompt and which terminal events it reports.""" + + @classmethod + def stalled(cls, message: str) -> AcpTurnEnding: + return StalledAcpTurn(message) + + @classmethod + def held(cls) -> AcpTurnEnding: + return HeldAcpTurn() + + async def release(self, backend: AntigravityAcpBackend, live: AcpLivePrompt) -> None: + live.close() + + @abstractmethod + def events( + self, state: AcpTurnStreamState, identity: ProcessIdentity + ) -> tuple[AgentEvent, ...]: ... + + +class SettledAcpTurn(AcpTurnEnding): + def events( + self, state: AcpTurnStreamState, identity: ProcessIdentity + ) -> tuple[AgentEvent, ...]: + return ( + NativePhaseChanged(SettlingStatsPhase(), identity), + events.StreamSettled(), + events.Done(text=state.full_text, ok=True), + ) + + +class HeldAcpTurn(SettledAcpTurn): + """The reply is complete while agy holds the prompt open for a background task: + the turn settles and the backend's next turn continues the prompt.""" + + async def release(self, backend: AntigravityAcpBackend, live: AcpLivePrompt) -> None: + backend._held = live + + +@dataclass(frozen=True) +class StalledAcpTurn(AcpTurnEnding): + message: str + + async def release(self, backend: AntigravityAcpBackend, live: AcpLivePrompt) -> None: + await live.cancel_and_close() + + def events( + self, state: AcpTurnStreamState, identity: ProcessIdentity + ) -> tuple[AgentEvent, ...]: + return ( + events.Error(text=self.message), + events.Done(text=self.message, ok=False, failure=ModelStalled(self.message)), + ) + + class AntigravityAcpBackend( ServedAgentBackend, AntigravityAcpBackendDeclaration ): @@ -126,7 +187,7 @@ class AntigravityAcpBackend( location_type: ClassVar[type[RuntimeLocation]] = AntigravitySession event_kinds: ClassVar[frozenset[str]] = ANTIGRAVITY_ACP_EVENT_KINDS REPLY_QUIET_SECONDS: ClassVar[float] = 15.0 - POST_REPLY_STALL_SECONDS: ClassVar[float] = 180.0 + POST_REPLY_HOLD_SECONDS: ClassVar[float] = 180.0 MODEL_STALL_SECONDS: ClassVar[float] = 360.0 @classmethod @@ -168,6 +229,7 @@ def turn_transcript_sink( def __init__(self, process: AntigravityAcpProcess) -> None: self._process = process self._acp_session: AcpSessionSelection = NoAcpSessionId() + self._held: AcpTurnPrompt = NoLivePrompt() self._applied_model: str = "" self._applied_thinking: str = "" self._lock = asyncio.Lock() @@ -221,6 +283,8 @@ async def _ensure_acp_session( bound_sessions = self._bound_sessions() if bound_sessions and self._process.alive: return bound_sessions[0], False, storage.db_path + # A prompt held on a session this process no longer serves cannot continue. + self._held = NoLivePrompt() if storage.exists: descriptor = await self._process.resume_session( AcpSessionId(str(storage.conversation_id)), worktree @@ -292,7 +356,11 @@ async def run_turn( ) last_phase: TurnPhase = state.phase yield NativePhaseChanged(last_phase, self._process._state.require_identity()) - live = await self._process.open_prompt(session_id, content.acp_prompt_blocks()) + live = await self._held.continue_with( + self._process, session_id, content.acp_prompt_blocks() + ) + self._held = NoLivePrompt() + ending: AcpTurnEnding = SettledAcpTurn() inbox_task: asyncio.Task[TurnInboxItem] = asyncio.create_task(delivery.inbox.get()) frames_task: asyncio.Task[tuple[AcpPromptFrame, ...]] = asyncio.create_task( live.next_frames() @@ -307,7 +375,7 @@ async def run_turn( deadlines.append(max(0.0, self.REPLY_QUIET_SECONDS - idle)) stall_budget = state.phase.silence_budget( model_wait=self.MODEL_STALL_SECONDS, - post_reply_wait=self.POST_REPLY_STALL_SECONDS, + post_reply_wait=self.POST_REPLY_HOLD_SECONDS, ) if stall_budget is not None: deadlines.append(max(0.0, stall_budget - idle)) @@ -328,18 +396,11 @@ async def run_turn( ) stall_budget = state.phase.silence_budget( model_wait=self.MODEL_STALL_SECONDS, - post_reply_wait=self.POST_REPLY_STALL_SECONDS, + post_reply_wait=self.POST_REPLY_HOLD_SECONDS, ) if stall_budget is not None and idle >= stall_budget: - stall_message = state.phase.stalled().stall_message(stall_budget) - await live.cancel_and_close() - yield events.Error(text=stall_message) - yield events.Done( - text=stall_message, - ok=False, - failure=ModelStalled(stall_message), - ) - return + ending = state.phase.silence_ending(stall_budget, AcpTurnEnding) + break continue if inbox_task in done: last_activity = loop.time() @@ -382,12 +443,9 @@ async def run_turn( pending_task.cancel() with suppress(asyncio.CancelledError): await pending_task - live.close() - yield NativePhaseChanged( - SettlingStatsPhase(), self._process._state.require_identity() - ) - yield events.StreamSettled() - yield events.Done(text=state.full_text, ok=True) + await ending.release(self, live) + for event in ending.events(state, self._process._state.require_identity()): + yield event except (AcpRpcError, ConnectionError, TimeoutError) as error: message = str(error) yield events.Error(text=message) @@ -403,6 +461,8 @@ async def close_idle(self) -> None: async with self._lock: bound_sessions = self._bound_sessions() self._acp_session = NoAcpSessionId() + self._held.close() + self._held = NoLivePrompt() self._applied_model = "" self._applied_thinking = "" for active in bound_sessions: diff --git a/src/agent_comms/execution/turn_phase.py b/src/agent_comms/execution/turn_phase.py index 48cfe8eadf..2aebe54b54 100644 --- a/src/agent_comms/execution/turn_phase.py +++ b/src/agent_comms/execution/turn_phase.py @@ -1,5 +1,6 @@ from __future__ import annotations +from abc import ABC, abstractmethod from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING, ClassVar, Self @@ -29,6 +30,18 @@ def model_progress(self) -> TurnPhase: return self +class SilenceEndings[Ending](ABC): + """The endings a backend gives a stream silent past its phase's budget.""" + + @classmethod + @abstractmethod + def stalled(cls, message: str) -> Ending: ... + + @classmethod + @abstractmethod + def held(cls) -> Ending: ... + + class NoModelWait: """Native-owned excursions have no Core model-progress deadline.""" @@ -162,6 +175,10 @@ def stalled(self) -> TurnPhase: def stall_message(self, budget: float) -> str: return f"Model produced no RPC progress for {budget:g} seconds." + def silence_ending[Ending](self, budget: float, endings: type[SilenceEndings[Ending]]) -> Ending: + """How a stream silent past this phase's budget ends: a stall cancels the turn.""" + return endings.stalled(self.stalled().stall_message(budget)) + def phase_effects(self, agents: AgentActivity, lease: TurnLeaseFence) -> None: agents.publish_phase() @@ -254,10 +271,13 @@ def quiet_phase(self, *, background_tasks: tuple[str, ...]) -> TurnPhase: @dataclass(frozen=True) class BackgroundTaskWaitPhase(StallExempt, Excursion): - """Reply text stopped streaming, but a background task still holds the ACP turn open.""" + """Reply text stopped streaming, but a background task still holds the ACP turn open. + + agy holds ``session/prompt`` open while the task runs and wakes the model when it + ends, so silence here is the model waiting, never a stall: past the budget the turn + ends with its reply and the next turn continues the held prompt.""" tasks: tuple[str, ...] = () - stall_reason = "background_task_no_progress" activity_state = ActivityState.WORKING label = "Waiting on background task" @@ -273,11 +293,9 @@ def silence_budget(self, *, model_wait: float, post_reply_wait: float) -> float del model_wait return post_reply_wait - def stall_message(self, budget: float) -> str: - return ( - f"Antigravity ACP turn produced no progress for {budget:g} seconds " - "while waiting on a background task." - ) + def silence_ending[Ending](self, budget: float, endings: type[SilenceEndings[Ending]]) -> Ending: + del budget + return endings.held() class SettlingStatsPhase(NonFollowupTurnPhase): diff --git a/tests/test_antigravity_acp_backend.py b/tests/test_antigravity_acp_backend.py index a36d34d4b7..91e2a10f22 100644 --- a/tests/test_antigravity_acp_backend.py +++ b/tests/test_antigravity_acp_backend.py @@ -1456,13 +1456,12 @@ def run_goal_turn(sid, rid): @pytest.mark.asyncio -async def test_antigravity_acp_transitions_silent_post_reply_to_background_wait_and_recovers( +async def test_antigravity_acp_holds_a_background_task_prompt_into_the_next_turn( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """When agy acp holds session/prompt open silently after final reply text (e.g. a forgotten - background task or stopped child), AntigravityAcpBackend must move out of ReplyingPhase into - BackgroundTaskWaitPhase and cancel/fail with ModelStalled once the stall budget expires.""" - from agent_comms.execution.turn_failure import ModelStalled + """agy holds session/prompt open after the reply while a background task runs. Past the + hold budget the turn settles with its reply, nothing is cancelled (cancelling kills the + task), and the next turn continues the held prompt on the same session.""" from agent_comms.execution.turn_phase import ( BackgroundTaskWaitPhase, NativePhaseChanged, @@ -1470,57 +1469,65 @@ async def test_antigravity_acp_transitions_silent_post_reply_to_background_wait_ ) cancel_marker = tmp_path / "cancelled.txt" - hung_bg_server = f""" -import json, sys, threading, time, uuid + prompts_log = tmp_path / "prompts.txt" + held_bg_server = f""" +import json, sys, uuid cancel_path = {str(cancel_marker)!r} -cancelled = threading.Event() +prompts_path = {str(prompts_log)!r} +open_prompts = [] -def reader(): - for raw in sys.stdin: - if not raw.strip(): - continue - msg = json.loads(raw) - method = msg.get("method") - rid = msg.get("id") - params = msg.get("params") or {{}} - def send(payload): - sys.stdout.write(json.dumps(payload) + "\\n") - sys.stdout.flush() - if method == "initialize": - send({{"jsonrpc": "2.0", "id": rid, "result": {{"protocolVersion": 1}}}}) - elif method in ("session/new", "session/resume"): - sid = params.get("sessionId") or str(uuid.uuid4()) - send({{"jsonrpc": "2.0", "id": rid, "result": {{"sessionId": sid, "configOptions": []}}}}) - elif method == "session/cancel": - with open(cancel_path, "w", encoding="utf-8") as fh: - fh.write("cancelled") - cancelled.set() - elif method == "session/prompt": - sid = params["sessionId"] - for update in ( - {{"sessionUpdate": "tool_call", "toolCallId": "bg-1", "name": "run_command", "title": "run_command", "rawInput": {{"CommandLine": "sleep 999"}}}}, - {{"sessionUpdate": "tool_call_update", "toolCallId": "bg-1", "name": "run_command", "status": "completed", "rawOutput": "Tool is running as a background task with task id: conv/task-999"}}, - {{"sessionUpdate": "agent_message_chunk", "content": {{"type": "text", "text": "Reply already written"}}}}, - ): - send({{"jsonrpc": "2.0", "method": "session/update", "params": {{"sessionId": sid, "update": update}}}}) - # Hold session/prompt open silently, simulating a hung background task. - elif rid is not None: - send({{"jsonrpc": "2.0", "id": rid, "result": {{}}}}) - -reader() +def send(payload): + sys.stdout.write(json.dumps(payload) + "\\n") + sys.stdout.flush() + +def update(sid, body): + send({{"jsonrpc": "2.0", "method": "session/update", "params": {{"sessionId": sid, "update": body}}}}) + +for raw in sys.stdin: + if not raw.strip(): + continue + msg = json.loads(raw) + method = msg.get("method") + rid = msg.get("id") + params = msg.get("params") or {{}} + if method == "initialize": + send({{"jsonrpc": "2.0", "id": rid, "result": {{"protocolVersion": 1}}}}) + elif method in ("session/new", "session/resume"): + sid = params.get("sessionId") or str(uuid.uuid4()) + send({{"jsonrpc": "2.0", "id": rid, "result": {{"sessionId": sid, "configOptions": []}}}}) + elif method == "session/cancel": + with open(cancel_path, "w", encoding="utf-8") as fh: + fh.write("cancelled") + elif method == "session/prompt": + sid = params["sessionId"] + open_prompts.append(rid) + with open(prompts_path, "a", encoding="utf-8") as fh: + fh.write(sid + "\\n") + if len(open_prompts) == 1: + update(sid, {{"sessionUpdate": "tool_call", "toolCallId": "bg-1", "name": "run_command", "title": "run_command", "rawInput": {{"CommandLine": "sleep 999"}}}}) + update(sid, {{"sessionUpdate": "tool_call_update", "toolCallId": "bg-1", "name": "run_command", "status": "completed", "rawOutput": "Tool is running as a background task with task id: conv/task-999"}}) + update(sid, {{"sessionUpdate": "agent_message_chunk", "content": {{"type": "text", "text": "Reply already written"}}}}) + # Hold the prompt open while the background task runs. + else: + update(sid, {{"sessionUpdate": "agent_message_chunk", "content": {{"type": "text", "text": "Second reply"}}}}) + for held in open_prompts: + send({{"jsonrpc": "2.0", "id": held, "result": {{"stopReason": "end_turn"}}}}) + open_prompts.clear() + elif rid is not None: + send({{"jsonrpc": "2.0", "id": rid, "result": {{}}}}) """ monkeypatch.setattr(AntigravityAcpBackend, "REPLY_QUIET_SECONDS", 0.08) - monkeypatch.setattr(AntigravityAcpBackend, "POST_REPLY_STALL_SECONDS", 0.25) + monkeypatch.setattr(AntigravityAcpBackend, "POST_REPLY_HOLD_SECONDS", 0.25) class _FakeRunner: pass runner = _FakeRunner() process = AntigravityAcpPool.for_runner( - runner, command=(sys.executable, "-u", "-c", hung_bg_server), + runner, command=(sys.executable, "-u", "-c", held_bg_server), ) - backend = AntigravityAcpBackend.for_worker(runner, AcpSessionId("hung-bg")) + backend = AntigravityAcpBackend.for_worker(runner, AcpSessionId("held-bg")) class _StartListener: started_events = (events.OriginalInputStarted(),) @@ -1529,40 +1536,47 @@ def original(self, native_id, text): del native_id, text return True - delivery = SimpleNamespace( - worktree=str(tmp_path), - send_boundary=NO_SEND_BOUNDARY, - input_start=_StartListener(), - inbox=TurnInbox(), - ) + def delivery(): + return SimpleNamespace( + worktree=str(tmp_path), + send_boundary=NO_SEND_BOUNDARY, + input_start=_StartListener(), + inbox=TurnInbox(), + ) + loc = AntigravitySession.fresh_in(tmp_path) thread = NativeThread( - "agy-hung", frozenset(), Checkout(tmp_path), + "agy-held", frozenset(), Checkout(tmp_path), backend=AntigravityAcpBackend, model=DeclaredModel("antigravity/gemini-4-neon"), thinking_level=HighThinkingLevel, session_file=RegistrySessionLocation.from_path(loc.path, tmp_path), ) try: - emitted = await asyncio.wait_for( - _collect_backend_events(backend, thread, "run bg task", delivery), - timeout=5.0, + first = await asyncio.wait_for( + _collect_backend_events(backend, thread, "run bg task", delivery()), timeout=5.0, + ) + second = await asyncio.wait_for( + _collect_backend_events(backend, thread, "next goal turn", delivery()), timeout=5.0, ) finally: await process.shutdown() - phases = [ev.phase for ev in emitted if isinstance(ev, NativePhaseChanged)] + phases = [ev.phase for ev in first if isinstance(ev, NativePhaseChanged)] assert any(isinstance(phase, ReplyingPhase) for phase in phases) bg_phases = [phase for phase in phases if isinstance(phase, BackgroundTaskWaitPhase)] assert bg_phases, f"Expected transition to BackgroundTaskWaitPhase, saw: {phases!r}" assert bg_phases[0].tasks == ("conv/task-999",) assert bg_phases[0].summary == "Waiting on background task (1)" - done_events = [ev for ev in emitted if isinstance(ev, events.Done)] - assert len(done_events) == 1 - assert done_events[0].ok is False - assert isinstance(done_events[0].failure, ModelStalled) - assert "background task" in done_events[0].text - assert cancel_marker.is_file() + assert [(ev.ok, ev.text) for ev in first if isinstance(ev, events.Done)] == [ + (True, "Reply already written") + ] + assert [(ev.ok, ev.text) for ev in second if isinstance(ev, events.Done)] == [ + (True, "Second reply") + ] + assert not cancel_marker.exists() + sessions = prompts_log.read_text(encoding="utf-8").split() + assert len(sessions) == 2 and sessions[0] == sessions[1] async def _collect_backend_events(backend, thread, text, delivery):