Skip to content

The agent that grows with you

fix(gateway): keep native FIFO identity stable across compression

teknium1b5ab97cc5ea5
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index d59fa1a8f22..e08114fd562 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -100,9 +100,9 @@ async def recover_gateway_native_sessions(runner):
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]
+ bindings = [(owner, entry.origin, runner._adapter_for_source(entry.origin))
+ for entry in runner.session_store.list_sessions() if entry.origin is not None
+ for owner in [authority.logical_owner(entry.session_id)] if owner in pending]
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)
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 44633c74626..26a3a3fd6ef 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -60,7 +60,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
self._approval_owner = None
if authority is not None:
source = getattr(ctx, 'source', None)
- owner_id = source.chat_id if getattr(source, 'platform', None) == Platform.LOCAL else ctx.session_id
+ owner_id = (source.chat_id if getattr(source, 'platform', None) == Platform.LOCAL
+ else authority.logical_owner(ctx.session_id))
if owner_id in authority.sessions:
generation = authority.db.get_session(owner_id)["runtime_generation"]
self._approval_owner = (authority, owner_id, generation)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 92f270e5297..1b67892128b 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -78,10 +78,18 @@ class SessionAuthority:
if self.runner._draining:
raise RuntimeStoreError('runtime_draining')
+ def logical_owner(self, session_id):
+ """The FIFO/admission identity of a route: the root of its compression lineage.
+ Compression advances the physical transcript, never the admission identity."""
+ return self.db.get_compression_lineage(session_id)[0] if session_id else session_id
+
+ def physical_target(self, ref):
+ return self.db.get_compression_tip(ref.session_id) or ref.session_id
+
def register(self, source):
self._require_admission_open()
entry = self.runner.session_store.get_or_create_session(source)
- sid = entry.session_id
+ sid = self.logical_owner(entry.session_id)
self.sessions.setdefault(sid, LiveSession(source, entry.session_key))
# SessionStore reserves routing metadata before the first AIAgent exists.
if self.db.get_session(sid) is None:
@@ -210,13 +218,14 @@ class SessionAuthority:
native = [row for row in rows if 'native_text_v1' in row['payload']]
if not native:
raise RuntimeStoreError('not_found')
- source, route = await check_native_route(self.runner, native[-1]['payload'], sid,
+ target = self.physical_target(SessionRef(self.profile_id, sid))
+ source, route = await check_native_route(self.runner, native[-1]['payload'], target,
available_source, adapter)
for row in rows:
if row['status'] == 'queued':
if 'native_text_v1' not in row['payload']:
raise RuntimeStoreError('invalid_params')
- await check_native_route(self.runner, row['payload'], sid, available_source, adapter)
+ await check_native_route(self.runner, row['payload'], target, available_source, adapter)
self._require_admission_open()
self.sessions.setdefault(sid, LiveSession(source, route))
if any(row['status'] == 'unknown' for row in rows):
@@ -363,7 +372,7 @@ class SessionAuthority:
check_local_input(self, ref, first)
if first is not None and 'native_text_v1' in first['payload']:
from gateway.session_envelope import check_native_route
- await check_native_route(self.runner, first['payload'], ref.session_id, live.source,
+ await check_native_route(self.runner, first['payload'], self.physical_target(ref), live.source,
self.runner._adapter_for_source(live.source))
# Cancellation may advance FIFO while the connector is awaited.
# Never let the successor inherit this row's fresh verdict.
diff --git a/tests/gateway/test_native_fifo_compression_identity.py b/tests/gateway/test_native_fifo_compression_identity.py
new file mode 100644
index 00000000000..a3b8158a30a
--- /dev/null
+++ b/tests/gateway/test_native_fifo_compression_identity.py
@@ -0,0 +1,71 @@
+"""Native FIFO identity survives a compression that moves the physical route to a child."""
+import asyncio
+
+import pytest
+
+
+async def test_native_fifo_identity_is_stable_across_compression(tmp_path, monkeypatch):
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+ from gateway.platforms.event import MessageEvent
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority, SessionAuthority
+ from gateway.session_ingress_context import native_callback
+ from hermes_constants import get_hermes_home
+ from hermes_state_runtime import list_session_admissions
+ from plugins.platforms.discord.adapter import DiscordAdapter
+
+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)
+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')
+ runner = GatewayRunner(GatewayConfig())
+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False))
+ runner.adapters = {Platform.DISCORD: adapter}
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter)
+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')
+ events = [MessageEvent(text=name, source=source, message_id=name) for name in ('first', 'second')]
+ receipts = []
+ for event in events:
+ with native_callback(runner, event, get_hermes_home()):
+ receipts.append(await authority.admit_native(event))
+ key = runner.session_store._generate_session_key(source)
+ parent = runner.session_store.peek_session_id(key)
+ assert receipts[0].ref.session_id == parent == receipts[1].ref.session_id
+
+ # Compression (the real publication path) moves the route to a child before the drain runs.
+ db = authority.db
+ db.append_message(parent, 'user', 'first')
+ db.append_message(parent, 'assistant', 'ok')
+ child = parent + '-child'
+ db.publish_compression_child(parent_session_id=parent, child_session_id=child, source='discord',
+ messages=[{'role': 'user', 'content': 'summary'}],
+ require_compression_lease=False)
+ assert runner.session_store.advance_compression_session(key, parent, child) is not None
+ assert runner.session_store.peek_session_id(key) == child
+
+ executed = []
+ async def handle(event):
+ executed.append(event.text)
+ # The turn's execution callbacks must still reach the logical owner's stream.
+ from gateway.run_turn_runner import TurnRunner
+ from gateway.turn_context import TurnContext
+ ctx = TurnContext(session_id=runner.session_store.peek_session_id(key), session_key=key, source=source)
+ assert TurnRunner(runner, ctx)._approval_owner[1] == parent
+ return 'ok'
+ monkeypatch.setattr(runner, '_handle_message', handle)
+ ref = receipts[0].ref
+ await SessionAuthority._drain(authority, ref)
+ assert executed == ['first', 'second'], executed
+ rows = list_session_admissions(db, session_id=parent, pending_only=False)
+ assert [(r['request_id'], r['status']) for r in rows] == [('first', 'terminal'), ('second', 'terminal')]
+
+ # An exact retry of the first event is the same admission, and a third follows the same FIFO.
+ with native_callback(runner, events[0], get_hermes_home()):
+ assert (await authority.admit_native(events[0])).admission_id == receipts[0].admission_id
+ third = MessageEvent(text='third', source=source, message_id='third')
+ with native_callback(runner, third, get_hermes_home()):
+ receipt = await authority.admit_native(third)
+ assert receipt.ref.session_id == parent
+ await SessionAuthority._drain(authority, ref)
+ assert executed == ['first', 'second', 'third']
+ await asyncio.sleep(0)