The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): a card attempt lost across an owner restart settles interrupted
Tekniumaca73b2f64aa
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 7c2216852e7..509e81a87fe 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -622,11 +622,15 @@ class SessionAuthority:return resultsasync def submit(self, actor: Principal, request: Submission, *, _authorize_write=None, queue_while_restarting=False,- _replay_guard=None):+ _replay_guard=None, _kanban_card=None):"""``queue_while_restarting``: the caller is an interactive client attached to a restart'safter-turn wait, which commits the input queued for the next owner. Machine callers (a2a,kanban, hosted rooms) keep the plain ``runtime_draining`` refusal and retry against the next- owner with their own stable request id; none of them reads a released waiter as queued."""+ owner with their own stable request id; none of them reads a released waiter as queued.++ ``_kanban_card`` is the Kanban dispatcher's trusted producer marker (``session_kanban.run_task``+ only): committed as ``kanban_card_v1``, it lets a card attempt lost across an owner restart+ settle interrupted (#134889 KB-8). Never a payload field: a client cannot supply it."""self.authorize(actor, request.ref, 'session:submit')async with self.sessions[request.ref.session_id].mutation_lock:# Deletion can retire this session while the caller waits on its writer.@@ -634,9 +638,11 @@ class SessionAuthority:from gateway.session_ingress_media import capture_leasewith capture_lease(): # captured bytes are held from capture until commit or refusalreturn await self._submit(actor, request, _authorize_write=_authorize_write,- queue_only=queue_while_restarting is True, _replay_guard=_replay_guard)+ queue_only=queue_while_restarting is True, _replay_guard=_replay_guard,+ _kanban_card=_kanban_card)- async def _submit(self, actor, request, *, _authorize_write=None, queue_only=False, _replay_guard=None):+ async def _submit(self, actor, request, *, _authorize_write=None, queue_only=False, _replay_guard=None,+ _kanban_card=None):self._require_admission_open(queue_only=queue_only)if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {'text', 'attachments', 'finite', 'unattended', 'surface', 'voice_context', 'interrupted',@@ -658,6 +664,8 @@ class SessionAuthority:payload = {'text': request.payload['text'], **finite, **admit_surface(request.payload),**admit_display(request.payload), **admit_cli_turn(request.payload),**admit_attachments(request.payload.get('attachments'), admitted=admitted)}+ if _kanban_card is not None:+ payload['kanban_card_v1'] = _kanban_cardsource = self.sessions[request.ref.session_id].sourceif source is not None and source.user_id != actor.subject:# Durable server authorization, not a client payload field. The originaldiff --git a/gateway/session_kanban.py b/gateway/session_kanban.pyindex 0eb71e59077..8ebea7da0d6 100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@ -141,7 +141,14 @@ async def run_task(connection, params):payload: dict = {'text': f'work kanban task {params["task_id"]}'}if committed is None or 'finite' in committed['payload']:payload['finite'] = True- receipt = await authority.submit(connection.actor, Submission(request_id, ref, payload, 'queue'))+ # The dispatcher's trusted producer marker (#134889 KB-8): nobody waits on a card attempt, so one+ # lost across an owner restart settles interrupted instead of pausing the card session. An+ # attempt main committed without it resubmits unmarked (same digest, original receipt).+ card = None+ if committed is None or 'kanban_card_v1' in committed['payload']:+ card = {'board': context.get('board'), 'task_id': params['task_id'], 'run_id': params['run_id']}+ receipt = await authority.submit(connection.actor, Submission(request_id, ref, payload, 'queue'),+ _kanban_card=card)return {'session_id': ref.session_id, 'receipt': asdict(receipt)}diff --git a/gateway/session_operator.py b/gateway/session_operator.pyindex 40d411e755b..37e91ac50fd 100644--- a/gateway/session_operator.py+++ b/gateway/session_operator.py@@ -9,7 +9,7 @@ from hermes_state_runtime import RuntimeStoreError# Fields ``SessionAuthority.submit`` commits for a local session's input; producers commit their own envelope.LOCAL_INPUT_FIELDS = frozenset({'text', 'attachments_v1', 'finite', 'unattended', 'surface_v1', 'display_v1',- 'cli_turn_v1'})+ 'cli_turn_v1', 'kanban_card_v1'})def is_viewer_input(row):diff --git a/gateway/session_unattended_unknown.py b/gateway/session_unattended_unknown.pyindex a5587ce89f1..f60b77e420e 100644--- a/gateway/session_unattended_unknown.py+++ b/gateway/session_unattended_unknown.py@@ -4,7 +4,7 @@ A turn lost across an owner restart is fenced ``unknown`` and pauses its sessiononly 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``, a native envelope's ``automation`` block) or a webhook delivery-(``webhook_delivery``). Pausing on it stalls every message queued behind it until an operator+(``webhook_delivery``) or a Kanban card attempt (``kanban_card_v1``, set by the dispatcher). Pausing on it stalls every message queued behind it until an operatornotices (a Bot Chat sat ten hours behind one).Such a row settles through the same fenced resolution a person's Discard uses@@ -28,7 +28,10 @@ def is_unattended(row) -> bool:payload = row.get('payload') or {}native = payload.get('native_text_v1') or {}# A webhook delivery: the provider already got its 202 and nobody can be asked to resend it.- return 'local_automation_v1' in payload or 'automation' in native or 'webhook_delivery' in native+ # A Kanban card attempt (#134889 KB-8): the dispatcher's marker, committed only by+ # ``SessionAuthority.submit(_kanban_card=...)``; a card row main minted without it still pauses.+ return ('local_automation_v1' in payload or 'kanban_card_v1' in payload+ or 'automation' in native or 'webhook_delivery' in native)def _unattended_unknown(rows):diff --git a/tests/gateway/fixtures/kanban_recovery_probe.py b/tests/gateway/fixtures/kanban_recovery_probe.pyindex 727e268176d..721d1b82c11 100644--- a/tests/gateway/fixtures/kanban_recovery_probe.py+++ b/tests/gateway/fixtures/kanban_recovery_probe.py@@ -138,7 +138,9 @@ def main():(owner / 'config.yaml').write_text(json.dumps(cfg))with daemon(root, owner, env, barrier=False) as (proc, desc):answer = asyncio.run(retry(desc, params))- assert answer['receipt']['status'] == 'unknown', answer+ # #134889 KB-8: nobody waits on a card attempt, so the lost turn settles+ # interrupted at boot (never replayed) instead of pausing the card session.+ assert (answer['receipt']['status'], answer['receipt']['outcome']) == ('terminal', 'interrupted'), answerassert answer['session_id'] == first['target_session_id']with closing(sqlite3.connect((owner / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:frozen = json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',diff --git a/tests/gateway/test_kanban_finite_admission.py b/tests/gateway/test_kanban_finite_admission.pyindex e6d9920cbb3..c9d524ddc1b 100644--- a/tests/gateway/test_kanban_finite_admission.py+++ b/tests/gateway/test_kanban_finite_admission.py@@ -45,7 +45,7 @@ def test_kanban_submission_enters_single_query_approval_context(tmp_path, monkeymonkeypatch.setattr('gateway.session_ingress.execute_admission', execute)- async def submit(actor, submission):+ async def submit(actor, submission, **kwargs):await execute_finite_admission(authority, ref, {'admission_id': 'admission', 'payload': submission.payload})return AdmissionReceipt('admission', ref, 1, 'queued', None, 1, None)@@ -160,8 +160,8 @@ def test_retry_of_pre_finite_kanban_admission_returns_original_receipt(kanban_owauthority = owner.authorityreal_submit = authority.submit- async def pre_finite_submit(actor, submission):- # The payload run_task committed before this change: no finite flag.+ async def pre_finite_submit(actor, submission, **kwargs):+ # The payload run_task committed before this change: no finite flag (and no card marker).payload = {k: v for k, v in submission.payload.items() if k != 'finite'}return await real_submit(actor, type(submission)(submission.request_id, submission.ref, payload, submission.intent))@@ -206,3 +206,96 @@ def test_admission_lookup_matches_only_the_exact_durable_key(kanban_owner):await owner.close()asyncio.run(scenario())+++def _lose_across_restart(authority, sid):+ """Claim the card's admission under this owner, then a new owner epoch boots on the same store+ and runs the real boot recovery (fence ``unknown``, then settle the unattended ones)."""+ from gateway.session_unattended_unknown import settle_recovered_unattended+ from hermes_state_runtime import (begin_runtime_epoch, claim_session_input, list_session_admissions,+ recover_session_inputs)+ db = authority.db+ claimed = claim_session_input(db, epoch=authority.epoch, session_id=sid)+ assert claimed and claimed['status'] == 'started'+ epoch = begin_runtime_epoch(db, instance_id='owner-2')+ assert recover_session_inputs(db, epoch=epoch) == 1+ settle_recovered_unattended(db, epoch)+ [row] = list_session_admissions(db, session_id=sid, pending_only=False)+ return row+++def test_kanban_card_fenced_unknown_across_owner_epochs_settles_interrupted(kanban_owner):+ """#134889 KB-8: a card attempt lost across an owner restart has nobody to resend it; the+ dispatcher's trusted marker makes boot recovery settle it interrupted instead of pausing."""+ from gateway.session_kanban import run_task++ owner = kanban_owner(_CONFIG)++ async def scenario():+ try:+ sid = (await run_task(owner.connection, owner.params))['session_id']+ row = _lose_across_restart(owner.authority, sid)+ assert (row['status'], row['outcome']) == ('terminal', 'interrupted'), row+ notices = [m['content'] for m in owner.authority.db.get_messages(sid)+ if m.get('display_kind') == 'failed_turn']+ assert notices and 'automat' in notices[0].lower(), notices+ finally:+ await owner.close()++ asyncio.run(scenario())+++def test_card_admitted_before_the_marker_keeps_pausing_and_retries_cleanly(kanban_owner, monkeypatch):+ """Upgrade compat: an attempt main committed without the marker resubmits its exact payload on+ retry (original receipt, no admission_conflict) and keeps today's pause when lost."""+ from gateway.session_kanban import run_task++ owner = kanban_owner(_CONFIG)+ authority = owner.authority+ real_submit = authority.submit++ async def unmarked_submit(actor, submission, **kwargs):+ kwargs.pop('_kanban_card', None) # the admission main committed: no producer marker+ return await real_submit(actor, submission, **kwargs)++ async def scenario():+ try:+ monkeypatch.setattr(authority, 'submit', unmarked_submit)+ first = await run_task(owner.connection, owner.params)+ monkeypatch.setattr(authority, 'submit', real_submit)+ assert await run_task(owner.connection, owner.params) == first+ row = _lose_across_restart(authority, first['session_id'])+ assert row['status'] == 'unknown', row+ finally:+ await owner.close()++ asyncio.run(scenario())+++def test_a_client_cannot_mint_the_kanban_card_marker(kanban_owner):+ """The marker is the dispatcher's, never a client payload field: session.submit and the+ authority's public payload both refuse it, so a person's turn can't opt out of the pause."""+ from gateway.session_contract import Submission+ from gateway.session_kanban import run_task+ from hermes_state_runtime import RuntimeStoreError++ owner = kanban_owner(_CONFIG)+ authority = owner.authority++ async def scenario():+ try:+ sid = (await run_task(owner.connection, owner.params))['session_id']+ from gateway.session_contract import SessionRef+ ref = SessionRef(authority.profile_id, sid)+ forged = {'text': 'x', 'kanban_card_v1': {'task_id': owner.params['task_id'], 'run_id': owner.params['run_id']}}+ with pytest.raises(RuntimeStoreError) as refused:+ await authority.submit(owner.connection.actor, Submission('forged', ref, forged, 'queue'))+ assert refused.value.reason == 'invalid_params'+ with pytest.raises(RuntimeStoreError) as refused:+ owner.connection.subscriptions[sid] = object()+ owner.connection.submission(ref, {'session_id': sid, 'submission_id': 'f2', **forged})+ assert refused.value.reason == 'invalid_params'+ finally:+ await owner.close()++ asyncio.run(scenario())diff --git a/tests/gateway/test_session_kanban.py b/tests/gateway/test_session_kanban.pyindex a3b3f8e5969..b6af6174d63 100644--- a/tests/gateway/test_session_kanban.py+++ b/tests/gateway/test_session_kanban.py@@ -131,7 +131,7 @@ def test_claim_reclaimed_before_admission_marker_is_refused(tmp_path, monkeypatckb.claim_task(conn, task_id)return SimpleNamespace(session_id='owner-session', profile_id=str(tmp_path))monkeypatch.setattr('gateway.session_local.create_local_session', create_local_session)- async def submit(actor, submission):+ async def submit(actor, submission, **kwargs):calls.append(('submit', submission))async def resume(ref, params):calls.append(('resume', ref))diff --git a/tests/gateway/test_session_kanban_run_off_loop.py b/tests/gateway/test_session_kanban_run_off_loop.pyindex 44614233174..7d93095903c 100644--- a/tests/gateway/test_session_kanban_run_off_loop.py+++ b/tests/gateway/test_session_kanban_run_off_loop.py@@ -38,7 +38,7 @@ def test_run_task_kanban_write_never_blocks_the_loop(tmp_path, monkeypatch):session_id='owner-session', profile_id=str(tmp_path)))calls = []- async def submit(actor, submission):+ async def submit(actor, submission, **kwargs):calls.append('submit')return SimpleNamespace(admission_id='a')