Skip to content

The agent that grows with you

fix(gateway): resolving an unknown turn commits the answer this owner captured

Teknium21e58810862a
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 9812c85c531..1e316c71e20 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -477,17 +477,36 @@ class SessionAuthority:
self._schedule(ref)
async def resolve_unknown(self, actor, ref, admission_id, generation):
- """Operator acknowledgement that a turn lost across an owner restart will not
- finish; the paused FIFO behind it resumes. Never requeues the lost input."""
+ """Operator acknowledgement that an ``unknown`` turn will not finish; the paused FIFO behind
+ it resumes. Never requeues the input. A turn that finished in THIS owner but whose
+ settlement write failed (its exact result is still in ``pending_results``) commits that
+ result instead of discarding it: the answer was produced, only its receipt was lost."""
self.authorize(actor, ref, 'session:control')
- await self.receipt(actor, ref, admission_id)
+ before = await self.receipt(actor, ref, admission_id)
+ captured = self.pending_results.get(admission_id)
+ prepared = None
+ if captured is not None and before.status == 'unknown':
+ from gateway.session_results import prepare_result
+ row = get_session_admission(self.db, admission_id=admission_id)
+ prepared = prepare_result(row, captured['result'].get('final_response') or '', 'completed', captured)
# The transcript boundary commits WITH the terminal transition: a follower can never be
- # claimed with the discarded text left open to be merged into its request.
+ # claimed with the discarded text left open to be merged into its request. With a captured
+ # result the answer is normally already the transcript tail, so the closer is a no-op.
from gateway.session_results import close_discarded_turn
row = resolve_unknown_session_input(self.db, epoch=self.epoch, admission_id=admission_id,
- generation=generation,
+ generation=generation, _captured=prepared,
_terminal_write=lambda conn, lost: close_discarded_turn(self.db, conn, lost))
self.pending_results.pop(admission_id, None)
+ if prepared is not None and row['owner_epoch'] == self.epoch:
+ # The captured result committed: viewers told the turn is unknown get its completion,
+ # unless the drain still owns the claim (resolution raced its recovery stamp) and
+ # publishes the committed result itself.
+ from gateway.session_settlement_recovery import _publish_completion
+ live = self.sessions[ref.session_id]
+ with live.event_stream.lock:
+ if live.event_stream.execution.get('admission_id') != admission_id:
+ _publish_completion(self, live, ref, row, row,
+ captured['result'].get('final_response') or '', captured)
# Its own write txn + unlink, so it runs after the resolution commits; a discarded image
# would otherwise stay on disk forever (the drain releases only settled turns).
from gateway.session_ingress_media import release_admission_media
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 4800f7ebc3c..cdf86dd143b 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -378,24 +378,40 @@ def import_legacy_session_admissions(db, *, epoch: int, source_path, principal_i
def resolve_unknown_session_input(db, *, epoch: int, admission_id: str, generation: int,
- _terminal_write=None) -> dict:
+ _terminal_write=None, _captured=None) -> dict:
"""Explicit operator acknowledgement; resolves uncertainty, never requeues it.
``_terminal_write(conn, row)`` is the owner's same-transaction effect (the discarded turn's
transcript boundary): it must not commit, may run again on SQLite retry, and raising rolls
- the whole resolution back, so the FIFO can never advance past an unclosed lost turn."""
+ the whole resolution back, so the FIFO can never advance past an unclosed lost turn.
+ ``_captured=(outcome, stored_result)`` is the exact result this owner captured for the turn
+ before its settlement write failed; it commits with the resolution (only for an ``unknown``
+ row stamped by this same owner epoch), so the finished answer is not thrown away."""
+ from hermes_state_terminal import RESULT_PREFIX
def write(conn):
_epoch(conn, epoch)
row = _admission(conn, admission_id)
- if (type(generation) is int and row['generation'] == generation
- and row['status'] == 'terminal' and row['outcome'] == 'interrupted'):
+ if (type(generation) is int and row['generation'] == generation and row['status'] == 'terminal'
+ and (row['outcome'] == 'interrupted' or conn.execute(
+ 'SELECT 1 FROM state_meta WHERE key=?', (RESULT_PREFIX + admission_id,)).fetchone())):
return _row(row)
if type(generation) is not int or row['status'] != 'unknown' or row['generation'] != generation:
raise RuntimeStoreError('stale_generation')
+ outcome = 'interrupted'
+ if _captured is not None and row['owner_epoch'] == epoch:
+ outcome, stored = _captured
+ if outcome not in ('completed', 'interrupted', 'failed'):
+ raise RuntimeStoreError('invalid_params')
+ from hermes_state_terminal import compact_result
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '
+ 'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
+ (RESULT_PREFIX + admission_id, _json(compact_result(
+ stored, user_message=json.loads(row['payload_json']).get('text')))))
if _terminal_write is not None:
_terminal_write(conn, row)
_retire_admission_workers(conn, row, row['owner_epoch'])
- conn.execute("UPDATE session_admissions SET status='terminal',outcome='interrupted' WHERE admission_id=?", (admission_id,))
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome=? WHERE admission_id=?",
+ (outcome, admission_id))
conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
return _row(_admission(conn, admission_id))
return db._execute_write(write)
diff --git a/tests/gateway/test_live_settlement_recovery.py b/tests/gateway/test_live_settlement_recovery.py
index 73041f39d5a..2dd93c8b71f 100644
--- a/tests/gateway/test_live_settlement_recovery.py
+++ b/tests/gateway/test_live_settlement_recovery.py
@@ -54,6 +54,14 @@ async def test_failed_commit_retains_result_and_releases_fifo_for_explicit_disca
assert not any(frame['params']['type'] == 'message.complete' for frame in frames)
await authority.resolve_unknown(ACTOR, REF, head.admission_id, row['generation'])
assert head.admission_id not in authority.pending_results
+ # The answer was produced in this owner; only its receipt write failed. Resolution
+ # commits that exact result instead of discarding it, and viewers get its completion.
+ from gateway.session_results import admission_result
+ resolved = get_session_admission(db, admission_id=head.admission_id)
+ assert (resolved['status'], resolved['outcome']) == ('terminal', 'completed')
+ assert admission_result(db, head.admission_id)['result']['final_response'] == 'head done'
+ complete, = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']
+ assert (complete['admission_id'], complete['text']) == (head.admission_id, 'head done')
await asyncio.wait_for(authority._drain(REF), 5)
assert calls == ['head', 'follower']
assert get_session_admission(db, admission_id=follower.admission_id)['status'] == 'terminal'