The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: hosted observation polls bounded terminal receipts; size error is distinct
Tekniumb4e4d812f585
diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 4b5f36d4e2e..ae29fdf2365 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -300,7 +300,12 @@ class GatewayControlServer:except Exception:encoded = b'{"ok": false, "error": "response serialization failed"}'if len(encoded) > _MAX_RESPONSE_BYTES:- encoded = b'{"ok": false, "error": "response too large"}'+ # Structured and distinct: a caller must not read an oversized answer as a drain.+ too_large: dict[str, Any] = {"ok": False, "error": "response_too_large", "code": "response_too_large",+ "limit": _MAX_RESPONSE_BYTES, "protocol": CONTROL_PROTOCOL_VERSION}+ if isinstance(request_id, (int, str)) and len(str(request_id)) <= 128:+ too_large["id"] = request_id+ encoded = json.dumps(too_large).encode("utf-8")return encoded + b"\n"def _session_ticket(self, request: dict, peer_subject: Optional[str]) -> dict:diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.pyindex 39da9e2996e..7dc80227674 100644--- a/gateway/session_hosted_rpc.py+++ b/gateway/session_hosted_rpc.py@@ -15,6 +15,8 @@ from gateway.session_contract import SessionRef, Submissionfrom hermes_state_runtime import RuntimeStoreError, list_session_admissions_RESULTLESS_OUTCOMES = frozenset({'interrupted', 'cancelled'})+# Encoded receipts per ``results`` read; under the 512 KiB private-socket response line.+_RESULTS_BUDGET_BYTES = 384 * 1024class HostedRoomAuthorityRPC:@@ -188,6 +190,32 @@ class HostedRoomAuthorityRPC:history.append({**receipt, 'role': 'assistant', 'content': receipt['text']})return history+ async def _results(self, params):+ """Terminal receipts only, never the transcript: one bounded response line.++ ``admission_ids`` narrows the read to the caller's pending callbacks. Each text+ keeps just over the driver's persisted bound, so its own truncation (and notice)+ is unchanged; newest receipts win the byte budget and the rest follow next poll.+ """+ wanted = params.get('admission_ids')+ if wanted is not None and (not isinstance(wanted, list) or len(wanted) > 256+ or not all(isinstance(i, str) and i for i in wanted)):+ raise RuntimeStoreError('invalid_params')+ from tui_gateway.hosted_room_driver import MAX_TERMINAL_TEXT_BYTES+ receipts, used = [], 0+ for row, task, generation in reversed(self._rows()):+ if row['status'] != 'terminal' or (wanted is not None and row['admission_id'] not in wanted):+ continue+ receipt = self._terminal(row, task, generation)+ raw = receipt['text'].encode('utf-8')+ if len(raw) > MAX_TERMINAL_TEXT_BYTES:+ receipt['text'] = raw[:MAX_TERMINAL_TEXT_BYTES + 4].decode('utf-8', 'ignore')+ used += len(json.dumps(receipt))+ if receipts and used > _RESULTS_BUDGET_BYTES:+ break+ receipts.append(receipt)+ return receipts[::-1]+async def _info(self, params):rows = self._rows()for row, task, generation in rows:@@ -267,6 +295,10 @@ class HostedRoomAuthorityRPC:def history(self, *, profile, session_id, source):return self._call('history', profile=profile, session_id=session_id, source=source)+ def results(self, *, profile, session_id, source, admission_ids=None):+ return self._call('results', profile=profile, session_id=session_id, source=source,+ admission_ids=admission_ids)+def info(self, *, profile, session_id, source):return self._call('info', profile=profile, session_id=session_id, source=source)diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.pyindex 496c4d11f5a..a5c0b331f73 100644--- a/gateway/session_hosted_transport.py+++ b/gateway/session_hosted_transport.py@@ -22,7 +22,7 @@ from gateway.session_hosted_rpc import HostedRoomAuthorityRPCfrom hermes_state_runtime import RuntimeStoreError, _epoch_BINDING = 'gateway.hosted.transport.v1:'-_OPERATIONS = frozenset({'resolve_exact', 'create', 'resume', 'submit', 'history',+_OPERATIONS = frozenset({'resolve_exact', 'create', 'resume', 'submit', 'history', 'results','info', 'interrupt', 'discard', 'approve'})# One chunk per private-socket exchange. The response is a single JSON line capped at# gateway.control_socket._MAX_RESPONSE_BYTES (512 KiB) on both the POSIX socket and the@@ -72,8 +72,8 @@ def owner_request(home, verb, params, *, timeout=30):response = json.loads(raw)if response.get('ok') is not True:reason = str(response.get('error', '')).split(': ')[-1]- if reason not in {'permission_denied', 'profile_mismatch', 'invalid_params',- 'unknown_execution', 'stale_generation', 'admission_conflict'}:+ if reason not in {'permission_denied', 'profile_mismatch', 'invalid_params', 'unknown_execution',+ 'stale_generation', 'admission_conflict', 'response_too_large'}:reason = 'runtime_draining'raise RuntimeStoreError(reason)if response.get('protocol') != 1 or response.get('id') != 1:@@ -327,10 +327,21 @@ class HostedRoomOwnerRPC(HostedRoomAuthorityRPC):self._monitor = threading.Thread(target=self._watch,args=(params['session_id'],), daemon=True)self._monitor.start()- if operation == 'history':+ if operation in {'history', 'results'}:self._deliver(result)return result+ def history(self, *, profile, session_id, source):+ """Driver recovery reads terminal receipts; a transcript past one response line+ degrades to the bounded receipt rows (all the driver matches on) instead of failing."""+ try:+ return super().history(profile=profile, session_id=session_id, source=source)+ except RuntimeStoreError as exc:+ if exc.reason != 'response_too_large':+ raise+ return [{**receipt, 'role': 'assistant', 'content': receipt['text']}+ for receipt in self.results(profile=profile, session_id=session_id, source=source)]+def _deliver(self, history):for row in history:with self._lock:@@ -344,8 +355,10 @@ class HostedRoomOwnerRPC(HostedRoomAuthorityRPC):with self._lock:if not self.callbacks:return- self.history(profile=self.binding['selector']['profile'],- session_id=session_id, source='bot_room')+ pending = list(self.callbacks)[:256]+ # Per-admission receipts only: polling never re-reads the transcript.+ self.results(profile=self.binding['selector']['profile'],+ session_id=session_id, source='bot_room', admission_ids=pending)time.sleep(0.25)except (OSError, ValueError, RuntimeStoreError):# Retain callbacks/input for normal driver history recovery; no retrydiff --git a/tests/gateway/test_hosted_observation_bounded.py b/tests/gateway/test_hosted_observation_bounded.pynew file mode 100644index 00000000000..9d5a9b383f0--- /dev/null+++ b/tests/gateway/test_hosted_observation_bounded.py@@ -0,0 +1,112 @@+"""Cross-profile hosted observation stays bounded when the member transcript is large.++The private owner socket caps one response line at 512 KiB. A long member session must not+stop the driver-side terminal watcher (callbacks retained, completed turn never observed),+and an oversized response must surface as its own structured error, not ``runtime_draining``.+"""+import asyncio+import json+import threading+from types import SimpleNamespace++import pytest+++def _server(home):+ from gateway.control_socket import GatewayControlServer+ descriptor = {'runtime_protocol': 1, 'state': 'ready', 'instance_id': 'test',+ 'authority_epoch': 1, 'served_profiles': [{'home': str(home), 'profile_id': str(home)}],+ 'capabilities': ['session-authority-v1'], 'api_origin': 'http://127.0.0.1:1',+ 'supervisor': 'none'}+ return GatewayControlServer(home, verb_handlers={'identify': lambda: descriptor})+++def _owner_pair(hosted_owner, tmp_path):+ from gateway.session_hosted_transport import install_hosted_transport+ authority, loop, _, _ = hosted_owner+ source, target = tmp_path / 'source', tmp_path / 'target'+ source.mkdir(mode=0o700)+ target.mkdir(mode=0o700)+ authority.profile_id = str(target)+ def attest(selector, operation, params):+ return {'owner': 'room-owner', 'target_home': authority.profile_id, 'prompt': 'input', 'attachments': []}+ servers = [_server(source), _server(target)]+ install_hosted_transport(servers[0], SimpleNamespace(profile_id=str(source)), loop, attest=attest)+ install_hosted_transport(servers[1], authority, loop, attest=lambda *a: None)+ for server in servers:+ assert asyncio.run_coroutine_threadsafe(server.start(), loop).result()+ return source, target, servers+++def test_watcher_delivers_terminal_once_with_bounded_polls_past_the_response_cap(hosted_owner, tmp_path, monkeypatch):+ from gateway import session_hosted_transport as transport+ from gateway.control_socket import _MAX_RESPONSE_BYTES+ from gateway.hosted_room_driver import TaskIdentity+ from hermes_state_runtime import claim_session_input, settle_session_input+ from tui_gateway.hosted_room_driver import _bounded_terminal_result+ authority, loop, _, _ = hosted_owner+ polls, real_request = [], transport.owner_request+ def recording(home, verb, params, **kwargs):+ result = real_request(home, verb, params, **kwargs)+ polls.append((params['operation'], len(json.dumps(result, default=str).encode())))+ return result+ monkeypatch.setattr(transport, 'owner_request', recording)+ source, target, servers = _owner_pair(hosted_owner, tmp_path)+ rpc = transport.HostedRoomOwnerRPC(home=target, source_home=source, room_id='room', member_id='member', profile='default')+ try:+ coords = dict(profile='default', source='bot_room')+ sid = rpc.create(**coords, title='Group: room')['session_id']+ # A long member conversation: the transcript alone exceeds the response line cap.+ for _ in range(3):+ authority.db.append_message(sid, 'assistant', 'transcript ' * 25_000)+ received, done = [], threading.Event()+ def terminal(receipt):+ received.append(receipt)+ done.set()+ receipt = rpc.submit(**coords, session_id=sid, prompt='input', task=TaskIdentity('room', 'task', 'thread', 'turn'),+ execution_generation=1, on_terminal=terminal)+ final = '\u20ac' * 100_000 # 300 KB UTF-8, 600 KB as an escaped JSON string+ row = claim_session_input(authority.db, epoch=authority.epoch, session_id=sid)+ settle_session_input(authority.db, epoch=authority.epoch, admission_id=row['admission_id'], generation=row['generation'],+ outcome='completed', result={'result': {'final_response': final}, 'usage': {}})+ assert done.wait(10), 'a completed turn must reach its callback despite the transcript size'+ rpc._monitor.join(5)+ assert not rpc._monitor.is_alive() and not rpc.callbacks+ assert received[0]['settlement_id'] == receipt['admission_id'] and received[0]['status'] == 'settled'+ # The driver persists the same bounded reply it would have built from the full text.+ assert _bounded_terminal_result(received[0]) == _bounded_terminal_result(+ {'message_id': receipt['admission_id'], 'text': final})+ watched = [size for operation, size in polls if operation not in {'create', 'submit'}]+ assert watched and 'history' not in [operation for operation, _ in polls]+ assert max(watched) < _MAX_RESPONSE_BYTES+ # Explicit recovery after the callback identity is lost still finds the receipt, once.+ history = rpc.history(**coords, session_id=sid)+ assert [m['settlement_id'] for m in history if m.get('task_id') == 'task'] == [receipt['admission_id']]+ assert len(received) == 1+ finally:+ with rpc._lock:+ rpc.callbacks.clear()+ for server in servers:+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()+++def test_oversized_owner_response_is_a_distinct_structured_error(hosted_owner, tmp_path):+ from gateway.control_socket import _MAX_RESPONSE_BYTES+ from gateway.session_hosted_transport import HostedRoomOwnerRPC+ from hermes_state_runtime import RuntimeStoreError+ _, loop, _, _ = hosted_owner+ source, target, servers = _owner_pair(hosted_owner, tmp_path)+ try:+ servers[1].private_handlers['hosted-producer'] = lambda params, peer: 'x' * _MAX_RESPONSE_BYTES+ raw = json.dumps({'protocol': 1, 'id': 7, 'verb': 'hosted-producer', 'params': {}}).encode()+ response = json.loads(servers[1].handle_request_line(raw, 'peer'))+ assert response['ok'] is False and response['id'] == 7+ assert response['error'] == response['code'] == 'response_too_large'+ assert response['limit'] == _MAX_RESPONSE_BYTES+ rpc = HostedRoomOwnerRPC(home=target, source_home=source, room_id='room', member_id='member', profile='default')+ with pytest.raises(RuntimeStoreError) as exc:+ rpc.info(profile='default', session_id='s', source='bot_room')+ assert exc.value.reason == 'response_too_large'+ finally:+ for server in servers:+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()