Skip to content

Commit dca761a

Browse files
committed
fix(turn-driver): stream oversized same-turn rollout records in _native_reader
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent bdf8e07 commit dca761a

2 files changed

Lines changed: 480 additions & 17 deletions

File tree

‎loopx/control_plane/turn_driver/codex_context_history.py‎

Lines changed: 292 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@
99
"""
1010
from __future__ import annotations
1111

12+
import codecs
1213
import hashlib
1314
import json
1415
import os
1516
import re
1617
import stat
17-
from collections.abc import Iterator
18+
from collections.abc import Iterator, Mapping
1819
from contextlib import contextmanager
1920
from pathlib import Path
2021
from typing import Any, BinaryIO
@@ -31,10 +32,25 @@
3132
_IO_CHUNK_BYTES = 64 * 1024
3233
# Bound one decoded protocol record, not the history or the replay interval.
3334
_MAX_RECORD_BYTES = 16 * 1024 * 1024
35+
_MAX_HEADER_FIELD_BYTES = 16 * 1024
36+
_MAX_PRIMITIVE_BYTES = 1024
37+
_MAX_SKIP_DEPTH = 256
3438
_MAX_SELECTED_REPLAY_READS = 32
3539
_MAX_COMPLETE_REREADS = 32
3640
_SHELL_OUTPUT = re.compile(r"\AChunk ID: [^\r\n]+\nWall time: [0-9.]+ seconds\n"
3741
r"Process exited with code 0\n(?:Original token count: [0-9]+\n)?Output:\n(.*)\Z", re.DOTALL)
42+
_JSON_WS_STOP = re.compile(rb"[^ \t\r\n]")
43+
_JSON_STR_SPAN = re.compile(rb'(?:[^"\\\x00-\x1f]+|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})){1,64}')
44+
_JSON_TOKEN_STOP = re.compile(rb"[ \t\r\n,\}\]]")
45+
_PREFIX_PAYLOAD_SPEC: dict[str, Any] = {
46+
"type": None,
47+
"call_id": None,
48+
"name": None,
49+
"turn_id": None,
50+
"item": {"type": None, "id": None, "exit_code": None},
51+
"internal_chat_message_metadata_passthrough": {"turn_id": None},
52+
}
53+
_PREFIX_RECORD_SPEC: dict[str, Any] = {"type": None, "payload": _PREFIX_PAYLOAD_SPEC}
3854
_REPLAY_ERRORS = (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError)
3955
_SOURCE_IDENTITY_FIELDS = ("path", "device", "inode", "metadata_sha256", "model", "permission_mode")
4056

@@ -110,21 +126,264 @@ def _region_digest(stream: BinaryIO, start: int, end: int) -> str:
110126
return digest.hexdigest()
111127

112128

113-
def _reader_tail(stream: BinaryIO, end: int) -> Iterator[tuple[int, dict[str, Any]]]:
114-
"""Walk backwards from the hook, one bounded record at a time."""
115-
cursor, buffer = end, b""
116-
while cursor:
117-
start = max(0, cursor - _IO_CHUNK_BYTES)
129+
def _reader_spans(stream: BinaryIO, end: int) -> Iterator[tuple[int, int]]:
130+
"""Walk backwards from the hook one bounded chunk at a time, yielding line spans."""
131+
if end <= 0:
132+
return
133+
stream.seek(end - 1)
134+
if stream.read(1) != b"\n":
135+
raise ValueError("incomplete native reader record")
136+
line_end = end
137+
cursor = end - 1
138+
while cursor > 0:
139+
chunk_start = max(0, cursor - _IO_CHUNK_BYTES)
140+
stream.seek(chunk_start)
141+
chunk = stream.read(cursor - chunk_start)
142+
if len(chunk) != cursor - chunk_start:
143+
raise ValueError("native reader interval was truncated")
144+
pos = len(chunk)
145+
while True:
146+
split = chunk.rfind(b"\n", 0, pos)
147+
if split < 0:
148+
break
149+
line_start = chunk_start + split + 1
150+
if line_end > line_start:
151+
yield line_start, line_end
152+
line_end = line_start
153+
pos = split
154+
cursor = chunk_start
155+
if line_end > 0:
156+
yield 0, line_end
157+
158+
159+
def _reject_json_constant(token: str) -> Any:
160+
raise ValueError(f"unsupported JSON constant: {token}")
161+
162+
163+
class _JsonSliceCursor:
164+
"""Chunked JSON validator and header extractor for oversized Turn-prefix records."""
165+
166+
def __init__(self, stream: BinaryIO, start: int, stop: int) -> None:
118167
stream.seek(start)
119-
buffer = stream.read(cursor - start) + buffer
120-
cursor = start
121-
while (split := buffer.rstrip(b"\n").rfind(b"\n")) >= 0:
122-
raw, buffer = buffer[split + 1:], buffer[:split + 1]
123-
if len(raw) > _MAX_RECORD_BYTES:
124-
raise ValueError("unsupported native reader record")
125-
yield cursor + split + 1, json.loads(raw)
126-
if len(buffer) > _MAX_RECORD_BYTES:
127-
raise ValueError("unsupported native reader record")
168+
self._stream = stream
169+
self._cursor = start
170+
self._stop = stop
171+
self._buf = b""
172+
self._pos = 0
173+
174+
def _ensure(self, n: int = 1) -> bool:
175+
while len(self._buf) - self._pos < n and self._cursor < self._stop:
176+
chunk = self._stream.read(min(_IO_CHUNK_BYTES, self._stop - self._cursor))
177+
if not chunk:
178+
raise ValueError("native reader interval was truncated")
179+
self._cursor += len(chunk)
180+
self._buf = self._buf[self._pos:] + chunk
181+
self._pos = 0
182+
return len(self._buf) - self._pos >= n
183+
184+
def skip_ws(self) -> int | None:
185+
while True:
186+
if self._pos >= len(self._buf) and not self._ensure(1):
187+
return None
188+
match = _JSON_WS_STOP.search(self._buf, self._pos)
189+
if match is not None:
190+
self._pos = match.start()
191+
return self._buf[self._pos]
192+
self._pos = len(self._buf)
193+
194+
def consume_byte(self, expected: int) -> None:
195+
if not self._ensure(1) or self._buf[self._pos] != expected:
196+
raise ValueError("malformed native JSON record")
197+
self._pos += 1
198+
199+
def scan_string(self, *, capture_limit: int | None = None, allow_long_key: bool = False) -> str:
200+
self.consume_byte(0x22)
201+
decoder = codecs.getincrementaldecoder("utf-8")("strict")
202+
raw: bytearray | None = bytearray(b'"') if capture_limit is not None else None
203+
204+
def _append_raw(data: bytes) -> bytearray | None:
205+
if raw is None or capture_limit is None:
206+
return None
207+
if len(raw) + len(data) > capture_limit:
208+
if not allow_long_key:
209+
raise ValueError("oversized JSON header field")
210+
return None
211+
raw.extend(data)
212+
return raw
213+
214+
while True:
215+
if self._pos >= len(self._buf) and not self._ensure(1):
216+
raise ValueError("unterminated JSON string")
217+
match = _JSON_STR_SPAN.match(self._buf, self._pos)
218+
if match is not None:
219+
seg = self._buf[self._pos:match.end()]
220+
decoder.decode(seg, final=False)
221+
raw = _append_raw(seg)
222+
self._pos = match.end()
223+
continue
224+
ch = self._buf[self._pos]
225+
if ch == 0x22:
226+
decoder.decode(b"", final=True)
227+
self._pos += 1
228+
raw = _append_raw(b'"')
229+
return "" if raw is None else str(json.loads(bytes(raw)))
230+
if ch == 0x5c and len(self._buf) - self._pos < 6 and self._cursor < self._stop:
231+
before = len(self._buf) - self._pos
232+
self._ensure(6)
233+
if len(self._buf) - self._pos > before:
234+
continue
235+
raise ValueError("invalid JSON string")
236+
237+
def read_primitive(self) -> Any:
238+
raw = bytearray()
239+
while True:
240+
if self._pos >= len(self._buf) and not self._ensure(1):
241+
break
242+
match = _JSON_TOKEN_STOP.search(self._buf, self._pos)
243+
end = len(self._buf) if match is None else match.start()
244+
seg = self._buf[self._pos:end]
245+
if len(raw) + len(seg) > _MAX_PRIMITIVE_BYTES:
246+
raise ValueError("oversized JSON primitive")
247+
raw.extend(seg)
248+
self._pos = end
249+
if match is not None:
250+
break
251+
if not raw:
252+
raise ValueError("expected JSON value")
253+
return json.loads(bytes(raw), parse_constant=_reject_json_constant)
254+
255+
def skip_value(self) -> None:
256+
stack: list[bool] = [] # True = object, False = array
257+
state = 0 # 0=val, 1=val|arr_end, 2=arr_sep, 3=key|obj_end, 4=key, 5=colon, 6=obj_sep
258+
while True:
259+
ch = self.skip_ws()
260+
if ch is None:
261+
raise ValueError("unexpected EOF in JSON value")
262+
if state in {3, 6}:
263+
if ch == 0x7d:
264+
self._pos += 1
265+
stack.pop()
266+
if not stack:
267+
return
268+
state = 6 if stack[-1] else 2
269+
continue
270+
if state == 6:
271+
if ch != 0x2c:
272+
raise ValueError("expected comma or end of JSON object")
273+
self._pos += 1
274+
state = 4
275+
continue
276+
state = 4
277+
if state == 4:
278+
self.scan_string()
279+
state = 5
280+
continue
281+
if state == 5:
282+
if ch != 0x3a:
283+
raise ValueError("expected colon in JSON object")
284+
self._pos += 1
285+
state = 0
286+
continue
287+
if state == 2:
288+
if ch == 0x5d:
289+
self._pos += 1
290+
stack.pop()
291+
if not stack:
292+
return
293+
state = 6 if stack[-1] else 2
294+
continue
295+
if ch != 0x2c:
296+
raise ValueError("expected comma or end of JSON array")
297+
self._pos += 1
298+
state = 0
299+
continue
300+
if state == 1 and ch == 0x5d:
301+
self._pos += 1
302+
stack.pop()
303+
if not stack:
304+
return
305+
state = 6 if stack[-1] else 2
306+
continue
307+
if ch == 0x7b:
308+
if len(stack) >= _MAX_SKIP_DEPTH:
309+
raise RecursionError("JSON nesting too deep")
310+
self._pos += 1
311+
stack.append(True)
312+
state = 3
313+
elif ch == 0x5b:
314+
if len(stack) >= _MAX_SKIP_DEPTH:
315+
raise RecursionError("JSON nesting too deep")
316+
self._pos += 1
317+
stack.append(False)
318+
state = 1
319+
elif ch == 0x22:
320+
self.scan_string()
321+
if not stack:
322+
return
323+
state = 6 if stack[-1] else 2
324+
else:
325+
self.read_primitive()
326+
if not stack:
327+
return
328+
state = 6 if stack[-1] else 2
329+
330+
def read_small_value(self) -> Any:
331+
ch = self.skip_ws()
332+
if ch is None:
333+
raise ValueError("unexpected EOF in JSON value")
334+
if ch == 0x22:
335+
return self.scan_string(capture_limit=_MAX_HEADER_FIELD_BYTES)
336+
if ch == 0x7b:
337+
self.skip_value()
338+
return {}
339+
if ch == 0x5b:
340+
self.skip_value()
341+
return []
342+
return self.read_primitive()
343+
344+
345+
def _scan_selected_object(cursor: _JsonSliceCursor, spec: Mapping[str, Any]) -> dict[str, Any]:
346+
cursor.consume_byte(0x7b)
347+
result: dict[str, Any] = {}
348+
ch = cursor.skip_ws()
349+
if ch == 0x7d:
350+
cursor._pos += 1
351+
return result
352+
while True:
353+
if ch != 0x22:
354+
raise ValueError("expected JSON object key")
355+
key = cursor.scan_string(capture_limit=128, allow_long_key=True)
356+
if cursor.skip_ws() != 0x3a:
357+
raise ValueError("expected colon in JSON object")
358+
cursor._pos += 1
359+
if key not in spec:
360+
cursor.skip_value()
361+
elif isinstance(spec[key], dict):
362+
if cursor.skip_ws() == 0x7b:
363+
result[key] = _scan_selected_object(cursor, spec[key])
364+
else:
365+
result[key] = cursor.read_small_value()
366+
else:
367+
result[key] = cursor.read_small_value()
368+
ch = cursor.skip_ws()
369+
if ch == 0x7d:
370+
cursor._pos += 1
371+
return result
372+
if ch != 0x2c:
373+
raise ValueError("expected comma or end of JSON object")
374+
cursor._pos += 1
375+
ch = cursor.skip_ws()
376+
377+
378+
def _scan_turn_prefix_record(stream: BinaryIO, start: int, stop: int) -> dict[str, Any]:
379+
"""Decode only Turn/parent metadata from a large earlier record in O(chunk) memory."""
380+
cursor = _JsonSliceCursor(stream, start, stop)
381+
if cursor.skip_ws() != 0x7b:
382+
raise ValueError("native replay record must be a JSON object")
383+
record = _scan_selected_object(cursor, _PREFIX_RECORD_SPEC)
384+
if cursor.skip_ws() is not None:
385+
raise ValueError("trailing data in native replay record")
386+
return record
128387

129388

130389
def _turn_boundary(record: dict[str, Any]) -> bool:
@@ -136,8 +395,19 @@ def _native_reader(stream: BinaryIO, end: int, event: dict[str, Any]) -> tuple[i
136395
reader = event["tool_use_id"]
137396
completed = False
138397
closed_parents: set[str] = set()
139-
parent = None
140-
for offset, record in _reader_tail(stream, end):
398+
parent: tuple[int, str] | None = None
399+
for offset, stop in _reader_spans(stream, end):
400+
raw_len = stop - offset - 1
401+
if parent is None:
402+
if raw_len > _MAX_RECORD_BYTES:
403+
raise ValueError("unsupported native reader record")
404+
stream.seek(offset)
405+
record = json.loads(stream.read(stop - offset))
406+
elif raw_len > _IO_CHUNK_BYTES:
407+
record = _scan_turn_prefix_record(stream, offset, stop - 1)
408+
else:
409+
stream.seek(offset)
410+
record = json.loads(stream.read(stop - offset))
141411
if _turn_boundary(record):
142412
break
143413
payload = record["payload"]
@@ -154,6 +424,11 @@ def _native_reader(stream: BinaryIO, end: int, event: dict[str, Any]) -> tuple[i
154424
if not isinstance(call, str) or not call:
155425
continue
156426
if call == reader and kind in {"function_call", "function_call_output"}:
427+
if raw_len > _MAX_RECORD_BYTES:
428+
return None
429+
if parent is not None and raw_len > _IO_CHUNK_BYTES:
430+
stream.seek(offset)
431+
record = json.loads(stream.read(stop - offset))
157432
return offset, _digest(record)
158433
if kind == "custom_tool_call_output":
159434
closed_parents.add(call)

0 commit comments

Comments
 (0)