Skip to content

The agent that grows with you

feat(runtime): one session authority per served profile home under multiplex

Teknium8b8559bf5819
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index de557870944..61d5631486b 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -1,4 +1,10 @@
-"""Session-runtime lifecycle owned by the ordinary gateway bootstrap."""
+"""Session-runtime lifecycle owned by the ordinary gateway bootstrap.
+
+One SessionAuthority per reserved profile home. The launch home always has one; under
+``gateway.multiplex_profiles`` every served secondary gets its own, built under that
+profile's runtime scope against that profile's ``state.db``. ``runner.session_authority``
+stays the launch profile's authority so single-profile behaviour is byte-identical.
+"""
from __future__ import annotations
import asyncio
@@ -6,40 +12,71 @@ from pathlib import Path
import uuid
+def reserved_profile_homes(runner):
+ """``(name, home)`` pairs this process reserved: launch home first, then served secondaries."""
+ from hermes_constants import get_hermes_home
+ launch = get_hermes_home().resolve()
+ homes = [(getattr(runner, '_primary_profile_name', None) or 'default', launch)]
+ if getattr(runner.config, 'multiplex_profiles', False):
+ reserved = getattr(runner.config, '_runtime_profile_homes', None) or ()
+ for name, home in reserved:
+ canonical = Path(home).resolve()
+ if canonical != launch and canonical not in {h for _, h in homes}:
+ homes.append((name, canonical))
+ return homes
+
+
async def initialize_gateway_runtime(runner):
from gateway.runtime_bootstrap import TicketStore
from gateway.runtime_ownership import process_ownership
+ from gateway.run import _profile_runtime_scope
+ from gateway.session_authorities import SessionAuthorities
from gateway.session_authority import initialize_session_authority
- from hermes_constants import get_hermes_home
- home = get_hermes_home().resolve()
- # One SessionAuthority currently binds exactly one DB. Never give a
- # secondary home's principal access to the launch home's authority.
- if getattr(runner.config, 'multiplex_profiles', False):
- raise RuntimeError('shared gateway bootstrap does not yet support multiplex profile authorities')
- if not process_ownership.owns(home):
- raise RuntimeError('session authority requires reserved profile ownership')
- db = getattr(runner._session_db, '_db', runner._session_db)
- if db is None or Path(db.db_path).resolve().parent != home:
- raise RuntimeError('session authority database does not belong to the reserved profile')
+ homes = reserved_profile_homes(runner)
+ for _name, home in homes:
+ if not process_ownership.owns(home):
+ raise RuntimeError(f'session authority requires reserved profile ownership: {home}')
+ instance_id = uuid.uuid4().hex
descriptor = {
- 'instance_id': uuid.uuid4().hex, 'runtime_protocol': 1,
+ 'instance_id': instance_id, 'runtime_protocol': 1,
'state': 'starting', 'capabilities': [],
- 'served_profiles': [{'profile_id': str(home), 'home': str(home)}],
+ 'served_profiles': [],
}
runner.session_runtime_descriptor = descriptor
- authority = await initialize_session_authority(
- runner, profile_id=str(home), instance_id=descriptor['instance_id'])
- descriptor['authority_epoch'] = authority.epoch
- runner.session_ticket_store = TicketStore(descriptor['instance_id'], frozenset({str(home)}))
+ registry = SessionAuthorities(homes[0][1])
+ runner.session_authorities = registry
+ for index, (name, home) in enumerate(homes):
+ # Each home's store resolves through the runner's scope-following handle cache, exactly
+ # 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:
+ raise RuntimeError(f'session authority database does not belong to the reserved profile {home}')
+ registry.add(home, None, name=name)
+ authority = await initialize_session_authority(
+ runner, profile_id=str(home), instance_id=instance_id, db=db,
+ register=index == 0)
+ registry.replace(home, authority)
+ descriptor['authority_epoch'] = registry.launch.epoch
+ descriptor['served_profiles'] = registry.served_profiles()
+ runner.session_ticket_store = TicketStore(instance_id, registry.profile_ids())
+
+
+def _authorities(runner):
+ from gateway.session_authorities import all_authorities
+ return all_authorities(runner)
async def start_gateway_runtime_api(runner):
from gateway.run_api import start_gateway_api
+ from gateway.session_authorities import owner_scope
runner.session_api = await start_gateway_api(runner)
runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_origin
from gateway.session_bot import recover_bot_deliveries
- await recover_bot_deliveries(runner.session_authority)
+ for authority in _authorities(runner):
+ with owner_scope(authority):
+ await recover_bot_deliveries(authority)
async def recover_gateway_native_sessions(runner):
@@ -48,23 +85,28 @@ async def recover_gateway_native_sessions(runner):
Stored envelopes are input, not authority to create a route or reconnect a
transport. The authority preflights every queued sender before any claim.
"""
- authority = getattr(runner, 'session_authority', None)
- if authority is None:
+ import logging
+ from gateway.session_authorities import owner_scope
+ authorities = _authorities(runner)
+ if not authorities:
return {}
from gateway.session_hosted_service import ensure_hosted_service
await ensure_hosted_service(runner)
from gateway.session_local_recovery import recover_local_sessions
- recover_local_sessions(authority, schedule=True)
- pending = {row['target_session_id'] for row in authority.db._read_all(
- "SELECT DISTINCT target_session_id FROM session_admissions WHERE status IN ('queued','unknown')")}
- bindings = [(entry.session_id, entry.origin, runner._adapter_for_source(entry.origin))
- for entry in runner.session_store.list_sessions()
- if entry.session_id in pending and entry.origin is not None]
- results = await authority.recover_native_sessions(bindings)
- import logging
logger = logging.getLogger(__name__)
- for sid, outcome in results.items():
- logger.info('Native session startup recovery %s: %s', sid, outcome)
+ results = {}
+ for authority in authorities:
+ with owner_scope(authority):
+ recover_local_sessions(authority, schedule=True)
+ pending = {row['target_session_id'] for row in authority.db._read_all(
+ "SELECT DISTINCT target_session_id FROM session_admissions WHERE status IN ('queued','unknown')")}
+ bindings = [(entry.session_id, entry.origin, runner._adapter_for_source(entry.origin))
+ for entry in runner.session_store.list_sessions()
+ if entry.session_id in pending and entry.origin is not None]
+ outcome = await authority.recover_native_sessions(bindings)
+ for sid, verdict in outcome.items():
+ logger.info('Native session startup recovery %s (%s): %s', sid, authority.profile_id, verdict)
+ results.update(outcome)
return results
@@ -107,6 +149,9 @@ async def drain_gateway_runtime(runner):
# by already admitted work. Base adapters refuse before stamping acceptance.
for adapter in runner.adapters.values():
adapter.set_message_handler(None)
+ for adapters in getattr(runner, '_profile_adapters', {}).values():
+ for adapter in adapters.values():
+ adapter.set_message_handler(None)
store = getattr(runner, 'session_ticket_store', None)
if store is not None:
store.revoke()
@@ -117,9 +162,7 @@ async def drain_gateway_runtime(runner):
async def settle_gateway_runtime(runner):
"""Keep authority tasks alive until their last durable settlement write."""
- authority = getattr(runner, 'session_authority', None)
- if authority is None:
- return
- tasks = [live.task for live in authority.sessions.values() if live.task is not None]
+ tasks = [live.task for authority in _authorities(runner)
+ for live in authority.sessions.values() if live.task is not None]
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
diff --git a/gateway/runtime_bootstrap.py b/gateway/runtime_bootstrap.py
index 4bad2036a0f..c929c2ae50a 100644
--- a/gateway/runtime_bootstrap.py
+++ b/gateway/runtime_bootstrap.py
@@ -43,6 +43,8 @@ class TicketStore:
return ticket
def redeem(self, ticket, *, profile_id, purpose) -> dict:
+ """``profile_id=None`` accepts a ticket minted for ANY served profile; the returned grant's
+ ``profile_id`` then selects the authority. A named profile must match exactly."""
if not isinstance(ticket, str) or len(ticket) > 256:
raise PermissionError('invalid bootstrap ticket')
key = hashlib.sha256(ticket.encode()).hexdigest()
@@ -54,7 +56,8 @@ class TicketStore:
if expires <= time.monotonic():
del self._entries[key]
raise PermissionError('expired bootstrap ticket')
- if grant['profile_id'] != profile_id or grant['purpose'] != purpose:
+ served = grant['profile_id'] in self.profile_ids if profile_id is None else grant['profile_id'] == profile_id
+ if not served or grant['purpose'] != purpose:
raise PermissionError('bootstrap binding rejected')
del self._entries[key]
return dict(grant)
diff --git a/gateway/session_authorities.py b/gateway/session_authorities.py
new file mode 100644
index 00000000000..8d47cd4247d
--- /dev/null
+++ b/gateway/session_authorities.py
@@ -0,0 +1,148 @@
+"""One SessionAuthority per reserved profile home; resolved by the active runtime scope.
+
+A multiplexing gateway owns every profile under ``profiles/`` plus the default home. Each
+home has its own ``state.db``, admission ledger, runtime epoch and control identity, so each
+gets its own authority. Every consumer already runs inside the routed profile's
+``_profile_runtime_scope`` (that is what the multiplex fixes on main established), so the
+authority for "the profile this code is acting for" is the one keyed by the active home.
+
+A single-profile gateway is a map of one: the launch home's authority answers every lookup,
+scoped or not, exactly as before.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+from hermes_constants import get_hermes_home, get_hermes_home_override, hermes_home_key
+from hermes_state_runtime import RuntimeStoreError
+
+
+class SessionAuthorities:
+ """Registry of authorities keyed by ``hermes_home_key(home)``."""
+
+ def __init__(self, launch_home):
+ self.launch_key = hermes_home_key(launch_home)
+ self._by_key: dict[str, object] = {}
+ self._names: dict[str, str | None] = {}
+
+ def add(self, home, authority, name=None) -> None:
+ key = hermes_home_key(home)
+ if key in self._by_key:
+ raise RuntimeError(f'duplicate session authority for {home}')
+ self._by_key[key] = authority
+ self._names[key] = name
+
+ def replace(self, home, authority) -> None:
+ """Fill the slot reserved by ``add(home, None, name=...)`` once the authority exists."""
+ key = hermes_home_key(home)
+ if key not in self._by_key or self._by_key[key] is not None:
+ raise RuntimeError(f'no reserved session authority slot for {home}')
+ self._by_key[key] = authority
+
+ def profile_name(self, authority):
+ """Served profile name for *authority*; None for the launch profile (its adapters are
+ ``runner.adapters``, its session keys the historical ``agent:main`` namespace)."""
+ key = hermes_home_key(authority.profile_id)
+ return None if key == self.launch_key else self._names.get(key)
+
+ def __len__(self) -> int:
+ return len(self._by_key)
+
+ def __iter__(self):
+ return iter(self._by_key.values())
+
+ def __contains__(self, home) -> bool:
+ return hermes_home_key(home) in self._by_key
+
+ @property
+ def launch(self):
+ return self._by_key[self.launch_key]
+
+ def for_home(self, home):
+ """Authority owning *home*, or None when this process does not serve it."""
+ return self._by_key.get(hermes_home_key(home))
+
+ def require(self, home):
+ authority = self.for_home(home)
+ if authority is None:
+ raise RuntimeStoreError('profile_mismatch')
+ return authority
+
+ def active(self):
+ """Authority for the active runtime scope.
+
+ Unscoped code (startup, shutdown, background watchers) belongs to the launch profile.
+ Scoped code that names a home this process does not serve gets ``None``: a routed
+ profile must never fall back to the launch profile's ledger.
+ """
+ if len(self._by_key) == 1 or get_hermes_home_override() is None:
+ return self._by_key[self.launch_key]
+ return self._by_key.get(hermes_home_key(get_hermes_home()))
+
+ def served_profiles(self) -> list[dict]:
+ return [{'profile_id': a.profile_id, 'home': a.profile_id} for a in self._by_key.values()]
+
+ def profile_ids(self) -> frozenset[str]:
+ return frozenset(a.profile_id for a in self._by_key.values())
+
+
+def served_profile_name(home) -> str:
+ """Canonical profile id of a served home (``default`` for the root, the directory name for
+ ``profiles/<name>``); the shape-only ``parent == 'profiles'`` guess mislabels a custom
+ HERMES_HOME outside ``profiles/`` as ``default`` and collides in rosters/relay selectors."""
+ from hermes_constants import profile_name_for_home
+ name = profile_name_for_home(home)
+ if name is not None:
+ return name
+ from hermes_cli.profiles import get_active_profile_name
+ from hermes_constants import get_hermes_home
+ if Path(home).resolve() == get_hermes_home().resolve():
+ return get_active_profile_name() or 'default'
+ return Path(home).name
+
+
+def authority_for_home(runner, home):
+ """Explicit per-home lookup for callers that already know the routed home."""
+ registry = getattr(runner, 'session_authorities', None)
+ if registry is None:
+ authority = getattr(runner, 'session_authority', None)
+ if authority is not None and Path(authority.db.db_path).resolve().parent == Path(home).resolve():
+ return authority
+ return None
+ return registry.for_home(home)
+
+
+def authority_for_profile_id(runner, profile_id):
+ return authority_for_home(runner, Path(profile_id))
+
+
+def active_authority(runner):
+ """Authority for the active runtime scope (see ``SessionAuthorities.active``); the single
+ launch authority when the runner predates the registry (bare test runners)."""
+ registry = getattr(runner, 'session_authorities', None)
+ if registry is None:
+ return getattr(runner, 'session_authority', None)
+ return registry.active()
+
+
+def all_authorities(runner):
+ registry = getattr(runner, 'session_authorities', None)
+ if registry is not None:
+ return list(registry)
+ authority = getattr(runner, 'session_authority', None)
+ return [authority] if authority is not None else []
+
+
+def owner_scope(authority, *, hydrate_secrets=False):
+ """Runtime scope of the profile that owns *authority*.
+
+ Owner-side handlers (RPC dispatch, cron submit, admitted execution) must read config, jobs
+ and policy for the OWNING profile, never the launch profile's ambient scope. Test peers
+ build authorities with symbolic ids ('fixture'); those keep the ambient scope.
+ """
+ from contextlib import nullcontext
+ home = Path(str(authority.profile_id))
+ if not home.is_absolute() or not home.is_dir():
+ return nullcontext()
+ from gateway.run import _profile_runtime_scope
+ return _profile_runtime_scope(home, hydrate_secrets=hydrate_secrets)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index d7894c911ab..1524c30fec8 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -401,16 +401,30 @@ class SessionAuthority:
waiter.set_result(response)
-async def initialize_session_authority(runner, *, profile_id, instance_id):
- """Call after exclusive profile ownership, before connecting adapters/API."""
- db = getattr(runner._session_db, '_db', runner._session_db)
+async def initialize_session_authority(runner, *, profile_id, instance_id, db=None, register=True):
+ """Call after exclusive profile ownership, before connecting adapters/API.
+
+ ``register=False`` builds a served secondary's authority without making it the runner's
+ launch authority (``runner.session_authority``); the per-home registry owns the lookup.
+ """
+ if db is None:
+ db = getattr(runner._session_db, '_db', runner._session_db)
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)
- runner.session_authority = authority
+ if register:
+ runner.session_authority = authority
from gateway.session_cron import bind_owner
bind_owner(authority)
- runner.session_store._local_authority_epoch = epoch
+ store = runner.session_store
+ if register:
+ store._local_authority_epoch = epoch
+ # Local resets write the owning profile's store; the epoch fence must be that store's.
+ epochs = 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
from gateway.session_local_recovery import recover_local_sessions
recover_local_sessions(authority)
return authority
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
index faab508fa74..095ad61099c 100644
--- a/gateway/session_cron.py
+++ b/gateway/session_cron.py
@@ -87,7 +87,8 @@ def _create(authority, actor, params):
policy = replace(policy, source='cron', platform='cron', model=_load_cron_job_config(job, jid, job.get('name') or jid).model,
request_json=json.dumps({'cron_job': job, 'extra_prompt': extra, 'request_id': request_id}))
policy = bind_launch_key(authority, sid, policy, None, config_secrets=private)
- source = SessionSource(platform=Platform.LOCAL, chat_id=sid, user_id=actor.subject, chat_type='dm')
+ from gateway.session_local_recovery import local_source
+ source = local_source(authority, sid, actor.subject)
route = authority.runner.session_store._generate_session_key(source)
now = datetime.now(timezone.utc)
entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
@@ -117,14 +118,18 @@ async def operation(authority, name, params, actor=None):
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, sid)
from gateway.config import Platform
- policy = authority.runner.adapters[Platform.LOCAL].policies[sid]
+ from gateway.session_local_recovery import local_adapter_map
+ policy = local_adapter_map(authority)[Platform.LOCAL].policies[sid]
frozen = json.loads(policy.request_json)
if frozen['extra_prompt'] != params['extra_prompt']:
raise RuntimeStoreError('admission_conflict')
state['job'] = frozen['cron_job']
return state
if name == 'submit':
- ref, request_id = _create(authority, actor, params)
+ from gateway.session_authorities import owner_scope
+ # The job id, jobs file and gateway config belong to the OWNING profile.
+ with owner_scope(authority):
+ ref, request_id = _create(authority, actor, params)
row = admit_session_input(authority.db, epoch=authority.epoch, principal_id=actor.subject,
session_id=ref.session_id, request_id=request_id,
payload={'text': params['extra_prompt'] or ''})
diff --git a/gateway/session_local.py b/gateway/session_local.py
index bab1a0345b3..d87a8c16178 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -67,10 +67,12 @@ def authorize_local_source(runner, source):
return None
# A forged profile must not miss this adapter and fall into a messaging
# allow-all policy. Local source identity is owned by this authority alone.
- adapter = runner._primary_adapters().get(Platform.LOCAL)
+ adapter = runner._adapters_for_profile(source.profile).get(Platform.LOCAL)
if not isinstance(adapter, LocalSessionAdapter):
return None
- if adapter.authority is not getattr(runner, 'session_authority', None):
+ from gateway.session_authorities import authority_for_profile_id
+ owner = authority_for_profile_id(runner, adapter.authority.profile_id)
+ if owner is None or adapter.authority is not owner:
return False
return adapter.authorize_source(source)
@@ -131,8 +133,8 @@ def create_local_session(authority, actor, params, *, trusted_policy=None, trust
raise RuntimeStoreError('admission_conflict')
return restore_local_session(authority, sid)
policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets)
- source = SessionSource(platform=Platform.LOCAL, chat_id=sid,
- user_id=actor.subject, chat_type='dm')
+ from gateway.session_local_recovery import local_source
+ source = local_source(authority, sid, actor.subject)
route = authority.runner.session_store._generate_session_key(source)
now = datetime.now(timezone.utc)
entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
@@ -146,7 +148,8 @@ def publish_local_policy(authority, session_id):
from hermes_state_local import local_receipt
from gateway.session_policy import restore_policy
live = authority.sessions[session_id]
- adapter = authority.runner.adapters[Platform.LOCAL]
+ from gateway.session_local_recovery import local_adapter_map
+ adapter = local_adapter_map(authority)[Platform.LOCAL]
adapter.policies[live.source.chat_id] = restore_policy(local_receipt(authority.db, session_id)['policy'])
authority.runner._evict_cached_agent(live.route)
diff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.py
index 05ba398b811..e13ea8d13e0 100644
--- a/gateway/session_local_migration.py
+++ b/gateway/session_local_migration.py
@@ -88,7 +88,8 @@ def adopt_legacy_session(authority, actor, row):
if policy.model is None:
policy = replace(policy, model=_resolve_gateway_model(policy.config()))
policy = bind_launch_key(authority, sid, policy, None, config_secrets=private)
- source = SessionSource(platform=Platform.LOCAL, chat_id=sid, user_id=actor.subject, chat_type='dm')
+ from gateway.session_local_recovery import local_source
+ source = local_source(authority, sid, actor.subject)
route = authority.runner.session_store._generate_session_key(source)
now = datetime.fromtimestamp(row['started_at'], timezone.utc)
entry = SessionEntry(route, row['id'], now, now, origin=source, platform=Platform.LOCAL)
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index 8b507614959..039012a7e88 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -2,6 +2,7 @@
import hashlib
import json
import logging
+from pathlib import Path
from gateway.config import Platform
from gateway.session import SessionEntry, SessionSource
@@ -15,6 +16,33 @@ def local_identity(profile_id, principal_id, request_id):
return 'local-' + hashlib.sha256(identity.encode()).hexdigest()
+def local_adapter_map(authority):
+ """The adapter map a LOCAL session of *authority* lives in: ``runner.adapters`` for the launch
+ profile, ``runner._profile_adapters[name]`` for a served secondary (its routed home, so
+ ``_adapter_for_source`` / ``_adapters_for_profile`` resolve the right transport)."""
+ runner = authority.runner
+ registry = getattr(runner, 'session_authorities', None)
+ name = registry.profile_name(authority) if registry is not None else None
+ if name is None:
+ return runner.adapters
+ profile_adapters = getattr(runner, '_profile_adapters', None)
+ if profile_adapters is None:
+ profile_adapters = runner._profile_adapters = {}
+ return profile_adapters.setdefault(name, {})
+
+
+def local_source(authority, chat_id, user_id):
+ """LOCAL SessionSource for a session owned by *authority*. A served secondary's local sessions
+ carry its profile so ``build_session_key`` namespaces them (``agent:<name>:local:...``) and the
+ SessionStore writes their rows to that profile's ``state.db``, not the launch store."""
+ source = SessionSource(platform=Platform.LOCAL, chat_id=chat_id, user_id=user_id, chat_type='dm')
+ registry = getattr(authority.runner, 'session_authorities', None)
+ name = registry.profile_name(authority) if registry is not None else None
+ if name is not None:
+ source.profile = name
+ return source
+
+
def restore_local_session(authority, sid):
from gateway.session_authority import LiveSession
from gateway.session_local import LocalSessionAdapter
@@ -27,8 +55,7 @@ def restore_local_session(authority, sid):
local_identity(receipt['profile_id'], receipt['principal_id'], receipt['request_id']))
if receipt['session_id'] != sid or sid != chat_id:
raise ValueError('identity mismatch')
- source = SessionSource(platform=Platform.LOCAL, chat_id=chat_id,
- user_id=receipt['principal_id'], chat_type='dm')
+ source = local_source(authority, chat_id, receipt['principal_id'])
store = authority.runner.session_store
route = store._generate_session_key(source)
if receipt['route'] != route:
@@ -49,10 +76,11 @@ def restore_local_session(authority, sid):
if isinstance(exc, RuntimeStoreError):
raise
raise RuntimeStoreError('storage_unavailable') from exc
- adapter = authority.runner.adapters.get(Platform.LOCAL)
+ adapters = local_adapter_map(authority)
+ adapter = adapters.get(Platform.LOCAL)
if adapter is None:
adapter = LocalSessionAdapter(authority)
- authority.runner.adapters[Platform.LOCAL] = adapter
+ adapters[Platform.LOCAL] = adapter
if not isinstance(adapter, LocalSessionAdapter) or adapter.authority is not authority:
raise RuntimeStoreError('runtime_draining')
live = authority.sessions.get(sid)
@@ -95,7 +123,10 @@ def reset_local_session(store, old_entry, session_id, now, display_name):
origin=old_entry.origin, platform=old_entry.platform, chat_type=old_entry.chat_type,
display_name=display_name if display_name is not None else old_entry.display_name,
is_fresh_reset=True)
- reset_local_target(store._db_for_key(old_entry.session_key), epoch=store._local_authority_epoch,
+ db = store._db_for_key(old_entry.session_key)
+ epochs = getattr(store, '_local_authority_epochs', None) or {}
+ epoch = epochs.get(Path(db.db_path).resolve(), store._local_authority_epoch) if db is not None else store._local_authority_epoch
+ reset_local_target(db, epoch=epoch,
parent_session_id=old_entry.session_id, entry=entry.to_dict())
store._entries[old_entry.session_key] = entry
return entry
diff --git a/tests/gateway/test_session_authorities_multiplex.py b/tests/gateway/test_session_authorities_multiplex.py
new file mode 100644
index 00000000000..ec768252f27
--- /dev/null
+++ b/tests/gateway/test_session_authorities_multiplex.py
@@ -0,0 +1,115 @@
+"""One session authority per served profile home under gateway.multiplex_profiles."""
+import asyncio
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+def _reserve_homes(tmp_path, monkeypatch, names=('alpha', 'beta')):
+ root = tmp_path / '.hermes'
+ root.mkdir(mode=0o700)
+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)
+ monkeypatch.setenv('HERMES_HOME', str(root))
+ # The autouse isolation fixture pins hermes_state.DEFAULT_DB_PATH to its own fake home once
+ # hermes_state is imported; per-home stores must follow the scoped HERMES_HOME here.
+ import hermes_state
+ monkeypatch.setattr(hermes_state, 'DEFAULT_DB_PATH', hermes_state._IMPORT_DEFAULT_DB_PATH)
+ homes = [('default', root)]
+ for name in names:
+ home = root / 'profiles' / name
+ home.mkdir(parents=True, mode=0o700)
+ (home / 'config.yaml').write_text('{}')
+ homes.append((name, home))
+ return root, homes
+
+
+def _runner(root, homes):
+ from gateway.config import GatewayConfig
+ from gateway.run import GatewayRunner
+ config = GatewayConfig()
+ config.multiplex_profiles = True
+ config._runtime_profile_homes = tuple(homes)
+ runner = GatewayRunner(config)
+ return runner
+
+
+async def test_multiplex_builds_one_authority_per_reserved_home(tmp_path, monkeypatch):
+ from gateway.run_runtime import initialize_gateway_runtime
+ from gateway.runtime_ownership import process_ownership
+ from hermes_constants import hermes_home_key
+ root, homes = _reserve_homes(tmp_path, monkeypatch)
+ process_ownership.reserve([home for _, home in homes])
+ try:
+ runner = _runner(root, homes)
+ await initialize_gateway_runtime(runner)
+ registry = runner.session_authorities
+ assert len(registry) == 3
+ # The launch authority is the default profile's; secondaries bind their own stores.
+ assert runner.session_authority is registry.launch
+ for _name, home in homes:
+ authority = registry.for_home(home)
+ assert authority is not None
+ assert Path(authority.db.db_path).resolve().parent == home.resolve()
+ assert (home / 'state.db').exists()
+ epochs = {hermes_home_key(h): registry.for_home(h).epoch for _, h in homes}
+ assert all(epoch >= 1 for epoch in epochs.values())
+ # Descriptor + ticket store carry the whole served set.
+ served = {entry['home'] for entry in runner.session_runtime_descriptor['served_profiles']}
+ assert served == {str(h.resolve()) for _, h in homes}
+ assert runner.session_ticket_store.profile_ids == frozenset(str(h.resolve()) for _, h in homes)
+ # A ticket minted for a secondary redeems under the served-set rule and names that home.
+ ticket = runner.session_ticket_store.mint(profile_id=str(homes[1][1].resolve()), subject='uid:1', purpose='interactive')
+ grant = runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='interactive')
+ assert grant['profile_id'] == str(homes[1][1].resolve())
+ finally:
+ for authority in list(getattr(runner, 'session_authorities', []) or []):
+ authority.db.close()
+ for _, home in homes:
+ process_ownership.release(home)
+
+
+async def test_scoped_lookup_follows_routed_home_and_never_borrows_launch(tmp_path, monkeypatch):
+ from gateway.run import _profile_runtime_scope
+ from gateway.run_runtime import initialize_gateway_runtime
+ from gateway.runtime_ownership import process_ownership
+ from gateway.session_authorities import active_authority, authority_for_home
+ root, homes = _reserve_homes(tmp_path, monkeypatch)
+ process_ownership.reserve([home for _, home in homes])
+ try:
+ runner = _runner(root, homes)
+ await initialize_gateway_runtime(runner)
+ alpha = homes[1][1]
+ with _profile_runtime_scope(alpha, {}):
+ assert active_authority(runner) is authority_for_home(runner, alpha)
+ assert active_authority(runner) is not runner.session_authority
+ assert active_authority(runner) is runner.session_authority # unscoped = launch profile
+ foreign = tmp_path / 'elsewhere'
+ foreign.mkdir()
+ with _profile_runtime_scope(foreign, {}):
+ assert active_authority(runner) is None
+ assert authority_for_home(runner, foreign) is None
+ finally:
+ for authority in list(runner.session_authorities):
+ authority.db.close()
+ for _, home in homes:
+ process_ownership.release(home)
+
+
+def test_single_profile_runtime_is_a_map_of_one(tmp_path, monkeypatch):
+ """Without multiplex the registry holds only the launch home and every lookup returns it."""
+ from gateway.run import _profile_runtime_scope
+ from gateway.session_authorities import SessionAuthorities, active_authority
+ root, _ = _reserve_homes(tmp_path, monkeypatch, names=())
+ registry = SessionAuthorities(root)
+ authority = SimpleNamespace(profile_id=str(root), epoch=1)
+ registry.add(root, authority, name='default')
+ runner = SimpleNamespace(session_authorities=registry, session_authority=authority)
+ assert registry.served_profiles() == [{'profile_id': str(root), 'home': str(root)}]
+ other = tmp_path / 'other'
+ other.mkdir()
+ with _profile_runtime_scope(other, {}):
+ assert active_authority(runner) is authority