Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 124 additions & 7 deletions forks/hermes-agent/gateway/run_startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<?", (authority.epoch,))
for raw in rows:
row = _row(raw)
if row['admission_id'] in getattr(authority, 'restart_fenced_admissions', ()) and not is_unattended(row):
recovered.setdefault(row['target_session_id'], []).append((authority, row['admission_id']))
rows = await asyncio.to_thread(authority.db._read_all,
"SELECT key,value FROM state_meta WHERE key LIKE 'restart_resume:%'")
for row in rows:
markers.setdefault(row['value'], []).append((authority, row['key'].removeprefix('restart_resume:')))
except Exception:
logger.warning('Could not enumerate restart admissions', exc_info=True)
def lookup_owners():
owners = {}
for authority in authorities:
for entry in entries:
try:
owners[(id(authority), entry.session_id)] = admission_owner(authority, entry.session_id)
except Exception:
logger.warning('Could not look up restart owner for %s', entry.session_id, exc_info=True)
return owners
owners = await asyncio.to_thread(lookup_owners)
for entry in entries:
if entry.resume_pending or entry.origin is None or entry.suspended or not any(
owners.get((id(authority), entry.session_id)) in recovered for authority in authorities):
continue
if platform is not None and entry.origin.platform != platform:
continue
try:
source = self._restored_source(entry)
if self._delivery_adapter_for(source) and self._resume_owner_authorized(entry.session_key, source):
await self.async_session_store.mark_resume_pending(entry.session_key, 'restart_interrupted')
except Exception:
logger.warning('Could not mark restart session %s', entry.session_id, exc_info=True)
candidates = self._resume_pending_candidates(platform)
if not candidates:
return self._schedule_resume_pending_sessions(platform=platform, candidates=candidates)
from gateway.session_authorities import all_authorities
held = await asyncio.to_thread(self._held_resume_sessions, all_authorities(self), candidates)
return self._schedule_resume_pending_sessions(platform=platform, candidates=candidates, held=held)
return 0
resolved_admissions = set()
resolved_sessions = set()
eligible = []
window = _auto_continue_freshness_window()
for entry in candidates:
try:
if (not self._still_resume_pending(entry.session_key)
or not _is_fresh_gateway_interruption(entry.last_resume_marked_at or entry.updated_at, window_secs=window)
or self._is_session_running(entry.session_key)):
continue
source = self._restored_source(entry)
if self._delivery_adapter_for(source) is None or not self._resume_owner_authorized(entry.session_key, source):
continue
eligible.append(entry)
for authority in authorities:
owner = owners.get((id(authority), entry.session_id))
for candidate_authority, admission_id in recovered.get(owner, ()):
if candidate_authority is not authority:
continue
if not await self.async_session_store.mark_resume_pending(entry.session_key, entry.resume_reason):
continue
settled = await settle_recovered_session(authority, entry.session_id)
if settled:
resolved_admissions.add(settled)
resolved_sessions.add(owner)
for marker_authority, admission_id in markers.get(owner, ()):
if marker_authority is not authority:
continue
resolved_admissions.add(admission_id)
resolved_sessions.add(owner)
holds = getattr(authority, 'restart_resume_holds', None)
if holds is None:
holds = authority.restart_resume_holds = set()
holds.add(owner)
except Exception:
logger.warning('Could not recover restart session %s', entry.session_id, exc_info=True)
held = await asyncio.to_thread(self._held_resume_sessions, authorities, eligible, resolved_admissions, resolved_sessions)
scheduled = self._schedule_resume_pending_sessions(platform=platform, candidates=eligible, held=held)
from gateway.session_contract import SessionRef
for entry in eligible:
if self._is_session_running(entry.session_key):
continue
for authority in authorities:
holds = getattr(authority, 'restart_resume_holds', set())
owner = owners.get((id(authority), entry.session_id))
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))
return scheduled

def _held_resume_sessions(self, authorities, candidates) -> 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:
Expand Down
21 changes: 8 additions & 13 deletions forks/hermes-agent/gateway/session_authorities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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"
Expand All @@ -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:
Expand Down
37 changes: 30 additions & 7 deletions forks/hermes-agent/gateway/session_authority.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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)."""
Expand All @@ -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)
Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand All @@ -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
Expand Down
27 changes: 27 additions & 0 deletions forks/hermes-agent/gateway/session_unattended_unknown.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading