Skip to content

The agent that grows with you

fix(gateway): settle a lost automation turn as interrupted instead of pausing the FIFO

Tekniumd4220ab52206
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
index 8ff6a690faa..6239ef93e0f 100644
--- a/agent/turn_failure_copy.py
+++ b/agent/turn_failure_copy.py
@@ -43,6 +43,12 @@ PARTIAL_FAILED_TURN_NOTICE = (
"This turn did not complete. Some actions may already have run; verify their effects "
"before resending."
)
+# A turn no person sent (a cron run, a process completion) lost across a gateway restart: it
+# settles interrupted and is never re-run, so nobody is asked to resend it (#134889 GW-10).
+AUTOMATION_INTERRUPTED_NOTICE = (
+ "An automated delivery was interrupted when Hermes restarted and was not run again. Some "
+ "actions may already have run; verify their effects."
+)
# ``messages.display_kind`` of that row: display-only (stripped before every provider request),
# so renderers show a Hermes notice and room pollers never read it as the model's reply.
FAILED_TURN_DISPLAY_KIND = "failed_turn"
@@ -52,7 +58,7 @@ def untyped_failed_turn_display_kind(role: Any, content: Any) -> Optional[str]:
"""``FAILED_TURN_DISPLAY_KIND`` for a boundary row persisted before the closers typed it
(exact notice text, so a real reply quoting it stays a reply); read-side only."""
if role == "assistant" and isinstance(content, str) and content.strip() in (
- FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE,
+ FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE, AUTOMATION_INTERRUPTED_NOTICE,
):
return FAILED_TURN_DISPLAY_KIND
return None
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 938a696ac67..3a8977465d9 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -789,9 +789,10 @@ class SessionAuthority:
await self.receipt(actor, ref, admission_id)
return await self.resolve_unknown_as_owner(ref, admission_id, generation)
- async def resolve_unknown_as_owner(self, ref, admission_id, generation):
+ async def resolve_unknown_as_owner(self, ref, admission_id, generation, *, notice=None):
"""``resolve_unknown`` past authorization: also the owner's own call when the last viewer
- closed a session whose turn recovered ``unknown`` (gateway/session_viewer_close)."""
+ closed a session whose turn recovered ``unknown`` (gateway/session_viewer_close), or when an
+ unattended automation turn settles itself (``notice``: its transcript copy, GW-10)."""
captured = self.pending_results.get(admission_id)
before = get_session_admission(self.db, admission_id=admission_id)
prepared = None
@@ -807,7 +808,7 @@ class SessionAuthority:
return await tracked_write(self, partial(
resolve_unknown_session_input, self.db, epoch=self.epoch, admission_id=admission_id,
generation=generation, _captured=prepared,
- _terminal_write=lambda conn, lost: close_discarded_turn(self.db, conn, lost)),
+ _terminal_write=lambda conn, lost: close_discarded_turn(self.db, conn, lost, notice)),
then=partial(self._resolved_unknown, ref, admission_id, prepared, captured))
async def _resolved_unknown(self, ref, admission_id, prepared, captured, row):
@@ -1084,6 +1085,12 @@ class SessionAuthority:
try:
row, first = await self._claim_next(ref, live)
except RuntimeStoreError as exc:
+ if exc.reason == 'unknown_execution':
+ # An automation turn nobody is waiting on settles interrupted (GW-10); only a
+ # person's lost turn keeps the FIFO paused for them to resolve.
+ from gateway.session_unattended_unknown import settle_unattended_unknown
+ if await settle_unattended_unknown(self, ref):
+ continue
import logging
logging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)
self._pause(ref, exc.reason)
@@ -1320,6 +1327,9 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=No
epoch = await asyncio.to_thread(begin_runtime_epoch, db, instance_id=instance_id)
# Hot-serve builds a profile while the loop serves the others: both writes stay off it.
await asyncio.to_thread(recover_session_inputs, db, epoch=epoch)
+ # A lost automation turn has nobody to resolve it: it settles interrupted before any FIFO runs.
+ from gateway.session_unattended_unknown import settle_recovered_unattended
+ await asyncio.to_thread(settle_recovered_unattended, db, epoch)
await asyncio.to_thread(backfill_legacy_session_owners, db)
authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)
# A receipt's compression catch-up (#140060) writes: it commits off the loop too, before the
diff --git a/gateway/session_results.py b/gateway/session_results.py
index 9bcf86dcb40..13b8ab653ab 100644
--- a/gateway/session_results.py
+++ b/gateway/session_results.py
@@ -99,7 +99,7 @@ def admission_result(db, admission_id):
return load_result(saved[0]) if saved else None
-def close_discarded_turn(db, conn, row):
+def close_discarded_turn(db, conn, row, notice=None):
"""Close a discarded ``unknown`` turn the way a failed turn is closed, on the resolution's
own transaction (``resolve_unknown_session_input(_terminal_write=...)``).
@@ -113,7 +113,10 @@ def close_discarded_turn(db, conn, row):
A turn lost while parked on a tool (an approval or clarify prompt) ends on its assistant
``tool_calls`` row with no result. That tail is open too: repair prunes the unanswered call,
drops the now-empty row and merges the discarded input into the follower's user turn, so it
- gets the same boundary (merged onto the call row, whose calls are then pruned)."""
+ gets the same boundary (merged onto the call row, whose calls are then pruned).
+
+ ``notice`` (an unattended automation turn settled by the owner, GW-10) replaces the hedged copy
+ and is written even on a closed tail: nobody resolved it, so the transcript must say why."""
import time
from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, PARTIAL_FAILED_TURN_NOTICE
from hermes_state_local_lineage import local_physical_target
@@ -121,9 +124,10 @@ def close_discarded_turn(db, conn, row):
target = _canonical_chain(conn, local_physical_target(conn, row['target_session_id']))[-1]
tail = conn.execute("SELECT role, tool_calls FROM messages WHERE session_id=? AND active=1 "
"AND role NOT IN ('session_meta','system') ORDER BY id DESC LIMIT 1", (target,)).fetchone()
- if tail is None or not (tail[0] == 'user' or (tail[0] == 'assistant' and tail[1] not in (None, '', '[]'))):
+ if notice is None and (tail is None or not (
+ tail[0] == 'user' or (tail[0] == 'assistant' and tail[1] not in (None, '', '[]')))):
return False
db._append_messages_in_transaction(conn, target, [{
- 'role': 'assistant', 'content': PARTIAL_FAILED_TURN_NOTICE, 'timestamp': time.time(),
+ 'role': 'assistant', 'content': notice or PARTIAL_FAILED_TURN_NOTICE, 'timestamp': time.time(),
'display_kind': FAILED_TURN_DISPLAY_KIND}])
return True
diff --git a/gateway/session_unattended_unknown.py b/gateway/session_unattended_unknown.py
new file mode 100644
index 00000000000..2c82452d1aa
--- /dev/null
+++ b/gateway/session_unattended_unknown.py
@@ -0,0 +1,79 @@
+"""An ``unknown`` turn nobody is waiting on settles as interrupted (#134889 GW-10, #139532).
+
+A turn lost across an owner restart is fenced ``unknown`` and pauses its session's FIFO, because
+only the person who sent it knows whether to resend it. An automation delivery has no such person:
+a cron run (``CRON_PRINCIPAL_ID``), a process completion or heartbeat (``automation:<route>``,
+``local_automation_v1``, or a native envelope's ``automation`` block). Pausing on it stalls every
+message queued behind it until an operator notices (a Bot Chat sat ten hours behind one).
+
+Such a row settles through the same fenced resolution a person's Discard uses
+(``resolve_unknown_session_input``): terminal ``interrupted``, never requeued or replayed, with a
+Hermes transcript notice committed in the same transaction. No second recovery store.
+"""
+from __future__ import annotations
+
+import logging
+
+from hermes_state_keys import CRON_PRINCIPAL_ID
+
+logger = logging.getLogger(__name__)
+
+
+def is_unattended(row) -> bool:
+ """True for an admission no person submitted (so nobody can be asked to resend it)."""
+ principal = row.get('principal_id') or ''
+ if principal == CRON_PRINCIPAL_ID or principal.startswith('automation:'):
+ return True
+ payload = row.get('payload') or {}
+ return 'local_automation_v1' in payload or 'automation' in (payload.get('native_text_v1') or {})
+
+
+def _unattended_unknown(rows):
+ return [row for row in rows if row['status'] == 'unknown' and is_unattended(row)]
+
+
+def settle_recovered_unattended(db, epoch) -> int:
+ """Boot recovery, right after ``recover_session_inputs`` fenced lost turns ``unknown`` and before
+ any FIFO is scheduled: settle every unattended one. Synchronous; runs off the owner loop."""
+ from agent.turn_failure_copy import AUTOMATION_INTERRUPTED_NOTICE
+ from gateway.session_ingress_media import release_admission_media
+ from gateway.session_results import close_discarded_turn
+ from hermes_state_runtime import RuntimeStoreError, _row, resolve_unknown_session_input
+ with db._read_ctx() as conn:
+ rows = [_row(r) for r in conn.execute(
+ "SELECT * FROM session_admissions WHERE status='unknown' ORDER BY seq").fetchall()]
+ settled = 0
+ for row in _unattended_unknown(rows):
+ try:
+ resolve_unknown_session_input(
+ db, epoch=epoch, admission_id=row['admission_id'], generation=row['generation'],
+ _terminal_write=lambda conn, lost: close_discarded_turn(db, conn, lost, AUTOMATION_INTERRUPTED_NOTICE))
+ except RuntimeStoreError as exc:
+ logger.warning('Lost automation admission %s left unknown: %s', row['admission_id'], exc.reason)
+ continue
+ release_admission_media(db, row['admission_id'])
+ settled += 1
+ logger.info('Lost automation admission %s on session %s settled interrupted (not replayed)',
+ row['admission_id'], row['target_session_id'])
+ return settled
+
+
+async def settle_unattended_unknown(authority, ref) -> bool:
+ """The drain found an ``unknown`` head (fenced in this owner, e.g. a lost managed worker):
+ settle the unattended ones through the owner's resolution. True when any settled, so the
+ drain re-reads its FIFO instead of pausing; a person's ``unknown`` row still pauses it."""
+ import asyncio
+
+ from agent.turn_failure_copy import AUTOMATION_INTERRUPTED_NOTICE
+ from hermes_state_runtime import RuntimeStoreError, list_session_admissions
+ rows = await asyncio.to_thread(list_session_admissions, authority.db, session_id=ref.session_id)
+ settled = False
+ for row in _unattended_unknown(rows):
+ try:
+ await authority.resolve_unknown_as_owner(ref, row['admission_id'], row['generation'],
+ notice=AUTOMATION_INTERRUPTED_NOTICE)
+ except RuntimeStoreError as exc:
+ logger.warning('Lost automation admission %s left unknown: %s', row['admission_id'], exc.reason)
+ continue
+ settled = True
+ return settled
diff --git a/tests/gateway/test_unknown_automation_settles.py b/tests/gateway/test_unknown_automation_settles.py
new file mode 100644
index 00000000000..bec6e12d6bd
--- /dev/null
+++ b/tests/gateway/test_unknown_automation_settles.py
@@ -0,0 +1,160 @@
+"""GW-10 (#139532): an ``unknown`` admission no person is waiting on settles as interrupted.
+
+A turn lost across an owner restart is fenced ``unknown`` and pauses the session's FIFO until a
+person resolves it, because only they know whether to resend it. An automation delivery (a cron
+run, a ``local_automation_v1`` completion, a native automation envelope) has nobody to ask: it
+settles ``interrupted`` (never replayed), the transcript gets a notice, and the FIFO moves on.
+Real ``SessionStore`` SQLite, two real owner epochs; no store monkeypatching.
+"""
+import queue
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform
+from gateway.session import SessionSource, SessionStore
+from gateway.session_authority import LiveSession, initialize_session_authority
+from gateway.session_contract import SessionRef, Submission
+from gateway.session_controls import AuthorityConnection
+from hermes_state_keys import CRON_PRINCIPAL_ID
+from hermes_state_runtime import admit_session_input, claim_session_input, list_session_admissions
+from tests.waiting import async_wait_until
+
+
+class Peer:
+ def __init__(self):
+ self.frames = queue.Queue()
+
+ def write(self, frame):
+ self.frames.put(frame)
+ return True
+
+
+def _runner(tmp_path, monkeypatch, executed):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+
+ async def answer(event):
+ from gateway.session_results import execution_result
+ executed.append(event.text)
+ execution_result.get()['result'] = {'final_response': 'ACK_' + event.text, 'completed': True, 'messages': []}
+ return 'ACK_' + event.text
+
+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,
+ _handle_message=answer, _adapter_for_source=lambda source: None)
+ return store, runner
+
+
+async def _lost_head_then_restart(tmp_path, monkeypatch, executed, admit_head):
+ """Owner 1 admits a head (via ``admit_head``) and a person's follower, claims the head, dies.
+ Owner 2 starts on the same store. Returns (store, owner2, head_id, follower_id)."""
+ store, runner = _runner(tmp_path, monkeypatch, executed)
+ db = store._db
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='gw10')
+ db.create_session('s', source='telegram')
+ first = await initialize_session_authority(runner, profile_id='p', instance_id='owner-1')
+ first.sessions['s'] = LiveSession(source, 's')
+ ref = SessionRef('p', 's')
+ actor = AuthorityConnection(first, Peer(), {'user_id': 'human'}).actor
+ first._schedule = lambda ref: None
+ head_id = await admit_head(first, actor, ref)
+ follower = await first.submit(actor, Submission('follower', ref, {'text': 'FOLLOWER'}, 'queue'))
+ claimed = claim_session_input(db, epoch=first.epoch, session_id='s')
+ assert claimed['admission_id'] == head_id
+ db.append_message('s', 'user', 'HEAD') # the lost turn got as far as its user row
+ second = await initialize_session_authority(runner, profile_id='p', instance_id='owner-2')
+ second.sessions['s'] = LiveSession(source, 's')
+ return store, second, head_id, follower.admission_id
+
+
+async def _automation_head(authority, _actor, _ref):
+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id='automation:agent:main:telegram:dm:gw10',
+ session_id='s', request_id='completion-1',
+ payload={'text': 'HEAD', 'local_automation_v1': {'identity': 'proc-1', 'owner': 's'}})
+ return row['admission_id']
+
+
+async def _cron_head(authority, _actor, _ref):
+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id=CRON_PRINCIPAL_ID,
+ session_id='s', request_id='cron:job:exec-1', payload={'text': 'HEAD'})
+ return row['admission_id']
+
+
+async def _person_head(authority, actor, ref):
+ receipt = await authority.submit(actor, Submission('head', ref, {'text': 'HEAD'}, 'queue'))
+ return receipt.admission_id
+
+
+def _statuses(db):
+ return {r['admission_id']: (r['status'], r['outcome'])
+ for r in list_session_admissions(db, session_id='s', pending_only=False)}
+
+
[email protected]('admit_head', [_automation_head, _cron_head], ids=['local_automation_v1', 'cron'])
+async def test_unknown_automation_settles_interrupted_and_fifo_moves_on(tmp_path, monkeypatch, admit_head):
+ executed = []
+ store, authority, head_id, follower_id = await _lost_head_then_restart(tmp_path, monkeypatch, executed, admit_head)
+ try:
+ # The restart settled the lost automation turn: terminal/interrupted, never `unknown`.
+ assert _statuses(authority.db)[head_id] == ('terminal', 'interrupted')
+ authority._schedule(SessionRef('p', 's'))
+ live = authority.sessions['s']
+ await async_wait_until(lambda: live.task is not None and live.task.done(), what='drain finished')
+ # The follower ran exactly once; the automation input was never replayed.
+ assert executed == ['FOLLOWER']
+ assert _statuses(authority.db)[follower_id] == ('terminal', 'completed')
+ # A Hermes notice in the transcript says the automated delivery was interrupted.
+ messages = authority.db.get_messages('s')
+ notices = [m for m in messages if m.get('display_kind') == 'failed_turn']
+ assert notices and 'automat' in notices[0]['content'].lower(), messages
+ finally:
+ store.close_all_db_handles()
+
+
+async def test_a_persons_unknown_turn_still_pauses_the_fifo(tmp_path, monkeypatch):
+ executed = []
+ store, authority, head_id, follower_id = await _lost_head_then_restart(tmp_path, monkeypatch, executed, _person_head)
+ try:
+ assert _statuses(authority.db)[head_id] == ('unknown', None)
+ authority._schedule(SessionRef('p', 's'))
+ live = authority.sessions['s']
+ await async_wait_until(lambda: live.task is not None and live.task.done(), what='drain paused')
+ assert executed == []
+ assert _statuses(authority.db)[follower_id] == ('queued', None)
+ finally:
+ store.close_all_db_handles()
+
+
+async def test_automation_fenced_unknown_in_this_owner_settles_on_the_drain(tmp_path, monkeypatch):
+ """The drain path: an automation head this owner fences ``unknown`` (a lost managed worker
+ commits that verdict without a restart) settles on the next claim instead of pausing."""
+ executed = []
+ store, runner = _runner(tmp_path, monkeypatch, executed)
+ db = store._db
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='gw10')
+ db.create_session('s', source='telegram')
+ authority = await initialize_session_authority(runner, profile_id='p', instance_id='owner-1')
+ authority.sessions['s'] = LiveSession(source, 's')
+ ref = SessionRef('p', 's')
+ actor = AuthorityConnection(authority, Peer(), {'user_id': 'human'}).actor
+ authority._schedule = lambda ref: None
+ head_id = await _automation_head(authority, actor, ref)
+ follower = await authority.submit(actor, Submission('follower', ref, {'text': 'FOLLOWER'}, 'queue'))
+ claimed = claim_session_input(db, epoch=authority.epoch, session_id='s')
+ assert claimed['admission_id'] == head_id
+ # The managed-worker verdict: the claimed row is committed ``unknown`` under this same epoch.
+ db._execute_write(lambda c: c.execute("UPDATE session_admissions SET status='unknown' WHERE admission_id=?", (head_id,)))
+ try:
+ del authority._schedule
+ authority._schedule(ref)
+ live = authority.sessions['s']
+ await async_wait_until(lambda: live.task is not None and live.task.done(), what='drain finished')
+ assert executed == ['FOLLOWER']
+ statuses = _statuses(db)
+ assert statuses[head_id] == ('terminal', 'interrupted')
+ assert statuses[follower.admission_id] == ('terminal', 'completed')
+ finally:
+ store.close_all_db_handles()