Skip to content

The agent that grows with you

fix(gateway): an omitted resume resolves its transcript target once, under the stream lock

Teknium0b8bf3bdab6e
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index a14e5fa7283..5f524aa19c9 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -349,12 +349,12 @@ class SessionAuthority:
async def attach(self, actor, ref, *, history=True):
"""Join *ref*'s event stream and snapshot it. ``history=False``: the snapshot carries no transcript
- (``history == ()``), so the compression lineage is never read; for a viewer that pages the
- transcript itself (Desktop over REST) or reads only the prompts and handle."""
+ (``history == ()``), only the physical ``transcript_target``, so the display-row lineage read is
+ skipped; for a viewer that pages the transcript itself (Desktop over REST)."""
self.authorize(actor, ref, 'session:read')
from gateway.session_local_recovery import local_history, prepare_history, transcript_target
- # The lineage read stays off the loop and the lock; without history only the route is restored.
- prepared = await prepare_history(self, ref) if history else (transcript_target(self, ref), None)
+ # The lineage read stays off the loop and the lock; without history the target is resolved under it.
+ prepared = await prepare_history(self, ref) if history else None
from gateway.session_onboarding import keep_from_discard
# The last await before the viewer joins: a fresh launch's claim is taken back with no yield
# before the join, and a delete already past it answers not_found below.
@@ -380,9 +380,13 @@ class SessionAuthority:
active_generation = handle.execution_generation if handle.execution_state == "running" else None
prompts = live.controls.snapshot(ref.session_id, active_generation)
epoch, sequence = live.event_stream.watermark()
- history = self.unless_deleted(ref, lambda: tuple(local_history(self, ref, prepared))) if history else ()
+ if history:
+ history, target = self.unless_deleted(ref, lambda: tuple(local_history(self, ref, prepared))), None
+ else:
+ history, target = (), self.unless_deleted(ref, lambda: transcript_target(self, ref))
snapshot = SubscriptionSnapshot(subscription, handle, epoch, sequence, history,
- tuple(self._pending_receipt(r) for r in pending_rows(self, ref)), prompts)
+ tuple(self._pending_receipt(r) for r in pending_rows(self, ref)), prompts,
+ transcript_target=target)
from gateway.session_viewer_close import cancel_persisted_close
await asyncio.to_thread(cancel_persisted_close, self, ref.session_id) # the viewer cancels it
from gateway.session_deferred_pick import reask_on_attach
diff --git a/gateway/session_contract.py b/gateway/session_contract.py
index c109ac26acf..71107a5f82a 100644
--- a/gateway/session_contract.py
+++ b/gateway/session_contract.py
@@ -80,6 +80,8 @@ class SubscriptionSnapshot:
history: tuple[JsonObject, ...]
pending: tuple[PendingAdmission, ...]
prompts: tuple[JsonObject, ...]
+ # The physical transcript a history-less attach resolved under the stream lock (``history=False``).
+ transcript_target: str | None = None
class SessionAuthority(Protocol):
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 369703898c8..d96ec7c4b80 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -110,18 +110,20 @@ def model_only(row):
return isinstance(metadata, dict) and bool(metadata.get(MODEL_ONLY_DISPLAY_METADATA_KEY))
-async def _resume_transcript(authority, ref, history, omit):
+async def _resume_transcript(authority, ref, snapshot, history, omit):
"""A resume reply's transcript fields. *omit* (``omit_messages``): no rows and ``messages_omitted``, the
- count and the todo plan from bounded reads of the physical tip, as the stdio resume answers it."""
+ stored count and the todo plan of the physical target the attach resolved, as the stdio resume answers
+ it; the display-row lineage read is skipped (the todo lookup still walks the lineage's todo rows)."""
# Its home module, not tui_gateway.server: importing the stdio sidecar points sys.stdout at stderr.
from tui_gateway.tool_progress import _todo_state_from_history
if not omit:
# The newest todo result in the transcript, the snapshot the session's agent hydrates
# from and its ``todo.updated`` frames carried: a viewer attaching shows the plan now.
return {'messages': history, 'message_count': len(history), 'todo_state': _todo_state_from_history(history)}
- from gateway.session_local_recovery import omitted_history_state, transcript_target
- todo_state, count = await asyncio.to_thread(
- omitted_history_state, authority.db, transcript_target(authority, ref))
+ from gateway.session_local_recovery import omitted_history_state
+ # A delete committed since the attach is ``not_found``, as one during the attach is.
+ todo_state, count = await asyncio.to_thread(authority.unless_deleted, ref, partial(
+ omitted_history_state, authority.db, snapshot.transcript_target))
return {'messages': [], 'messages_omitted': True, 'message_count': count, 'todo_state': todo_state}
@@ -675,7 +677,7 @@ class AuthorityConnection:
display['display_messages'] = display_projection(
[row for row in history if not model_only(row)], self.authority.profile_id)
return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,
- **await _resume_transcript(self.authority, ref, history, omit), **display,
+ **await _resume_transcript(self.authority, ref, snapshot, history, omit), **display,
'running': snapshot.handle.execution_state == 'running',
'authority_epoch': snapshot.handle.authority_epoch,
'replay_epoch': snapshot.replay_epoch, 'last_sequence': snapshot.last_sequence,
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index e975e8bc202..99eed5e52a9 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -266,10 +266,13 @@ async def prepare_history(authority, ref):
def omitted_history_state(db, target):
- """``(todo_state, message_count)`` of a resume that omits its transcript: bounded, indexed reads of the
- physical *target* (the newest todo result, the stored count), never the compression lineage."""
+ """``(todo_state, message_count)`` of a resume that omits its transcript: the physical *target*'s stored
+ count and its todo plan. Skips the display-row lineage read; the todo lookup still walks the lineage's
+ todo rows (removed ones included, so an undone plan stays gone)."""
from tui_gateway.tool_progress import _todo_state_from_db
- row = db.get_session(target) or {}
+ row = db.get_session(target)
+ if row is None: # deleted since the attach resolved it
+ raise RuntimeStoreError('not_found')
return _todo_state_from_db(db, target), int(row.get('message_count') or 0)
diff --git a/tests/gateway/test_resume_omit_messages.py b/tests/gateway/test_resume_omit_messages.py
index 879ce5afbaa..7c44d138be8 100644
--- a/tests/gateway/test_resume_omit_messages.py
+++ b/tests/gateway/test_resume_omit_messages.py
@@ -124,3 +124,25 @@ async def test_omitted_resume_reply_passes_the_wire_contract(tmp_path, monkeypat
'params': {'session_id': ref.session_id, 'omit_messages': True}})
assert 'error' not in reply, reply
assert reply['result']['messages'] == [] and reply['result']['messages_omitted'] is True
+
+
+async def test_omitted_resume_racing_a_delete_answers_not_found(tmp_path, monkeypatch):
+ """A delete committing after the attach, before the omitted reply's count/plan read, is ``not_found``."""
+ from gateway.session_controls import AuthorityConnection
+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)
+ _seed_compacted(authority.db, physical)
+ attach = authority.attach
+
+ async def attach_then_delete(*args, **kwargs):
+ snapshot = await attach(*args, **kwargs)
+ for sid in (physical, ref.session_id):
+ authority.db.delete_session(sid)
+ return snapshot
+ monkeypatch.setattr(authority, 'attach', attach_then_delete)
+ conn = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ conn.actor = actor
+ authority.events[actor.transport_id] = object()
+ reply = await conn.dispatch({'jsonrpc': '2.0', 'id': 1, 'method': 'session.resume',
+ 'params': {'session_id': ref.session_id, 'omit_messages': True}})
+ assert reply['error']['data']['reason'] == 'not_found', reply