Skip to content

The agent that grows with you

fix(gateway): bound rollback.session_diff by its bytes on the wire

kshitijk4poor355fd340ab41
diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.py
index fe01a86cca1..017f49508c8 100644
--- a/gateway/session_tui_ops.py
+++ b/gateway/session_tui_ops.py
@@ -11,6 +11,7 @@ them. ``dispatch`` already runs every handler under the owning profile's scope (
import asyncio
from datetime import datetime
import json
+import re
import uuid
from functools import partial
from pathlib import Path
@@ -195,8 +196,10 @@ async def pause_delegation(connection, ref, params):
_ROLLBACK_FIELDS = {'list': {'session_id', 'profile'}, 'diff': {'session_id', 'profile', 'hash'},
'restore': {'session_id', 'profile', 'hash', 'file_path', 'all'},
'session_diff': {'session_id', 'profile'}}
-# ``rollback.session_diff`` body bound: well inside one 8 MiB frame (the classic CLI shows 400 lines).
-_SESSION_DIFF_CHARS = 2 * 1024 * 1024
+# ``rollback.session_diff`` stat + body bound, in bytes on the wire: half the 8 MiB frame every client
+# accepts (``hermes_cli/gateway_client.py``). Counted JSON-escaped, since a control character is one
+# character but six bytes (``\u0001``); the classic CLI shows 400 lines either way.
+_SESSION_DIFF_BYTES = 4 * 1024 * 1024
async def rollback(connection, ref, params, *, kind):
@@ -288,11 +291,32 @@ def _session_diff(mgr, cwd, refusal):
if not result.get('success'):
return {'enabled': True, 'success': False, 'error': str(result.get('error') or '')}
diff = result.get('diff', '')
- body = diff if len(diff) <= _SESSION_DIFF_CHARS else diff[:_SESSION_DIFF_CHARS].rpartition('\n')[0]
- return {'enabled': True, 'success': True, 'stat': result.get('stat', ''), 'diff': body,
+ stat = _fit_frame(result.get('stat', ''), _SESSION_DIFF_BYTES)
+ body = _fit_frame(diff, _SESSION_DIFF_BYTES - _wire_bytes(stat))
+ return {'enabled': True, 'success': True, 'stat': stat, 'diff': body,
'diff_lines': len(diff.splitlines()), 'empty': bool(result.get('empty'))}
+def _wire_bytes(text):
+ """Bytes ``text`` takes inside a frame: JSON-escaped as ``serialize_frame`` writes it, then UTF-8."""
+ return len(json.dumps(text, ensure_ascii=False).encode('utf-8', 'surrogatepass')) - 2
+
+
+def _fit_frame(text, budget):
+ """The longest whole-line prefix of ``text`` whose wire size fits ``budget`` bytes. The caller
+ reports the uncut line count, so the client names the cut instead of the frame dropping the socket."""
+ if len(text) * 6 <= budget or (len(text) <= budget and _wire_bytes(text) <= budget):
+ return text
+ kept, used = [], 0
+ # Lines end at ``\n`` only (``splitlines`` would also cut at ``\r``, ``\f``, U+2028 inside a diff line).
+ for line in re.split(r'(?<=\n)', text[:budget + 1]): # chars cost >= 1 byte; +1 keeps a cut line over
+ used += _wire_bytes(line)
+ if used > budget:
+ break
+ kept.append(line)
+ return ''.join(kept).removesuffix('\n')
+
+
async def _rewind_last_turn(connection, ref):
"""Drop the newest user turn and everything after it (main's full ``/rollback`` restore) via the
owner's revision-fenced ``rewind`` mutation; 0 when the transcript has no user turn."""
diff --git a/tests/gateway/fixtures/local_recovery_probe.py b/tests/gateway/fixtures/local_recovery_probe.py
index 336a95712b7..0ff95d330b6 100644
--- a/tests/gateway/fixtures/local_recovery_probe.py
+++ b/tests/gateway/fixtures/local_recovery_probe.py
@@ -64,10 +64,10 @@ async def rpc(ws, method, **params):
return reply
-def websocket(home, desc):
+def websocket(home, desc, **kw):
grant = control(home, 'session-ticket', {'profile_id': str(home), 'instance_id': desc['instance_id'], 'purpose': 'interactive'})
return connect(desc['api_origin'].replace('http:', 'ws:') + '/api/ws',
- subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']])
+ subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']], **kw)
@contextmanager
diff --git a/tests/gateway/test_session_tui_ops_session_diff.py b/tests/gateway/test_session_tui_ops_session_diff.py
index dc4fc337859..d9135268a03 100644
--- a/tests/gateway/test_session_tui_ops_session_diff.py
+++ b/tests/gateway/test_session_tui_ops_session_diff.py
@@ -2,13 +2,18 @@
frozen checkpoint policy decides, so a ``--checkpoints`` launch on a profile whose config leaves
checkpoints off still diffs, and the whole body comes back as data (no chat-sized cut)."""
import asyncio
+import json
import pytest
+from gateway.session_tui_ops import _fit_frame
from tests.gateway.fixtures.local_recovery_probe import rpc, websocket
from tests.gateway.test_session_busy_controls import owner
from tests.gateway.test_session_tui_ops import _checkpoint, _git_rpc
+# The classic CLI's frame cap (hermes_cli/gateway_client.py ``connect(..., max_size=...)``).
+CLIENT_MAX_FRAME = 8 * 1024 * 1024
+
@pytest.mark.platforms("linux")
def test_session_diff_follows_the_sessions_checkpoint_policy_and_keeps_the_whole_body(tmp_path):
@@ -38,3 +43,40 @@ def test_session_diff_follows_the_sessions_checkpoint_policy_and_keeps_the_whole
({'session_id': sid, 'profile': 'foreign'}, 'profile_mismatch')]:
assert (await rpc(ws, 'rollback.session_diff', **params))['error']['message'] == reason
asyncio.run(probe())
+
+
+def test_an_escape_heavy_session_diff_fits_the_clients_frame_and_names_its_cut(tmp_path):
+ """CLI-26: 2.4 Mi control characters are 14 MB JSON-escaped. The reply is cut to fit the classic
+ CLI's 8 MiB frame and says how many lines the whole diff has, instead of dropping the socket."""
+ with owner(tmp_path) as (home, _peer, desc):
+ work = tmp_path / 'work'
+ work.mkdir()
+ (work / 'big.txt').write_text('original\n')
+
+ async def probe():
+ async with websocket(home, desc, max_size=CLIENT_MAX_FRAME) as ws:
+ sid = (await rpc(ws, 'session.create', request_id='launch', source='cli', toolsets=[],
+ cwd=str(work), checkpoints=True))['result']['session_id']
+ await asyncio.to_thread(_checkpoint, home, work, 'before write_file')
+ (work / 'big.txt').write_text(('\x01' * 1000 + '\n') * 2400)
+ result = (await _git_rpc(ws, 'rollback.session_diff', session_id=sid))['result']
+ assert result['success'] is True and 'big.txt' in result['stat'], result['stat']
+ shown = result['diff'].splitlines()
+ assert 400 < len(shown) < result['diff_lines'] and result['diff_lines'] > 2400
+ assert len(json.dumps(result, ensure_ascii=False).encode()) <= CLIENT_MAX_FRAME // 2
+ # The connection survives for the next call.
+ assert (await _git_rpc(ws, 'rollback.list', session_id=sid))['result']['enabled'] is True
+ asyncio.run(probe())
+
+
+def test_fit_frame_never_turns_a_cut_over_budget_line_into_a_fitting_one():
+ """The prefix slice keeps one char past the budget, so a line it cuts still breaks the loop."""
+ assert _fit_frame('abcdefgh', 5) == ''
+ assert _fit_frame('ab\ncdefgh', 5) == 'ab'
+
+
+def test_fit_frame_cuts_only_at_a_newline():
+ """A carriage return, form feed or U+2028 inside a diff line is not a line end: the cut never lands on one."""
+ for sep in ('\r', '\x0c', '\u2028'):
+ assert _fit_frame(f'+a\n+b{sep}cdefghij\n', 9) == '+a', repr(sep)