Skip to content

The agent that grows with you

fix(gateway): persist a cron session's refusal as the turn's failed boundary

Tekniumbccbae028b0e
diff --git a/gateway/session_results.py b/gateway/session_results.py
index 6eec49c2299..875f48b7c04 100644
--- a/gateway/session_results.py
+++ b/gateway/session_results.py
@@ -88,10 +88,15 @@ def finish_result(db, *, epoch, row, response, outcome, result=None, prepared=No
# in this same write, so a viewer that reconnects after the restart reads why (#134889 GW-21);
# the live ``message.complete.warning`` carries the same copy. A retry that finds the row
# terminal returns above, so the notice is written once.
- from gateway.session_settlement_recovery import owner_stop_notice
- notice = owner_stop_notice(result, outcome, row)
+ # A gateway-owned refusal (a message typed into a cron session) commits its explanation and
+ # error card as the transcript's failed-turn boundary in this same write too: the admission
+ # result is not history, so a reopened chat would otherwise show nothing about the refusal.
+ from gateway.session_settlement_recovery import gateway_refusal_boundary, owner_stop_notice
+ notice, display_metadata = owner_stop_notice(result, outcome, row), None
+ if notice is None and (refusal := gateway_refusal_boundary(result, outcome)) is not None:
+ notice, display_metadata = refusal
write = None if notice is None else (lambda conn, _current: close_discarded_turn(
- db, conn, row, notice, replace_after=row.get('transcript_mark')))
+ db, conn, row, notice, replace_after=row.get('transcript_mark'), display_metadata=display_metadata))
settled = settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],
generation=row['generation'], outcome=outcome, result=stored, _transfers=transfers,
_terminal_write=write)
@@ -108,7 +113,7 @@ def admission_result(db, admission_id):
return load_result(saved[0]) if saved else None
-def close_discarded_turn(db, conn, row, notice=None, *, replace_after=None):
+def close_discarded_turn(db, conn, row, notice=None, *, replace_after=None, display_metadata=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=...)``).
@@ -130,7 +135,10 @@ def close_discarded_turn(db, conn, row, notice=None, *, replace_after=None):
``replace_after`` (the claim's transcript mark, an owner-stop notice): when the tail is a
failed-turn boundary written after that mark, it is THIS turn's own (the agent's core closer
wrote "Send it again" for the interrupted turn), so the notice replaces its copy instead of
- stacking a second boundary (#134889 GW-21). An earlier turn's boundary stays."""
+ stacking a second boundary (#134889 GW-21). An earlier turn's boundary stays.
+
+ ``display_metadata`` (``{error, error_surface}``) rides the boundary so a reopened chat redraws
+ the turn's error card from history (``agent.conversation_loop._failed_turn_display_metadata``)."""
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
@@ -140,12 +148,15 @@ def close_discarded_turn(db, conn, row, notice=None, *, replace_after=None):
"AND role NOT IN ('session_meta','system') ORDER BY id DESC LIMIT 1", (target,)).fetchone()
if (notice is not None and type(replace_after) is int and tail is not None and tail[0] == 'assistant'
and tail[3] == FAILED_TURN_DISPLAY_KIND and tail[2] > replace_after):
- conn.execute("UPDATE messages SET content=?, display_metadata=NULL WHERE id=?", (notice, tail[2]))
+ conn.execute("UPDATE messages SET content=?, display_metadata=? WHERE id=?",
+ (notice, db._encode_display_metadata(display_metadata), tail[2]))
return True
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': notice or PARTIAL_FAILED_TURN_NOTICE, 'timestamp': time.time(),
- 'display_kind': FAILED_TURN_DISPLAY_KIND}])
+ boundary = {'role': 'assistant', 'content': notice or PARTIAL_FAILED_TURN_NOTICE, 'timestamp': time.time(),
+ 'display_kind': FAILED_TURN_DISPLAY_KIND}
+ if display_metadata:
+ boundary['display_metadata'] = display_metadata
+ db._append_messages_in_transaction(conn, target, [boundary])
return True
diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.py
index bb04d7bf6f4..7342e111b19 100644
--- a/gateway/session_settlement_recovery.py
+++ b/gateway/session_settlement_recovery.py
@@ -137,6 +137,16 @@ def owner_stop_notice(captured, outcome, row=None):
return notice
+def gateway_refusal_boundary(captured, outcome):
+ """``(notice, display_metadata)`` for a failed turn the gateway itself refused with a renderable
+ descriptor (``session_cron.execute``: the only producer of ``result.error_surface``), else None."""
+ value = (captured or {}).get('result') or {}
+ surface, error = value.get('error_surface'), value.get('error')
+ if outcome != 'failed' or not isinstance(surface, dict) or not isinstance(error, str) or not error:
+ return None
+ return error, {'error': error, 'error_surface': dict(surface)}
+
+
def _release_media(authority, row):
"""Terminal media cleanup: its own write txn after publication, never under the stream lock."""
try:
diff --git a/tests/gateway/test_cron_admission_error_surface.py b/tests/gateway/test_cron_admission_error_surface.py
index 98108169765..0e4d5bb7b1f 100644
--- a/tests/gateway/test_cron_admission_error_surface.py
+++ b/tests/gateway/test_cron_admission_error_surface.py
@@ -10,19 +10,23 @@ import gateway.session_managed_worker
from gateway.session_authority import SessionAuthority
-async def test_typed_turn_in_cron_session_settles_with_read_only_surface(owner, monkeypatch):
+_SURFACE = {'layer': 'gateway', 'code': 'cron_session_read_only', 'retryable': False}
+
+
+async def _typed_turn_in_cron_session(owner, monkeypatch):
+ """Run a person's message through a cron session's real executor: ``(row, response, outcome, captured)``."""
from cron import scheduler
from gateway.config import Platform
from gateway.session import SessionSource
from gateway.session_contract import SessionRef
from gateway.session_local import LocalSessionAdapter
- from gateway.session_results import prepare_result
- from gateway.session_settlement_recovery import completion_payload
from hermes_state_runtime import admit_session_input, claim_session_input
session_id = 'cron-session'
owner.db.create_session(session_id, source='local')
+ # The job's last fire: the history a reopened chat shows above the refusal.
+ owner.db.append_message(session_id, 'user', 'summarize the inbox')
+ owner.db.append_message(session_id, 'assistant', 'Inbox summary: nothing urgent.')
source = SessionSource(platform=Platform.LOCAL, chat_id=session_id, user_id='cron-user', profile='default')
owner.sessions[session_id] = SimpleNamespace(
source=source, review=None, event_stream=SimpleNamespace(lock=threading.RLock()), subscribers=())
@@ -39,11 +43,44 @@ async def test_typed_turn_in_cron_session_settles_with_read_only_surface(owner,
response, outcome = await SessionAuthority._execute_claimed(
owner, SessionRef('default', session_id), owner.sessions[session_id], row)
+ return row, response, outcome, owner.pending_results[row['admission_id']]
+
- captured = owner.pending_results[row['admission_id']]
+async def test_typed_turn_in_cron_session_settles_with_read_only_surface(owner, monkeypatch):
+ from gateway.session_results import prepare_result
+ from gateway.session_settlement_recovery import completion_payload
+
+ row, response, outcome, captured = await _typed_turn_in_cron_session(owner, monkeypatch)
settled_outcome, _stored = prepare_result(row, response, outcome, captured)
assert settled_outcome == 'failed'
complete = completion_payload(row, {'outcome': settled_outcome}, response, captured)
assert complete['status'] == 'error'
- assert complete['error_surface'] == {'layer': 'gateway', 'code': 'cron_session_read_only', 'retryable': False}
+ assert complete['error_surface'] == _SURFACE
assert 'scheduled job' in complete['text'] and 'Start a new chat' in complete['text']
+
+
+async def test_cron_refusal_is_in_the_reopened_transcript(owner, monkeypatch, tmp_path):
+ """Settlement commits the refusal as a failed-turn boundary carrying its error card, in the same
+ write: a reopened chat redraws the card from history, not from the admission result."""
+ from gateway.session_results import finish_result
+ from hermes_state import SessionDB
+
+ row, response, outcome, captured = await _typed_turn_in_cron_session(owner, monkeypatch)
+ settled, _response = finish_result(owner.db, epoch=owner.epoch, row=row, response=response,
+ outcome=outcome, result=captured)
+ assert settled['outcome'] == 'failed'
+
+ reopened = SessionDB(tmp_path / 'state.db')
+ try:
+ history = reopened.get_messages(row['target_session_id'])
+ finally:
+ reopened.close()
+ assert len(history) == 3, 'the refusal is the turn after the job\'s own exchange'
+ tail = history[-1]
+ assert (tail['role'], tail['display_kind']) == ('assistant', 'failed_turn')
+ assert 'scheduled job' in tail['content']
+ metadata = tail['display_metadata']
+ metadata = json.loads(metadata) if isinstance(metadata, str) else metadata
+ assert metadata == {'error': tail['content'], 'error_surface': _SURFACE}