Skip to content

The agent that grows with you

fix(gateway): a folded completion keeps only its own identity; a finishing job's tick never blocks the fold

Teknium33920f4b2f00
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index cb9b96691d7..f09f3cde3fd 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -491,7 +491,7 @@ class SessionAuthority:
if waiter is not None and not waiter.done():
waiter.set_exception(RuntimeStoreError(reason))
- async def admit_automation(self, adapter, event, identity, replaces=None, fold=False):
+ async def admit_automation(self, adapter, event, identity, replaces=None, fold=None):
from gateway.session_automation import admit_automation
return await admit_automation(self, adapter, event, identity, replaces, fold)
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index da5ed97c5c4..167d9c6db01 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -112,7 +112,7 @@ async def _admit_folded_completion(authority, adapter, event, evt, identity):
_fold_completion(event, waiting, identity)
try:
return await authority.admit_automation(adapter, event, identity, replaces=waiting['admission_id'],
- fold=True)
+ fold=waiting['_skip'])
except RuntimeStoreError as exc:
if exc.reason != 'stale_generation':
raise
@@ -122,13 +122,19 @@ async def _admit_folded_completion(authority, adapter, event, evt, identity):
def _waiting_completion(authority, evt, event):
"""The route's own completion row that is the LAST queued input of the session, or None. Only the
- tail folds: a completion never jumps ahead of, or behind, a prompt queued after it."""
+ tail folds: a completion never jumps ahead of, or behind, a prompt queued after it. The finishing
+ process's own queued liveness ticks do not count as the tail: this completion withdraws them
+ (``withdraw_process_ticks``); their admission ids ride the row as ``_skip`` for the write guard."""
from gateway.session_detached import route_entry
entry = route_entry(authority, str(evt.get('session_key') or ''))
if entry is None:
return None
queued = [row for row in list_session_admissions(authority.db, session_id=_route_owner(authority, entry))
if row['status'] == 'queued']
+ process = str(evt.get('session_id') or '')
+ skip = []
+ while queued and _queued_tick(queued[-1], process, entry.session_key):
+ skip.append(queued.pop()['admission_id'])
tail = queued[-1] if queued else None
if tail is None or tail['principal_id'] != 'automation:' + entry.session_key:
return None
@@ -138,7 +144,7 @@ def _waiting_completion(authority, evt, event):
if (descriptor.get('notification_category', 'result') != event.metadata.get('notification_category', 'result')
or descriptor.get('display_kind') != event.metadata.get('display_kind')):
return None
- return tail
+ return {**tail, '_skip': skip}
_FOLD_HEADER = ('[IMPORTANT: {count} background process results arrived while this session was busy. '
@@ -233,21 +239,24 @@ def _replace_queued(admission_id, session_id, replaced):
_FOLDED_TEXT = '[folded into a later completion batch]'
-def _fold_queued(admission_id, session_id, replaced):
+def _fold_queued(admission_id, session_id, replaced, skip=()):
"""``_replace_queued`` for a completion fold, which must still be the FIFO tail when it commits
- (a prompt admitted since the tail was read keeps the earlier result ahead of it), and whose
- replaced row drops its text: the batch carries it, so each fold must not store it again."""
+ (a prompt admitted since the tail was read keeps the earlier result ahead of it; ``skip`` names
+ the finishing process's ticks, withdrawn right after). The replaced row keeps only its own
+ identity: its text and earlier identities ride the batch, so no fold stores them twice."""
replace = _replace_queued(admission_id, session_id, replaced)
def guard(conn):
row = conn.execute("SELECT seq, payload_json FROM session_admissions WHERE admission_id=? "
"AND target_session_id=? AND status='queued'", (admission_id, session_id)).fetchone()
- if row is None or conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? "
- "AND status='queued' AND seq>?", (session_id, row[0])).fetchone():
+ later = row and conn.execute("SELECT admission_id FROM session_admissions WHERE target_session_id=? "
+ "AND status='queued' AND seq>?", (session_id, row[0])).fetchall()
+ if row is None or any(other[0] not in skip for other in later):
raise RuntimeStoreError('stale_generation')
replace(conn)
payload = json.loads(row[1])
payload['text'] = _FOLDED_TEXT
+ _descriptor(payload).pop('identities', None)
conn.execute('UPDATE session_admissions SET payload_json=? WHERE admission_id=?',
(json.dumps(payload, separators=(',', ':'), ensure_ascii=False), admission_id))
return guard
@@ -593,10 +602,11 @@ def restore_local_automation(authority, ref, row):
return event
-async def admit_automation(authority, adapter, event, identity, replaces=None, fold=False):
+async def admit_automation(authority, adapter, event, identity, replaces=None, fold=None):
"""``replaces``: a queued automation row of the same session this input supersedes (a liveness
tick carrying the output of the one still waiting). Its cancellation commits in this admission's
- own transaction, so neither lands without the other."""
+ own transaction, so neither lands without the other. ``fold``: ``replaces`` is a completion this
+ batch absorbs (``_fold_queued``), given the tick admission ids it may sit behind."""
authority._require_admission_open()
payload, entry = snapshot_automation(authority, adapter, event, identity)
from gateway.session_authority import LiveSession
@@ -620,8 +630,9 @@ async def admit_automation(authority, adapter, event, identity, replaces=None, f
return await tracked_write(authority, partial(
admit_session_input, authority.db, epoch=authority.epoch, principal_id='automation:' + entry.session_key,
session_id=ref.session_id, request_id=identity, payload=deepcopy(payload),
- _authorize_write=authority._admission_gate(replaces and (_fold_queued if fold else _replace_queued)(
- replaces, ref.session_id, replaced))),
+ _authorize_write=authority._admission_gate(replaces and (
+ _replace_queued(replaces, ref.session_id, replaced) if fold is None
+ else _fold_queued(replaces, ref.session_id, replaced, fold)))),
then=admitted, ordered=True, after=partial(authority._schedule_admitted, ref))
diff --git a/tests/gateway/test_completion_fold.py b/tests/gateway/test_completion_fold.py
index d041fc38724..e74eb0f1eb8 100644
--- a/tests/gateway/test_completion_fold.py
+++ b/tests/gateway/test_completion_fold.py
@@ -40,6 +40,13 @@ async def _discord_session(tmp_path, monkeypatch):
'exit_code': 0, 'output': f'{name} output'}
assert await runner._inject_watch_notification(f'[IMPORTANT: {name} finished]', evt) is True
+ async def tick(name):
+ evt = {'type': 'heartbeat', 'session_id': name, 'event_id': f'{name}-tick', 'started_at': 1.0,
+ 'session_key': route, 'parent_session_id': sid, 'platform': 'discord', 'chat_type': 'dm',
+ 'chat_id': '42', 'user_id': '42', 'output': f'{name} still running', 'omitted': 0}
+ assert await runner._inject_watch_notification(f'[IMPORTANT: {name} still running]', evt) is True
+ complete.tick = tick
+
def queued():
return [row for row in list_session_admissions(authority.db, session_id=owner) if row['status'] == 'queued']
def history():
@@ -52,8 +59,10 @@ async def _discord_session(tmp_path, monkeypatch):
async def test_completions_queued_behind_a_turn_fold_into_one_turn(tmp_path, monkeypatch):
authority, _human, complete, queued = await _discord_session(tmp_path, monkeypatch)
try:
- for name in ('proc_a', 'proc_b', 'proc_c'):
- await complete(name)
+ await complete('proc_a')
+ await complete.tick('proc_b') # the finishing process's own tick never blocks the fold
+ await complete('proc_b')
+ await complete('proc_c')
rows = queued()
assert [row['principal_id'].split(':')[0] for row in rows] == ['messaging', 'automation']
text = rows[-1]['payload']['text']
@@ -62,9 +71,12 @@ async def test_completions_queued_behind_a_turn_fold_into_one_turn(tmp_path, mon
assert all(f'{name} finished' in text for name in ('proc_a', 'proc_b', 'proc_c'))
assert text.count('INTERNAL NOTIFICATION') == 1
assert len(rows[-1]['payload']['native_text_v1']['automation']['identities']) == 3
- # Each replaced row drops its text (the batch carries it): storage grows with N, not N^2.
- folded = [row for row in complete.history() if row['outcome'] == 'cancelled']
+ # Each replaced row keeps only its own identity (the batch carries text and identities):
+ # storage grows with N, not N^2.
+ folded = [row for row in complete.history() if row['outcome'] == 'cancelled'
+ and row['request_id'].startswith('["completion"')]
assert [row['payload']['text'] for row in folded] == ['[folded into a later completion batch]'] * 2
+ assert not [row for row in folded if 'identities' in row['payload']['native_text_v1']['automation']]
finally:
authority.db.close()
@@ -79,7 +91,7 @@ async def test_a_prompt_queued_between_completions_keeps_them_apart(tmp_path, mo
await complete('proc_a')
if stale_read:
tail = queued()[-1]
- monkeypatch.setattr(session_automation, '_waiting_completion', lambda *args: tail)
+ monkeypatch.setattr(session_automation, '_waiting_completion', lambda *args: {**tail, '_skip': []})
await human('queued follow-up')
await complete('proc_b')
rows = queued()