The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): resolve session/runtime paths off the event loop
Teknium54327b2ad861
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 11eded4ee4f..1ad2897c2f4 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -43,7 +43,7 @@ async def _build_profile_authority(runner, name, home, *, register):# the handle every later scoped read of that profile uses (one writer per state.db).with _profile_runtime_scope(home, hydrate_secrets=False):db = getattr(runner._session_db, '_db', runner._session_db)- if db is None or Path(db.db_path).resolve().parent != home:+ if db is None or (await asyncio.to_thread(Path(db.db_path).resolve)).parent != home:raise RuntimeError(f'session authority database does not belong to the reserved profile {home}')registry.add(home, None, name=name)try:@@ -188,7 +188,7 @@ async def serve_profile_runtime(runner, name, home):from gateway.session_hosted_service import _ensure_hosted_service, start_ready_hosted_servicesfrom gateway.session_local_recovery import recover_local_sessionsfrom gateway.platforms.webhook_ingress import recover_webhook_finalizations- home = Path(home).resolve()+ home = await asyncio.to_thread(Path(home).resolve)registry = runner.session_authoritiesif registry.for_home(home) is not None:return registry.for_home(home)@@ -212,7 +212,7 @@ async def serve_profile_runtime(runner, name, home):async def unserve_profile_runtime(runner, home):"""Retire one profile's authority (deleted while running) and shrink the published set.No-op for a profile this process never served."""- home = Path(home).resolve()+ home = await asyncio.to_thread(Path(home).resolve)registry = runner.session_authoritiesauthority = registry.remove(home) if home in registry else Noneif authority is None:diff --git a/gateway/session_a2a.py b/gateway/session_a2a.pyindex c84c3a837c5..970e37891c5 100644--- a/gateway/session_a2a.py+++ b/gateway/session_a2a.py@@ -113,7 +113,7 @@ async def forward_to_owner(home, *, agent, tenant, peer, context_id, input_id, tfrom hermes_cli.gateway_client import GatewayClient, GatewayClientError, _session_ticketfrom hermes_cli.gateway_runtime import ensure_gateway_runtimefrom websockets.asyncio.client import connect- home = Path(home).resolve()+ home = await asyncio.to_thread(Path(home).resolve)async with asyncio.timeout(timeout):ready = await asyncio.to_thread(ensure_gateway_runtime, home)if ready.state != 'ready' or ready.endpoint is None:diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 5e8d26ad993..5d5b10e3c7f 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -584,6 +584,10 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=No"""if db is None:db = getattr(runner._session_db, '_db', runner._session_db)+ # Resolved off-loop before any state is published: the rest of the bring-up runs without+ # yielding, so no other task observes a half-registered authority.+ from pathlib import Path+ db_key = await asyncio.to_thread(Path(db.db_path).resolve)epoch = begin_runtime_epoch(db, instance_id=instance_id)recover_session_inputs(db, epoch=epoch)authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)@@ -598,8 +602,7 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=Noepochs = getattr(store, '_local_authority_epochs', None)if epochs is None:epochs = store._local_authority_epochs = {}- from pathlib import Path- epochs[Path(db.db_path).resolve()] = epoch+ epochs[db_key] = epochfrom gateway.session_local_recovery import recover_local_sessionsrecover_local_sessions(authority)return authoritydiff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex 8c0b2ed5b6a..e4efefcd842 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -192,7 +192,8 @@ async def execute(authority, ref, row, policy):token = _execution.set((authority, ref.session_id, data['cron_job']['id'], row['admission_id']))try:job = data['cron_job']- with _profile_runtime_scope(Path(authority.db.db_path).resolve().parent):+ db_path = await asyncio.to_thread(Path(authority.db.db_path).resolve)+ with _profile_runtime_scope(db_path.parent):result = await asyncio.to_thread(run_job, job, extra_prompt=data['extra_prompt'],execution_id=row['admission_id'], cancel_event=cancel)# run_job stamps run-side verdicts on ITS job copy (quota hold, unreachable model); thediff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.pyindex 275ef3900c1..eec29523163 100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@ -51,7 +51,8 @@ async def dispatch_group_control(connection, method, params):if method not in _FIELDS or not isinstance(params, dict) or set(params) - (_FIELDS[method] | {'profile'}):raise RuntimeStoreError('invalid_params')home = Path(authority.profile_id)- if Path(authority.db.db_path).resolve().parent != home.resolve():+ db_path = await asyncio.to_thread(Path(authority.db.db_path).resolve)+ if db_path.parent != await asyncio.to_thread(home.resolve):raise RuntimeStoreError('profile_mismatch')from hermes_cli.profiles import profile_matches_homeprofile = params.get('profile')diff --git a/gateway/session_kanban.py b/gateway/session_kanban.pyindex 8c78edcc6a1..fcb5462fb44 100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@ -1,4 +1,5 @@"""Trusted dispatcher claims enter the ordinary owner's durable admission queue."""+import asynciofrom contextlib import closingfrom dataclasses import asdict, replaceimport threading@@ -78,6 +79,9 @@ async def run_task(connection, params):from hermes_state_local import local_receiptfrom gateway.session_policy import restore_policyauthority = connection.authority+ # Resolved off-loop up front: no await may separate the saved-claim check, session+ # creation and the claim's write transaction below.+ owner_db = str(await asyncio.to_thread(Path(authority.db.db_path).resolve))# The dispatcher attempt is the durable request identity, including after the# task closes. Retry checks the saved claim, never reinterprets updated cards.request_id = 'kanban:' + json.dumps([params.get('board'), params.get('task_id'), params.get('run_id')], separators=(',', ':'))@@ -114,7 +118,7 @@ async def run_task(connection, params):if not (task and task.status == 'running' and task.current_run_id == params['run_id'] and task.claim_lock == params['claim_lock']):raise RuntimeStoreError('stale_kanban_claim')kb._append_event(conn, task.id, 'owner_admitted',- {'db': str(Path(authority.db.db_path).resolve()), 'session_id': ref.session_id,+ {'db': owner_db, 'session_id': ref.session_id,'request_id': request_id, 'pid': os.getpid(), 'birth': psutil.Process().create_time()},run_id=task.current_run_id)await connection.resume(ref, {})diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 2dc8367ce1f..62ce33199d8 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -237,8 +237,9 @@ def _worker_env(authority):async def execute_managed(authority, ref, row, policy):env = await asyncio.to_thread(_worker_env, authority)+ cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]process = await asyncio.to_thread(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],- cwd=Path(__file__).resolve().parents[1], stdin=subprocess.PIPE, env=env,+ cwd=cwd, stdin=subprocess.PIPE, env=env,stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=True)worker = ManagedWorker(process)workers = getattr(authority, '_managed_workers', None)