The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): ack a refused native admission instead of killing the reader
Tekniumd8abc7b4e994
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 9b7a8985714..157d9655de2 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -27,6 +27,7 @@ from gateway.platforms.event import ProcessingOutcomefrom agent.i18n import tfrom gateway.relay.adapter_discord_interaction import RelayDiscordInteractionMixinfrom gateway.relay.descriptor import CapabilityDescriptor+from hermes_state_runtime import RuntimeStoreErrorfrom gateway.relay.egress import (EGRESS_DECLINE_CODE,decline_error,@@ -38,6 +39,9 @@ from gateway.relay.transport import RelayTransportfrom datetime import UTClogger = logging.getLogger(__name__)+# Native admission refusals a redelivery cannot change (sender, route or payload).+_PERMANENT_REFUSALS = frozenset({'permission_denied', 'invalid_params', 'admission_conflict',+ 'profile_mismatch', 'not_found'})# The drain-path going-idle ACK budget must stay strictly under the runner's# default adapter disconnect timeout (5s) or cancellation fires before@@ -898,8 +902,18 @@ class RelayAdapter(RelayDiscordInteractionMixin, BasePlatformAdapter):# time must not change the fingerprint of a retried provider identity.event.timestamp = datetime.fromtimestamp(0, UTC)# Wait only for the SQLite receipt, never inference or outbound ACKs- # (those need this same WS reader). Exceptions deliberately suppress ACK.- if await admit_producer(self, event) is None and getattr(event, '_consumer_reply', None):+ # (those need this same WS reader). A permanent refusal returns, so the+ # transport ACKs it (a replay would be refused again: main's runner dropped+ # it too); any other failure withholds the ACK so the connector redelivers.+ try:+ receipt = await admit_producer(self, event)+ except RuntimeStoreError as exc:+ if exc.reason not in _PERMANENT_REFUSALS:+ raise+ logger.warning("relay inbound refused (%s) for %s chat=%s; acknowledged, not replayed",+ exc.reason, event.source.platform.value, event.source.chat_id)+ return+ if receipt is None and getattr(event, '_consumer_reply', None):# A post_gateway_admission plugin consumed it (never committed); its reply is# sent off this reader, like an executed admission's.from gateway.session_ingress import deliver_responsediff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex 9f05b087c30..d3e99284057 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -937,8 +937,14 @@ class WebSocketRelayTransport:returnfrom gateway.session_ingress_context import relay_callbackevent = _event_from_wire(frame.get("event", {}))- with relay_callback(self, event):- await self._inbound(event)+ try:+ with relay_callback(self, event):+ await self._inbound(event)+ except Exception:+ # A handler failure is not a socket failure: keep this reader, withhold the+ # ACK so the connector redelivers the buffered frame later.+ logger.exception("relay: inbound handler failed; frame left unacknowledged")+ return# A replayed buffered delivery carries a bufferId; ack AFTER the handler# has taken it so the connector advances its cursor (no dup).buffer_id = frame.get("bufferId")diff --git a/tests/gateway/relay/test_relay_native_refusal_ack.py b/tests/gateway/relay/test_relay_native_refusal_ack.pynew file mode 100644index 00000000000..aa5489e888a--- /dev/null+++ b/tests/gateway/relay/test_relay_native_refusal_ack.py@@ -0,0 +1,70 @@+"""A refused relay native admission is acknowledged on the same socket, never a replay loop."""+import asyncio+import json++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.run import GatewayRunner+from gateway.session_authority import initialize_session_authority+from gateway.session_results import execution_result+from tests.waiting import async_wait_until+++async def test_refused_relay_frame_is_acked_and_the_reader_keeps_serving(tmp_path, monkeypatch):+ websockets = pytest.importorskip('websockets')+ from gateway.relay.adapter import RelayAdapter+ from gateway.relay.descriptor import CapabilityDescriptor+ from gateway.relay.ws_transport import WebSocketRelayTransport++ sockets, outgoing, ready = [], [], asyncio.Queue()+ descriptor = CapabilityDescriptor(1, 'telegram', 'Fixture', 4096, False, True, False, 'plain', 'chars')++ async def connector(ws):+ await ws.recv() # hello+ await ws.send(json.dumps({'type': 'descriptor', 'descriptor': json.loads(descriptor.to_json())}) + '\n')+ sockets.append(ws)+ await ready.put(ws)+ async for line in ws:+ frame = json.loads(line)+ outgoing.append(frame)+ if frame['type'] == 'outbound':+ await ws.send(json.dumps({'type': 'outbound_result', 'requestId': frame['requestId'],+ 'result': {'success': True, 'message_id': 'sent'}}) + '\n')++ turns = []++ async def turn(event, *_args, **_kwargs):+ turns.append(event.text)+ execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}+ return 'ok'++ async with websockets.serve(connector, '127.0.0.1', 0) as relay:+ transport = WebSocketRelayTransport(+ f'ws://127.0.0.1:{relay.sockets[0].getsockname()[1]}/relay', 'telegram', 'fixture-bot',+ gateway_id='fixture-gateway', upgrade_secret='fixture-secret', reconnect=True, reconnect_backoff_s=.05)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='relay-refusal')+ adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor, transport)+ adapter.gateway_runner = runner+ runner.adapters[Platform.RELAY] = adapter+ runner._wire_adapter_handlers(adapter)+ try:+ assert await adapter.connect()+ ws = await asyncio.wait_for(ready.get(), 5)+ source = {'platform': 'telegram', 'chat_id': 'relay-chat', 'chat_type': 'dm', 'user_id': 'relay-user'}+ # A route this single-profile gateway does not serve: refused (profile_mismatch) on every replay.+ refused = {'text': 'for another profile', 'message_id': 'r1', 'source': {**source, 'profile': 'foreign'}}+ ok = {'text': 'hello', 'message_id': 'r2', 'source': source}+ for event, buffer_id in ((refused, 'buf-refused'), (ok, 'buf-ok')):+ await ws.send(json.dumps({'type': 'inbound', 'event': event, 'bufferId': buffer_id}) + '\n')+ acked = lambda: {f.get('bufferId') for f in outgoing if f.get('type') == 'inbound_ack'}+ await async_wait_until(lambda: {'buf-refused', 'buf-ok'} <= acked() and turns,+ timeout=20, what='both frames acknowledged and the valid one run')+ assert turns == ['hello']+ assert len(sockets) == 1, 'the refusal tore the relay socket down and re-dialed'+ finally:+ await adapter.disconnect()+ authority.db.close()