diff --git a/forks/hermes-agent/gateway/run_startup.py b/forks/hermes-agent/gateway/run_startup.py index f077d300c..830bded13 100644 --- a/forks/hermes-agent/gateway/run_startup.py +++ b/forks/hermes-agent/gateway/run_startup.py @@ -130,17 +130,39 @@ async def _run_startup_resume_event( """Dispatch one synthetic startup resume and wait for its agent turn (inbound stays queued until it finishes, else a user message can race it).""" from gateway.run import _AGENT_PENDING_SENTINEL + cancelled = False try: - await adapter.handle_message(event) + if adapter.platform == Platform.LOCAL: + state = self._peek_session_state(session_key) + if state is not None and state.turn.agent is _AGENT_PENDING_SENTINEL: + self._release_running_agent_state(session_key) + await self._primary_message_handler()(event) + else: + await adapter.handle_message(event) session_tasks = getattr(adapter, "_session_tasks", {}) task = session_tasks.get(session_key) if isinstance(session_tasks, dict) else None if task is not None: await asyncio.shield(task) + except asyncio.CancelledError: + cancelled = True + raise finally: # Release the pre-claimed slot if handle_message raised before _handle_message took ownership. _pre_state = self._peek_session_state(session_key) if (_pre_state.turn.agent if _pre_state else None) is _AGENT_PENDING_SENTINEL: self._release_running_agent_state(session_key) + from gateway.session_authorities import all_authorities, admission_owner + from gateway.session_contract import SessionRef + entry = self.session_store._entries.get(session_key) + if not cancelled and entry is not None: + for authority in all_authorities(self): + owner = await asyncio.to_thread(admission_owner, authority, entry.session_id) + holds = getattr(authority, 'restart_resume_holds', set()) + if owner in holds: + await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute( + "DELETE FROM state_meta WHERE key LIKE 'restart_resume:%' AND value=?", (owner,))) + holds.discard(owner) + authority._schedule(SessionRef(authority.profile_id, owner)) def _queue_startup_restore_event(self, event: MessageEvent) -> None: queue = getattr(self, "_startup_restore_queue", None) @@ -640,20 +662,115 @@ def _resume_owner_authorized(self, session_key: str, source) -> bool: async def _schedule_resume_pending_sessions_async(self, platform=None) -> int: """``_schedule_resume_pending_sessions`` for a coroutine: the held set is read in a worker thread.""" + from gateway.session_authorities import all_authorities, admission_owner + from gateway.session_unattended_unknown import is_unattended, settle_recovered_session + from gateway.run import _auto_continue_freshness_window, _is_fresh_gateway_interruption + from hermes_state_runtime import _row + authorities = all_authorities(self) + with self.session_store._lock: + self.session_store._ensure_loaded_locked() + entries = list(self.session_store._entries.values()) + recovered = {} + markers = {} + for authority in authorities: + try: + rows = await asyncio.to_thread(authority.db._read_all, + "SELECT * FROM session_admissions WHERE status='unknown' AND owner_epoch set: + def _held_resume_sessions(self, authorities, candidates, resumed_admissions=(), resumed_sessions=()) -> set: """Session ids of *candidates* a canonical admission holds (see ``held_admissions``), one read per authority.""" from gateway.session_authorities import held_admissions ids = [entry.session_id for entry in candidates] held: set = set() for authority in authorities: - held |= held_admissions(authority, ids) + held |= held_admissions(authority, ids, resumed_admissions=resumed_admissions, + resumed_sessions=resumed_sessions, resume_pending=True) return held def _still_resume_pending(self, session_key: str) -> bool: diff --git a/forks/hermes-agent/gateway/session_authorities.py b/forks/hermes-agent/gateway/session_authorities.py index 96b503bcf..2d454f1bf 100644 --- a/forks/hermes-agent/gateway/session_authorities.py +++ b/forks/hermes-agent/gateway/session_authorities.py @@ -303,17 +303,8 @@ def holds_admission(authority, session_id) -> bool: 'lineage_json, status, outcome, owner_epoch, generation') -def held_admissions(authority, session_ids) -> set: - """``{id for id in session_ids if holds_admission(authority, id)}``, read in batches. - - The startup resume scan asks this for every candidate, off the loop. It is two batched queries per chunk of - at most ``HELD_ID_CHUNK`` targets, plus a per-id owner lookup (``admission_owner``, one read per id) that - runs first. The per-id reads of ``holds_admission`` are not batched away: ``_restart_interrupted`` still - reads one admission result per interrupted row. The pending query and the latest-decision query are the - two batched reads; the latest decision row is picked in SQL. The answer matches ``holds_admission`` per id, - including the steer-row rule. A retiring store that cannot answer holds every candidate, as - ``holds_admission`` does; a serving store still raises. - """ +def held_admissions(authority, session_ids, *, resumed_admissions=(), resumed_sessions=(), resume_pending=False) -> set: + """Read held sessions in batches, allowing only explicitly resumed admissions.""" ids = list(session_ids) if not ids: return set() @@ -323,12 +314,14 @@ def held_admissions(authority, session_ids) -> set: targets = sorted({t for pair in pairs.values() for t in pair}) pending: set = set() latest: dict = {} + interrupted: set = set(resumed_admissions) for start in range(0, len(targets), HELD_ID_CHUNK): chunk = targets[start:start + HELD_ID_CHUNK] marks = ','.join('?' * len(chunk)) pending.update(row[0] for row in authority.db._read_all( f"SELECT DISTINCT target_session_id FROM session_admissions WHERE target_session_id IN ({marks}) " - "AND status IN ('queued','started','unknown')", chunk)) + + ("AND status IN ('started','unknown')" if resume_pending else + "AND status IN ('queued','started','unknown')"), chunk)) for row in authority.db._read_all( f"SELECT {_HELD_COLUMNS} FROM (" f" SELECT a.*, ROW_NUMBER() OVER (PARTITION BY a.target_session_id ORDER BY a.seq DESC) AS rn" @@ -345,7 +338,9 @@ def held_admissions(authority, session_ids) -> set: continue rows = [latest[t] for t in pairs[sid] if t in latest] newest = max(rows, key=lambda r: r['seq'], default=None) - if newest is not None and not _restart_interrupted(authority, newest): + resumed = any(t in resumed_sessions for t in pairs[sid]) + if newest is not None and newest['admission_id'] not in interrupted and not ( + resume_pending and resumed and newest['status'] == 'queued') and not _restart_interrupted(authority, newest): held.add(sid) return held except Exception as exc: diff --git a/forks/hermes-agent/gateway/session_authority.py b/forks/hermes-agent/gateway/session_authority.py index de6948c96..2f13337ce 100644 --- a/forks/hermes-agent/gateway/session_authority.py +++ b/forks/hermes-agent/gateway/session_authority.py @@ -482,6 +482,8 @@ def _publish_pending(self, ref): wake_bot_receipts(self, ref.session_id) def _schedule(self, ref): + if ref.session_id in getattr(self, 'restart_resume_holds', ()): + return from gateway.session_retirement import restore_retired restore_retired(self, ref.session_id) live = self.sessions[ref.session_id] @@ -912,7 +914,7 @@ async def resolve_unknown(self, actor, ref, admission_id, generation): 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, *, notice=None): + async def resolve_unknown_as_owner(self, ref, admission_id, generation, *, notice=None, restart_resume=False): """``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), or when an unattended automation turn settles itself (``notice``: its transcript copy, GW-10).""" @@ -928,14 +930,24 @@ async def resolve_unknown_as_owner(self, ref, admission_id, generation, *, notic # result the answer is normally already the transcript tail, so the closer is a no-op. from gateway.session_results import close_discarded_turn from gateway.session_runtime_workers import tracked_write + def close(conn, lost): + close_discarded_turn(self.db, conn, lost, None if ( + prepared is not None and lost['owner_epoch'] == self.epoch) else notice) + if restart_resume: + conn.execute('INSERT OR REPLACE INTO state_meta(key,value) VALUES(?,?)', + ('restart_resume:' + admission_id, ref.session_id)) + + async def resolved(row): + if restart_resume and row['status'] == 'terminal' and row['outcome'] == 'interrupted': + holds = getattr(self, 'restart_resume_holds', None) + if holds is None: + holds = self.restart_resume_holds = set() + holds.add(ref.session_id) + return await self._resolved_unknown(ref, admission_id, prepared, captured, row) + return await tracked_write(self, partial( resolve_unknown_session_input, self.db, epoch=self.epoch, admission_id=admission_id, - generation=generation, _captured=prepared, - # ``notice`` says the turn was interrupted: only when that is the outcome, never beside a - # captured result this resolution commits as the turn's own answer. - _terminal_write=lambda conn, lost: close_discarded_turn(self.db, conn, lost, None if ( - prepared is not None and lost['owner_epoch'] == self.epoch) else notice)), - then=partial(self._resolved_unknown, ref, admission_id, prepared, captured)) + generation=generation, _captured=prepared, _terminal_write=close), then=resolved) async def _resolved_unknown(self, ref, admission_id, prepared, captured, row): self.pending_results.pop(admission_id, None) @@ -1494,6 +1506,15 @@ def backfill_compression_created_sources(db): return stamped +def _restart_fenced_admissions(db, epoch): + # A turn interrupted during compression has an uncertain continuation, whether it ran in + # a managed worker or in-process. Keep it unknown until explicit recovery decides it. + return {row['admission_id'] for row in db._read_all( + "SELECT admission_id FROM session_admissions AS a " + "WHERE status='started' AND owner_epoch!=? AND NOT EXISTS (" + "SELECT 1 FROM state_meta WHERE key='admission_compressed:' || a.admission_id)", (epoch,))} + + async def initialize_session_authority(runner, *, profile_id, instance_id, db=None, register=True): """Call after exclusive profile ownership, before connecting adapters/API. @@ -1507,6 +1528,7 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=No from pathlib import Path db_key = await asyncio.to_thread(Path(db.db_path).resolve) epoch = await asyncio.to_thread(begin_runtime_epoch, db, instance_id=instance_id) + fenced = await asyncio.to_thread(_restart_fenced_admissions, db, epoch) # 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. @@ -1519,6 +1541,7 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=No from gateway.session_bot import release_superseded_bot_chat_at_boot await asyncio.to_thread(release_superseded_bot_chat_at_boot, db, runner.session_store) authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch) + authority.restart_fenced_admissions = fenced # A receipt's compression catch-up (#140060) writes: it commits off the loop too, before the # authority is published, so the recovery below only reads. from gateway.session_local_adoption import adopt_local_compressions diff --git a/forks/hermes-agent/gateway/session_unattended_unknown.py b/forks/hermes-agent/gateway/session_unattended_unknown.py index f60b77e42..aa28ab18c 100644 --- a/forks/hermes-agent/gateway/session_unattended_unknown.py +++ b/forks/hermes-agent/gateway/session_unattended_unknown.py @@ -63,6 +63,33 @@ def settle_recovered_unattended(db, epoch) -> int: row['admission_id'], row['target_session_id']) return settled +async def settle_recovered_session(authority, session_id, *, notice=None): + """Settle only a turn fenced from an earlier owner of this session.""" + import asyncio + from gateway.session_authorities import admission_owner + from gateway.session_contract import SessionRef + from hermes_state_runtime import RuntimeStoreError, list_session_admissions + + owner = await asyncio.to_thread(admission_owner, authority, session_id) + if not owner: + return None + rows = await asyncio.to_thread(list_session_admissions, authority.db, session_id=owner) + for row in rows: + if (row['admission_id'] not in getattr(authority, 'restart_fenced_admissions', ()) + or row['status'] != 'unknown' or row['owner_epoch'] is None + or row['owner_epoch'] >= authority.epoch or is_unattended(row)): + continue + try: + await authority.resolve_unknown_as_owner(SessionRef(authority.profile_id, owner), + row['admission_id'], row['generation'], notice=notice, + restart_resume=True) + except RuntimeStoreError as exc: + logger.warning('Lost admission %s left unknown: %s', row['admission_id'], exc.reason) + continue + authority.restart_fenced_admissions.discard(row['admission_id']) + return row['admission_id'] + return None + async def settle_unattended_unknown(authority, ref) -> bool: """The drain found an ``unknown`` head (fenced in this owner, e.g. a lost managed worker): diff --git a/forks/hermes-agent/hermes_state_compression.py b/forks/hermes-agent/hermes_state_compression.py index e3b5bc836..8e34c1105 100644 --- a/forks/hermes-agent/hermes_state_compression.py +++ b/forks/hermes-agent/hermes_state_compression.py @@ -443,6 +443,8 @@ def _publish_compression_child_on_conn( (parent_session_id,)) if not messages: raise RuntimeError("Compression child handoff must not be empty") + from hermes_state_runtime_workers import runtime_lineage + owners = json.dumps(sorted(runtime_lineage(conn, parent_session_id))) self._publish_child_session_row( conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id, source=source, model=model, model_config=model_config, system_prompt=system_prompt, @@ -473,6 +475,13 @@ def _publish_compression_child_on_conn( "WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id)) if updated.rowcount != 1: raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}") + conn.execute("UPDATE session_admissions SET lineage_json=json_insert(lineage_json,'$[#]',?) " + "WHERE status='started' AND (json_extract(lineage_json,'$[#-1]')=? " + "OR target_session_id IN (SELECT value FROM json_each(?)))", + (child_session_id, parent_session_id, owners)) + conn.execute("INSERT OR IGNORE INTO state_meta(key,value) " + "SELECT 'admission_compressed:' || admission_id, '1' FROM session_admissions " + "WHERE status='started' AND json_extract(lineage_json,'$[#-1]')=?", (child_session_id,)) # A child on a real surface stamps the chain's unset ancestors, so compressing a conversation # whose root predates write-time stamping lists it again under its surface. stamp_compression_ancestors(conn, child_session_id) diff --git a/forks/hermes-agent/hermes_state_runtime.py b/forks/hermes-agent/hermes_state_runtime.py index ac7bdf007..23c02074d 100644 --- a/forks/hermes-agent/hermes_state_runtime.py +++ b/forks/hermes-agent/hermes_state_runtime.py @@ -100,6 +100,7 @@ def _retire_admission_workers(conn, row, owner_epoch): compact_terminal_receipts(conn, execution_id) conn.execute(f"UPDATE worker_executions SET status='terminal' WHERE {scope}", (*targets, row['generation'], owner_epoch)) + conn.execute("DELETE FROM state_meta WHERE key=?", ('admission_compressed:' + row['admission_id'],)) def _row(row): diff --git a/forks/hermes-agent/tests/gateway/test_journey_restart_open_prompts.py b/forks/hermes-agent/tests/gateway/test_journey_restart_open_prompts.py index ef79235df..00923db80 100644 --- a/forks/hermes-agent/tests/gateway/test_journey_restart_open_prompts.py +++ b/forks/hermes-agent/tests/gateway/test_journey_restart_open_prompts.py @@ -5,8 +5,8 @@ behind it when the owner goes away. After a fresh daemon starts: - the stale prompts are gone from every snapshot and answering their old ids is refused, before and after the FIFO moves on, and never runs the gated command; -- a crash leaves the parked turn ``unknown`` and holds its followers until /discard (no replay); - a graceful stop settles it ``interrupted`` and the followers resume on their own; +- a crash resumes an eligible interrupted turn before its followers; a graceful stop settles it + ``interrupted`` and the followers resume on their own; - every input reaches the model exactly once and only as itself; the gated command never runs. """ import asyncio @@ -160,20 +160,7 @@ async def second(desc): snapshot = await call(ws, 'session.resume', session_id=sid) assert snapshot['prompts'] == [], snapshot['prompts'] fenced[kind] = await answer(ws, sid, before['prompts'][kind]) - if restart == 'crash': - lost = [r for r in snapshot['pending'] if r['status'] == 'unknown'] - assert [r['input_id'] for r in lost] == [ASK[kind]], snapshot['pending'] - queued = [r['input_id'] for r in snapshot['pending'] if r['status'] == 'queued'] - assert queued == list(FOLLOWERS[kind]), snapshot['pending'] assert fenced == {'approval': 'stale_generation', 'clarify': 'stale_generation'}, fenced - if restart == 'crash': - # Unknown work holds the FIFO: nothing ran behind it before the operator decides. - assert not any(reached(name) for names in FOLLOWERS.values() for name in names) - for kind, sid in before['sessions'].items(): - snapshot = await call(ws, 'session.resume', session_id=sid) - lost = next(r for r in snapshot['pending'] if r['status'] == 'unknown') - await call(ws, 'prompt.resolve_unknown', session_id=sid, admission_id=lost['admission_id'], - execution_generation=lost['execution_generation']) await until(lambda: all(r['status'] == 'terminal' for r in admissions().values())) late = {kind: await answer(ws, sid, before['prompts'][kind]) for kind, sid in before['sessions'].items()} assert late == {'approval': 'stale_generation', 'clarify': 'stale_generation'}, late @@ -196,7 +183,15 @@ async def second(desc): # turn (an unclosed tail would be merged into it and re-sent as part of that request). assert reached(ASK[kind]) == 1, [r['text'] for r in peer.requests] first_follower = next(r for r in peer.requests if r['text'] == names[0]) - assert first_follower['users'] == [ASK[kind], names[0]], first_follower['users'] + if restart == 'crash': + assert first_follower['users'][0] == ASK[kind] + assert first_follower['users'][-1] == names[0] + notes = [r for r in peer.requests if r['text'].startswith('[System note: resumed after gateway interruption.') + and ASK[kind] in r['users']] + assert len(notes) == 1 + assert peer.requests.index(notes[0]) < peer.requests.index(first_follower) + else: + assert first_follower['users'] == [ASK[kind], names[0]], first_follower['users'] assert not any(r['after_tool'] and r['text'] == ASK[kind] for r in peer.requests), 'gated tool resumed' order = [r['text'] for r in peer.requests if r['text'] in names] assert order == list(names), order diff --git a/forks/hermes-agent/tests/gateway/test_restart_resume_pending.py b/forks/hermes-agent/tests/gateway/test_restart_resume_pending.py index a93e44b11..84d83f6b9 100644 --- a/forks/hermes-agent/tests/gateway/test_restart_resume_pending.py +++ b/forks/hermes-agent/tests/gateway/test_restart_resume_pending.py @@ -657,6 +657,312 @@ async def _startup_auto_resume(authority, entry): return scheduled, adapter +@pytest.mark.asyncio +async def test_stale_restart_marker_keeps_admission_fenced(tmp_path, monkeypatch): + from datetime import timedelta + from hermes_state_runtime import begin_runtime_epoch, claim_session_input, get_session_admission, recover_session_inputs + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:stale', 'stale') + entry.last_resume_marked_at = datetime.now() - timedelta(hours=5) + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + with db: + await _submit(authority, 'lost') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + authority.restart_fenced_admissions = {lost['admission_id']} + authority.epoch = begin_runtime_epoch(db, instance_id='restart') + recover_session_inputs(db, epoch=authority.epoch) + assert await runner._schedule_resume_pending_sessions_async() == 0 + assert get_session_admission(db, admission_id=lost['admission_id'])['status'] == 'unknown' + assert 's' not in getattr(authority, 'restart_resume_holds', set()) + + +@pytest.mark.asyncio +async def test_second_compression_keeps_started_admission_unknown(tmp_path, monkeypatch): + from gateway.session_authority import _restart_fenced_admissions + from hermes_state_runtime import begin_runtime_epoch, claim_session_input, get_session_admission, recover_session_inputs + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + with db: + db.publish_compression_child(parent_session_id='s', child_session_id='c1', source='test', + messages=[{'role': 'assistant', 'content': 'summary'}], + require_compression_lease=False) + await _submit(authority, 'lost') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + db.publish_compression_child(parent_session_id='c1', child_session_id='c2', source='test', + messages=[{'role': 'assistant', 'content': 'summary'}], + require_compression_lease=False) + import json + row = db._read_one('SELECT lineage_json FROM session_admissions WHERE admission_id=?', (lost['admission_id'],)) + assert json.loads(row['lineage_json']) == ['s', 'c2'] + authority.epoch = begin_runtime_epoch(db, instance_id='restart') + assert lost['admission_id'] not in _restart_fenced_admissions(db, authority.epoch) + recover_session_inputs(db, epoch=authority.epoch) + assert get_session_admission(db, admission_id=lost['admission_id'])['status'] == 'unknown' + + +@pytest.mark.asyncio +@pytest.mark.parametrize('prior', ['reset', 'compression']) +async def test_worker_after_prior_boundary_auto_resumes_after_crash(tmp_path, monkeypatch, prior): + import subprocess + import sys + from gateway.session_authority import _restart_fenced_admissions + from gateway.session_worker_reservation import reserve_admission_worker + from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input, get_session_admission, recover_session_inputs + from tests.gateway.test_worker_admission_reservation import hello + from tests.hermes_state.test_target_advance_fence import _local_session, _mutate + + db, authority = _restart_authority(tmp_path, monkeypatch) + runner, adapter = make_restart_runner() + runner.session_authority = authority + adapter.handle_message = AsyncMock() + process = subprocess.Popen([sys.executable, '-c', 'import sys; sys.stdin.read()'], stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + with db: + sid = _local_session(db, authority.epoch, tmp_path) + authority.sessions[sid] = authority.sessions['s'] + if prior == 'reset': + target = _mutate(db, authority.epoch, sid, 'reset')['target_session_id'] + assert db.get_session(sid)['end_reason'] == 'session_reset' + else: + target = 'compressed' + db.publish_compression_child(parent_session_id=sid, child_session_id=target, source='test', + messages=[{'role': 'assistant', 'content': 'summary'}], + require_compression_lease=False) + entry = _auto_resume_entry('agent:main:telegram:dm:boundary-worker', 'boundary-worker', session_id=target) + runner.session_store._entries = {entry.session_key: entry} + admitted = admit_session_input(db, epoch=authority.epoch, principal_id='human', session_id=sid, + request_id='lost', payload={'text': 'lost'}) + lost = claim_session_input(db, epoch=authority.epoch, session_id=sid) + scope = reserve_admission_worker(authority, admission_id=lost['admission_id'], process=process, + principal_id='human', hello=hello(process)) + assert scope['session_id'] == target + authority.epoch = begin_runtime_epoch(db, instance_id='restart') + authority.restart_fenced_admissions = _restart_fenced_admissions(db, authority.epoch) + assert admitted['admission_id'] in authority.restart_fenced_admissions + recover_session_inputs(db, epoch=authority.epoch) + assert await runner._schedule_resume_pending_sessions_async() == 1 + await asyncio.gather(*list(runner._background_tasks)) + assert get_session_admission(db, admission_id=lost['admission_id'])['outcome'] == 'interrupted' + adapter.handle_message.assert_awaited_once() + finally: + process.stdin.close() + process.wait(timeout=5) + + +@pytest.mark.asyncio +async def test_old_epoch_started_admission_does_not_block_resume(tmp_path, monkeypatch): + from hermes_state_runtime import begin_runtime_epoch, claim_session_input, get_session_admission, recover_session_inputs + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:restart', 'restart') + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + resumed = asyncio.Event() + adapter.handle_message = AsyncMock(side_effect=lambda event: resumed.set()) + with db: + await _submit(authority, 'lost-original') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + authority.restart_fenced_admissions = {lost['admission_id']} + authority.epoch = begin_runtime_epoch(db, instance_id='restarted') + recover_session_inputs(db, epoch=authority.epoch) + scheduled = await runner._schedule_resume_pending_sessions_async() + await resumed.wait() + row = get_session_admission(db, admission_id=lost['admission_id']) + assert (row['status'], row['outcome']) == ('terminal', 'interrupted') + assert scheduled == 1 + adapter.handle_message.assert_awaited_once() + assert adapter.handle_message.await_args.args[0].text == '' + + +@pytest.mark.asyncio +async def test_unmarked_crash_resumes_only_its_fenced_admission(tmp_path, monkeypatch): + from hermes_state_runtime import (admit_session_input, begin_runtime_epoch, claim_session_input, + get_session_admission, recover_session_inputs) + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:crashed', 'crashed') + entry.resume_pending = False + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + resumed = asyncio.Event() + adapter.handle_message = AsyncMock(side_effect=lambda event: resumed.set()) + async def mark(key, reason): + entry.resume_pending = True + entry.resume_reason = reason + return True + runner.async_session_store.mark_resume_pending = AsyncMock(side_effect=mark) + with db: + await _submit(authority, 'lost-original') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + db.create_session('other', source='test') + other = admit_session_input(db, epoch=authority.epoch, principal_id='human', session_id='other', + request_id='other', payload={'text': 'other'}) + claim_session_input(db, epoch=authority.epoch, session_id='other') + authority.restart_fenced_admissions = {lost['admission_id'], other['admission_id']} + authority.epoch = begin_runtime_epoch(db, instance_id='restarted') + recover_session_inputs(db, epoch=authority.epoch) + scheduled = await runner._schedule_resume_pending_sessions_async() + await resumed.wait() + row = get_session_admission(db, admission_id=lost['admission_id']) + untouched = get_session_admission(db, admission_id=other['admission_id']) + assert (row['status'], row['outcome']) == ('terminal', 'interrupted') + assert untouched['status'] == 'unknown' + assert scheduled == 1 + assert entry.resume_reason == 'restart_interrupted' + assert adapter.sent == [] + assert adapter.handle_message.await_args.args[0].text == '' + +@pytest.mark.asyncio +async def test_resume_precedes_queued_follower(tmp_path, monkeypatch): + from hermes_state_runtime import begin_runtime_epoch, claim_session_input, recover_session_inputs + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:ordered', 'ordered') + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + events = [] + from gateway.session_authority import SessionAuthority + gate = asyncio.Event() + resume_started = asyncio.Event() + follower_done = asyncio.Event() + async def resume(event): + events.append('resume') + resume_started.set() + await gate.wait() + async def drain(ref): + events.append('follower') + follower_done.set() + adapter.handle_message = AsyncMock(side_effect=resume) + monkeypatch.setattr(authority, '_drain', drain) + with db: + await _submit(authority, 'lost') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + await _submit(authority, 'follower') + events.clear() + authority.restart_fenced_admissions = {lost['admission_id']} + monkeypatch.setattr(authority, '_schedule', SessionAuthority._schedule.__get__(authority)) + authority.epoch = begin_runtime_epoch(db, instance_id='restart') + recover_session_inputs(db, epoch=authority.epoch) + assert await runner._schedule_resume_pending_sessions_async() == 1 + await resume_started.wait() + assert events == ['resume'] + gate.set() + await follower_done.wait() + assert events == ['resume', 'follower'] + + +@pytest.mark.asyncio +async def test_cancelled_resume_keeps_marker_and_hold(tmp_path, monkeypatch): + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:cancel', 'cancel') + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + authority.restart_resume_holds = {'s'} + started = asyncio.Event() + async def resume(event): + started.set() + await asyncio.Event().wait() + adapter.handle_message = AsyncMock(side_effect=resume) + with db: + db._execute_write(lambda conn: conn.execute( + "INSERT INTO state_meta(key,value) VALUES('restart_resume:lost','s')")) + task = asyncio.create_task(runner._run_startup_resume_event(adapter, None, entry.session_key)) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert db._read_one("SELECT value FROM state_meta WHERE key='restart_resume:lost'")['value'] == 's' + assert 's' in authority.restart_resume_holds + + +@pytest.mark.asyncio +async def test_failed_resume_releases_marker_and_follower(tmp_path, monkeypatch): + from gateway.session_authority import SessionAuthority + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:failed', 'failed') + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + authority.restart_resume_holds = {'s'} + follower_done = asyncio.Event() + async def drain(ref): + follower_done.set() + monkeypatch.setattr(authority, '_drain', drain) + monkeypatch.setattr(authority, '_schedule', SessionAuthority._schedule.__get__(authority)) + adapter.handle_message = AsyncMock(side_effect=RuntimeError('resume failed')) + with db: + db._execute_write(lambda conn: conn.execute( + "INSERT INTO state_meta(key,value) VALUES('restart_resume:lost','s')")) + with pytest.raises(RuntimeError, match='resume failed'): + await runner._run_startup_resume_event(adapter, None, entry.session_key) + await asyncio.wait_for(follower_done.wait(), 5) + assert db._read_one("SELECT value FROM state_meta WHERE key='restart_resume:lost'") is None + assert 's' not in authority.restart_resume_holds + + +@pytest.mark.asyncio +async def test_second_restart_after_resolution_still_resumes(tmp_path, monkeypatch): + from hermes_state_runtime import begin_runtime_epoch, claim_session_input, recover_session_inputs + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry('agent:main:telegram:dm:second', 'second') + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + from gateway.session_authority import SessionAuthority + from gateway.session_contract import SessionRef + events = [] + gate = asyncio.Event() + resume_started = asyncio.Event() + follower_done = asyncio.Event() + async def resume(event): + events.append('resume') + resume_started.set() + await gate.wait() + async def drain(ref): + events.append('follower') + follower_done.set() + adapter.handle_message = AsyncMock(side_effect=resume) + monkeypatch.setattr(authority, '_drain', drain) + with db: + await _submit(authority, 'lost') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + await _submit(authority, 'follower') + authority.restart_fenced_admissions = {lost['admission_id']} + authority.epoch = begin_runtime_epoch(db, instance_id='restart') + recover_session_inputs(db, epoch=authority.epoch) + from gateway.session_unattended_unknown import settle_recovered_session + await settle_recovered_session(authority, 's') + authority.epoch = begin_runtime_epoch(db, instance_id='second-restart') + authority.restart_fenced_admissions = set() + authority.restart_resume_holds = set() + monkeypatch.setattr(authority, '_schedule', SessionAuthority._schedule.__get__(authority)) + assert await runner._schedule_resume_pending_sessions_async() == 1 + await resume_started.wait() + authority._schedule(SessionRef(authority.profile_id, 's')) + if authority.sessions['s'].task is not None: + await authority.sessions['s'].task + assert events == ['resume'] + gate.set() + await follower_done.wait() + assert events == ['resume', 'follower'] + + + @pytest.mark.asyncio @pytest.mark.parametrize("cause", [GATEWAY_RESTART_CAUSE, GATEWAY_SHUTDOWN_CAUSE]) async def test_turn_interrupted_by_restart_or_shutdown_resumes(tmp_path, monkeypatch, cause): @@ -722,6 +1028,42 @@ async def test_unattended_interrupted_turn_holds_its_session(tmp_path, monkeypat adapter.handle_message.assert_not_called() +@pytest.mark.asyncio +async def test_compression_child_recovers_owner_marker(tmp_path, monkeypatch): + from hermes_state_runtime import begin_runtime_epoch, claim_session_input, recover_session_inputs + from gateway.session_unattended_unknown import settle_recovered_session + from tests.gateway.test_session_authority_cancel_settlement import _submit + db, authority = _restart_authority(tmp_path, monkeypatch) + runner, adapter = make_restart_runner() + entry = _auto_resume_entry('agent:main:telegram:dm:child-marker', 'child-marker', session_id='child') + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + started, release = asyncio.Event(), asyncio.Event() + async def resume(event): + started.set() + await release.wait() + adapter.handle_message = AsyncMock(side_effect=resume) + with db: + await _submit(authority, 'lost') + lost = claim_session_input(db, epoch=authority.epoch, session_id='s') + authority.restart_fenced_admissions = {lost['admission_id']} + authority.epoch = begin_runtime_epoch(db, instance_id='first-restart') + recover_session_inputs(db, epoch=authority.epoch) + await settle_recovered_session(authority, 's') + db.publish_compression_child(parent_session_id='s', child_session_id='child', source='test', + messages=[{'role': 'assistant', 'content': 'summary'}], + require_compression_lease=False) + authority.epoch = begin_runtime_epoch(db, instance_id='second-restart') + authority.restart_resume_holds = set() + assert await runner._schedule_resume_pending_sessions_async() == 1 + await started.wait() + assert authority.restart_resume_holds == {'s'} + release.set() + tasks = list(runner._background_tasks) + await asyncio.gather(*tasks) + assert db._read_one("SELECT value FROM state_meta WHERE key=?", ('restart_resume:' + lost['admission_id'],)) is None + + @pytest.mark.asyncio @pytest.mark.parametrize(("outcome", "result", "resumes"), [ ("interrupted", _interrupted_result(GATEWAY_RESTART_CAUSE), 1), @@ -831,6 +1173,42 @@ async def test_startup_auto_resume_skips_session_with_a_pending_admission(tmp_pa adapter.handle_message.assert_not_called() +@pytest.mark.asyncio +async def test_startup_auto_resume_resolves_fenced_unknown_without_replaying_input(tmp_path, monkeypatch): + from hermes_state_runtime import (claim_session_input, begin_runtime_epoch, get_session_admission, + recover_session_inputs) + from tests.gateway.test_session_authority_cancel_settlement import _submit + + db, authority = _restart_authority(tmp_path, monkeypatch) + entry = _auto_resume_entry("agent:main:telegram:dm:restart-chat", "restart-chat") + runner, adapter = make_restart_runner() + runner.session_authority = authority + runner.session_store._entries = {entry.session_key: entry} + resumed = asyncio.Event() + adapter.handle_message = AsyncMock(side_effect=lambda event: resumed.set()) + with db: + receipt = await _submit(authority, 'lost-turn', 'original payload') + claim_session_input(db, epoch=authority.epoch, session_id='s') + authority.restart_fenced_admissions = {receipt.admission_id} + authority.epoch = begin_runtime_epoch(db, instance_id='restart') + recover_session_inputs(db, epoch=authority.epoch) + authority.resolve_unknown = AsyncMock(side_effect=AssertionError("manual discard used")) + + scheduled = await runner._schedule_resume_pending_sessions_async() + await resumed.wait() + + admission = get_session_admission(db, admission_id=receipt.admission_id) + assert (admission['status'], admission['outcome']) == ('terminal', 'interrupted') + + assert scheduled == 1 + adapter.handle_message.assert_awaited_once() + event = adapter.handle_message.await_args.args[0] + assert event.text == "" + assert event.internal + assert event.text != 'original payload' + authority.resolve_unknown.assert_not_called() + + @pytest.mark.asyncio async def test_reconnect_reschedule_is_platform_scoped(): diff --git a/forks/hermes-agent/tests/gateway/test_startup_resume_stale_snapshot.py b/forks/hermes-agent/tests/gateway/test_startup_resume_stale_snapshot.py index 80f7e4db5..817b892a2 100644 --- a/forks/hermes-agent/tests/gateway/test_startup_resume_stale_snapshot.py +++ b/forks/hermes-agent/tests/gateway/test_startup_resume_stale_snapshot.py @@ -31,8 +31,8 @@ async def _run_with_flip_during_read(tmp_path, monkeypatch, flip): flipped = threading.Event() real_held = runner._held_resume_sessions - def held_then_flip(authorities, candidates): - held = real_held(authorities, candidates) + def held_then_flip(authorities, candidates, *args): + held = real_held(authorities, candidates, *args) flip(runner.session_store, entry) flipped.set() return held