Skip to content

The agent that grows with you

fix(gateway): a busy same-sender burst is one authority admission again

Tekniuma3b8279ad88c
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 1022adda4b9..c2dfef860b2 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -3876,6 +3876,8 @@ class BasePlatformAdapter(ABC):
state = self._text_debounce_store().pop(session_key, None)
if state is not None:
state.cancel_timer()
+ from gateway.session_ingress_burst import discard_busy_burst
+ discard_busy_burst(self, session_key)
# ── Session task + guard ownership helpers: paired with the _session_tasks owner map so
# reconciliation is deterministic across completion, /stop /new /reset, and stale-lock heal.
@@ -4033,7 +4035,7 @@ class BasePlatformAdapter(ABC):
# On-entry self-heal: clear a guard whose owner task already exited.
if session_key in self._active_sessions:
self._heal_stale_session_lock(session_key)
- if session_key in self._active_sessions:
+ if session_key in self._active_sessions or self._shared_burst_pending(event, session_key):
await self._handle_message_while_active(event, session_key)
return
# Guard installed synchronously BEFORE the task spawns so a second message can't race in.
@@ -4044,6 +4046,10 @@ class BasePlatformAdapter(ABC):
runner = getattr(self._message_handler, '__self__', None)
return getattr(runner, 'session_authority', None) is not None and not event.get_command()
+ def _shared_burst_pending(self, event: MessageEvent, session_key: str) -> bool:
+ from gateway.session_ingress_burst import holds_busy_burst
+ return self._shared_runtime_owns_input(event) and holds_busy_burst(self, session_key)
+
def _pending_recovery_owners(self, event: MessageEvent, session_key: str) -> list:
"""Adapters whose pending slot may hold *event* after busy admission: this one, plus the
runner's current delivery adapter for its source when that replacement has no live guard."""
@@ -4066,8 +4072,8 @@ class BasePlatformAdapter(ABC):
commands / clarify replies dispatch inline, everything else is queued."""
# The shared runtime's durable FIFO replaces the adapter's busy-message slot.
if self._shared_runtime_owns_input(event):
- from gateway.session_ingress import dispatch_shared_busy
- await dispatch_shared_busy(self, event, session_key)
+ from gateway.session_ingress_burst import dispatch_busy_burst
+ await dispatch_busy_burst(self, event, session_key) # main's photo/text burst merge
return
# Bypass commands run inline: queued they'd leak as user text (/new) or deadlock
# (/approve, /deny — the agent is blocked on Event.wait). Dispatch inline by
diff --git a/gateway/session_ingress_burst.py b/gateway/session_ingress_burst.py
new file mode 100644
index 00000000000..96ff54ede22
--- /dev/null
+++ b/gateway/session_ingress_burst.py
@@ -0,0 +1,132 @@
+"""Busy same-sender bursts become one shared-runtime admission.
+
+Main merged a busy photo burst into the pending slot and debounced queue-mode text from one sender
+(``BasePlatformAdapter._queue_text_debounce``) so a thought split over two messages ran as one
+turn. The authority FIFO admits each input as it arrives, so the burst is held here for main's
+bounded window first, then committed once through ``dispatch_shared_busy``. Every absorbed caller
+returns only after that commit, with its acceptance copied from it (committed before ACK), and
+input that arrives later never commits before the burst.
+"""
+import asyncio
+from dataclasses import dataclass, field
+from functools import partial
+import time
+
+from gateway.platforms.event import MessageEvent, MessageType
+
+
+@dataclass(eq=False)
+class _Burst:
+ head: MessageEvent
+ done: asyncio.Future
+ first_ts: float
+ last_ts: float
+ timer: asyncio.Task | None = None
+ commit: asyncio.Task | None = None
+ absorbed: list = field(default_factory=list)
+
+
+def _kind(adapter, event):
+ if event.message_type == MessageType.PHOTO and not event.internal:
+ return 'photo'
+ return 'text' if adapter._is_queue_text_debounce_candidate(event) else None
+
+
+def _state(adapter, name):
+ return adapter.__dict__.setdefault(name, {})
+
+
+def holds_busy_burst(adapter, session_key):
+ """A burst is held or committing: later input for the route must queue behind it."""
+ return any(session_key in adapter.__dict__.get(name, ()) for name in ('_shared_bursts', '_shared_burst_commits'))
+
+
+async def dispatch_busy_burst(adapter, event, session_key):
+ """``dispatch_shared_busy`` for one busy input, merging a same-sender PHOTO+PHOTO or
+ queue-mode TEXT+TEXT burst first."""
+ from gateway.platforms.base import merge_pending_message_event
+ from gateway.session_ingress import dispatch_shared_busy
+ kind, bursts = _kind(adapter, event), _state(adapter, '_shared_bursts')
+ while (burst := bursts.get(session_key)) is not None:
+ if kind is not None and kind == _kind(adapter, burst.head) and adapter._can_merge_text_debounce_events(
+ burst.head, event):
+ merge_pending_message_event({session_key: burst.head}, session_key, event, merge_text=kind == 'text')
+ burst.absorbed.append(event)
+ burst.last_ts = time.monotonic()
+ _arm(adapter, session_key, burst)
+ return await _accepted(burst, event)
+ await asyncio.shield(_flush(adapter, session_key, burst)) # a different sender or kind: in order
+ previous = _state(adapter, '_shared_burst_commits').get(session_key)
+ if kind is None:
+ if previous is not None:
+ await asyncio.wait({previous})
+ return await dispatch_shared_busy(adapter, event, session_key)
+ now = time.monotonic()
+ burst = bursts[session_key] = _Burst(event, asyncio.get_running_loop().create_future(), now, now)
+ _arm(adapter, session_key, burst)
+ return await _accepted(burst, event)
+
+
+async def _accepted(burst, event):
+ await asyncio.shield(burst.done) # raises the merged admission's own refusal
+ event._gateway_accepted = burst.head._gateway_accepted
+
+
+def _track(adapter, task):
+ adapter._background_tasks.add(task)
+ task.add_done_callback(adapter._background_tasks.discard)
+ return task
+
+
+def _arm(adapter, session_key, burst):
+ if burst.timer is not None:
+ burst.timer.cancel()
+ delay = max(0.0, min(burst.last_ts + adapter._busy_text_debounce_seconds,
+ burst.first_ts + adapter._busy_text_hard_cap_seconds) - time.monotonic())
+
+ async def fire():
+ await asyncio.sleep(delay)
+ await asyncio.shield(_flush(adapter, session_key, burst))
+ burst.timer = _track(adapter, asyncio.create_task(fire()))
+
+
+def _flush(adapter, session_key, burst):
+ """Start committing ``burst`` (once), after any earlier commit for the route."""
+ if burst.commit is None:
+ bursts, tails = _state(adapter, '_shared_bursts'), _state(adapter, '_shared_burst_commits')
+ if bursts.get(session_key) is burst:
+ del bursts[session_key]
+ if burst.timer is not asyncio.current_task():
+ burst.timer.cancel()
+ burst.commit = tails[session_key] = _track(adapter, asyncio.create_task(
+ _commit(adapter, session_key, burst, tails.get(session_key))))
+ burst.commit.add_done_callback(lambda task: tails.get(session_key) is task and tails.pop(session_key))
+ burst.commit.add_done_callback(partial(_settle, burst))
+ return burst.commit
+
+
+async def _commit(adapter, session_key, burst, previous):
+ from gateway.session_ingress import dispatch_shared_busy
+ if previous is not None:
+ await asyncio.wait({previous})
+ await dispatch_shared_busy(adapter, burst.head, session_key)
+
+
+def _settle(burst, task):
+ """Every absorbed caller sees the merged admission's outcome, refusal or cancellation."""
+ if burst.done.done():
+ return
+ if task.cancelled():
+ burst.done.cancel()
+ elif task.exception() is not None:
+ burst.done.set_exception(task.exception())
+ else:
+ burst.done.set_result(None)
+
+
+def discard_busy_burst(adapter, session_key):
+ """``/stop`` / ``/new`` drop a held burst as main dropped its debounce buffer; nothing was ACKed."""
+ burst = adapter.__dict__.get('_shared_bursts', {}).pop(session_key, None)
+ if burst is not None:
+ burst.timer.cancel()
+ burst.done.done() or burst.done.set_result(None)
diff --git a/tests/gateway/test_busy_burst_merge_shared.py b/tests/gateway/test_busy_burst_merge_shared.py
new file mode 100644
index 00000000000..390a3894cd5
--- /dev/null
+++ b/tests/gateway/test_busy_burst_merge_shared.py
@@ -0,0 +1,93 @@
+"""A busy same-sender burst is one authority admission, as main merged it into one turn (N54).
+
+Main merged a busy photo burst into the pending slot and debounced queue-mode split text from one
+sender. Under the session authority every busy input was admitted on its own, so a thought split
+over two messages (or a photo burst) ran as separate turns. Real GatewayRunner, DiscordAdapter,
+SessionAuthority and drain over SQLite; the running user turn is a stand-in holding the slot.
+"""
+import asyncio
+
+import pytest
+
+PNG = b'\x89PNG\r\n\x1a\n' + b'\x00' * 24
+
+# (case, follow-ups as (sender, text, photo?), expected admitted (text, media count) after 'A')
+CASES = [
+ ('split-text', [('42', 'first half', False), ('42', 'second half', False)],
+ [('first half\nsecond half', 0)]),
+ ('photo-burst', [('42', 'look', True), ('42', '', True)], [('look', 2)]),
+ # Different senders never merge, and arrival order holds.
+ ('two-senders', [('42', 'mine', False), ('43', 'theirs', False)], [('mine', 0), ('theirs', 0)]),
+]
+
+
[email protected]('case,follow_ups,expected', CASES, ids=[c[0] for c in CASES])
+async def test_busy_burst_is_admitted_once(monkeypatch, tmp_path, case, follow_ups, expected):
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+ from gateway.platforms.base import SendResult
+ from gateway.platforms.event import MessageEvent, MessageType
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_ingress_burst import holds_busy_burst
+ from gateway.session_results import execution_result
+ from hermes_state_runtime import list_session_admissions
+ from plugins.platforms.discord.adapter import DiscordAdapter
+
+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42,43')
+ runner = GatewayRunner(GatewayConfig(group_sessions_per_user=False)) # one shared room session
+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False,
+ extra={'group_sessions_per_user': False}))
+
+ async def send(chat_id, content, reply_to=None, metadata=None):
+ return SendResult(success=True, message_id='sent')
+ monkeypatch.setattr(adapter, 'send', send)
+ adapter.gateway_runner = runner
+ runner.adapters = {Platform.DISCORD: adapter}
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter, busy_text_mode='queue')
+ running, finish = asyncio.Event(), asyncio.Event()
+ executed = []
+
+ async def turn(event, source, quick_key, run_generation):
+ executed.append(event.text)
+ if event.text == 'A':
+ running.set()
+ await finish.wait()
+ captured = execution_result.get()
+ if captured is not None:
+ captured['result'] = {'final_response': 'ok', 'messages': []}
+ return 'ok'
+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)
+
+ def event(sender, text, photo, n):
+ source = adapter.build_source(chat_id='room', chat_type='group', user_id=sender)
+ if not photo:
+ return MessageEvent(text=text, source=source, message_id=f'm{n}')
+ path = tmp_path / f'p{n}.png'
+ path.write_bytes(PNG + bytes([n]))
+ return MessageEvent(text=text, source=source, message_id=f'm{n}', message_type=MessageType.PHOTO,
+ media_urls=[str(path)], media_types=['image/png'])
+
+ await adapter.handle_message(event('42', 'A', False, 0))
+ await asyncio.wait_for(running.wait(), 10)
+ sent = [event(*spec, n) for n, spec in enumerate(follow_ups, 1)]
+ key = adapter._event_session_key(sent[0])
+ callers = []
+ for e in sent: # in arrival order: each lands while the earlier one is still held
+ callers.append(asyncio.create_task(adapter.handle_message(e)))
+ async with asyncio.timeout(5):
+ while not (holds_busy_burst(adapter, key) or e._gateway_accepted):
+ await asyncio.sleep(0)
+ # Each caller returns only once its input is durably committed (committed before ACK).
+ await asyncio.wait_for(asyncio.gather(*callers), 10)
+ assert all(e._gateway_accepted is True for e in sent), [e._gateway_accepted for e in sent]
+ owner = runner.session_store.peek_session_id(runner.session_store._generate_session_key(sent[0].source))
+ rows = list_session_admissions(authority.db, session_id=owner, pending_only=False)
+ assert [(r['payload']['text'], len(r['payload']['native_text_v1'].get('media', [])))
+ for r in rows[1:]] == expected
+ finish.set()
+ async with asyncio.timeout(10):
+ while len(executed) < 1 + len(expected):
+ await asyncio.sleep(0.01)
+ await asyncio.to_thread(authority.db.close)