Skip to content

Commit 958753b

Browse files
committed
fix(turn-driver): preserve 16 MiB json.loads threshold and stream skip_primitive
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 53f9df1 commit 958753b

2 files changed

Lines changed: 216 additions & 9 deletions

File tree

‎loopx/control_plane/turn_driver/codex_context_history.py‎

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
r"Process exited with code 0\n(?:Original token count: [0-9]+\n)?Output:\n(.*)\Z", re.DOTALL)
4242
_JSON_WS_STOP = re.compile(rb"[^ \t\r\n]")
4343
_JSON_STR_SPAN = re.compile(rb'(?:[^"\\\x00-\x1f]+|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})){1,64}')
44+
_JSON_DIGITS = re.compile(rb"[0-9]+")
45+
_JSON_PRIMITIVE_STOP = frozenset(b" \t\r\n,}]")
4446
_JSON_TOKEN_STOP = re.compile(rb"[ \t\r\n,\}\]]")
4547
_PREFIX_PAYLOAD_SPEC: dict[str, Any] = {
4648
"type": None,
@@ -181,6 +183,22 @@ def _ensure(self, n: int = 1) -> bool:
181183
self._pos = 0
182184
return len(self._buf) - self._pos >= n
183185

186+
def _peek_byte(self) -> int | None:
187+
if self._pos >= len(self._buf) and not self._ensure(1):
188+
return None
189+
return self._buf[self._pos]
190+
191+
def _consume_digits(self) -> bool:
192+
matched = False
193+
while True:
194+
if self._pos >= len(self._buf) and not self._ensure(1):
195+
return matched
196+
match = _JSON_DIGITS.match(self._buf, self._pos)
197+
if match is None:
198+
return matched
199+
matched = True
200+
self._pos = match.end()
201+
184202
def skip_ws(self) -> int | None:
185203
while True:
186204
if self._pos >= len(self._buf) and not self._ensure(1):
@@ -252,6 +270,43 @@ def read_primitive(self) -> Any:
252270
raise ValueError("expected JSON value")
253271
return json.loads(bytes(raw), parse_constant=_reject_json_constant)
254272

273+
def skip_primitive(self) -> None:
274+
"""Validate and skip a JSON literal or number in O(1) memory."""
275+
ch = self._peek_byte()
276+
if ch is None:
277+
raise ValueError("expected JSON value")
278+
if ch in {0x74, 0x66, 0x6e}:
279+
literal = b"true" if ch == 0x74 else b"false" if ch == 0x66 else b"null"
280+
if not self._ensure(len(literal)) or self._buf[self._pos:self._pos + len(literal)] != literal:
281+
raise ValueError("invalid JSON literal")
282+
self._pos += len(literal)
283+
else:
284+
if ch == 0x2d:
285+
self._pos += 1
286+
ch = self._peek_byte()
287+
if ch is None:
288+
raise ValueError("invalid JSON number")
289+
if ch == 0x30:
290+
self._pos += 1
291+
elif 0x31 <= ch <= 0x39:
292+
self._pos += 1
293+
self._consume_digits()
294+
else:
295+
raise ValueError("invalid JSON number")
296+
if self._peek_byte() == 0x2e:
297+
self._pos += 1
298+
if not self._consume_digits():
299+
raise ValueError("invalid JSON number")
300+
if self._peek_byte() in {0x65, 0x45}:
301+
self._pos += 1
302+
if self._peek_byte() in {0x2b, 0x2d}:
303+
self._pos += 1
304+
if not self._consume_digits():
305+
raise ValueError("invalid JSON number")
306+
nxt = self._peek_byte()
307+
if nxt is not None and nxt not in _JSON_PRIMITIVE_STOP:
308+
raise ValueError("invalid JSON primitive")
309+
255310
def skip_value(self) -> None:
256311
stack: list[bool] = [] # True = object, False = array
257312
state = 0 # 0=val, 1=val|arr_end, 2=arr_sep, 3=key|obj_end, 4=key, 5=colon, 6=obj_sep
@@ -322,7 +377,7 @@ def skip_value(self) -> None:
322377
return
323378
state = 6 if stack[-1] else 2
324379
else:
325-
self.read_primitive()
380+
self.skip_primitive()
326381
if not stack:
327382
return
328383
state = 6 if stack[-1] else 2
@@ -398,12 +453,9 @@ def _native_reader(stream: BinaryIO, end: int, event: dict[str, Any]) -> tuple[i
398453
parent: tuple[int, str] | None = None
399454
for offset, stop in _reader_spans(stream, end):
400455
raw_len = stop - offset - 1
401-
if parent is None:
402-
if raw_len > _MAX_RECORD_BYTES:
456+
if raw_len > _MAX_RECORD_BYTES:
457+
if parent is None:
403458
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:
407459
record = _scan_turn_prefix_record(stream, offset, stop - 1)
408460
else:
409461
stream.seek(offset)
@@ -426,9 +478,6 @@ def _native_reader(stream: BinaryIO, end: int, event: dict[str, Any]) -> tuple[i
426478
if call == reader and kind in {"function_call", "function_call_output"}:
427479
if raw_len > _MAX_RECORD_BYTES:
428480
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))
432481
return offset, _digest(record)
433482
if kind == "custom_tool_call_output":
434483
closed_parents.add(call)

‎tests/control_plane/test_codex_context_resume.py‎

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -866,3 +866,161 @@ def test_same_turn_large_earlier_record_keeps_ambiguity_and_corruption_rejected(
866866
assert "native_resume" not in context._state(tmp_path)["candidate"]
867867
context.codex_context_hook(str(tmp_path), {**event, "source": "resume"})
868868
assert "candidate" not in context._state(tmp_path)
869+
870+
871+
def _write_large_decimal_rollout_record(history: Path, *, min_bytes: int, decimal_digits: int = 1100) -> int:
872+
prefix = b'{"type":"event_msg","payload":{"unused_decimal":0.' + (b"1" * decimal_digits)
873+
prefix += b',"nested":{"flag":true,"empty":null,"nums":[-0,123.45e+6,false]},"message":"'
874+
suffix = b'","type":"background_event"}}'
875+
pad_len = max(0, min_bytes - len(prefix) - len(suffix))
876+
record = prefix + (b"x" * pad_len) + suffix
877+
with history.open("ab") as stream:
878+
stream.write(record + b"\n")
879+
return len(record)
880+
881+
882+
@pytest.mark.parametrize("min_bytes", [71 * 1024, 17 * 1024 * 1024], ids=["71KiB", "17MiB"])
883+
@pytest.mark.parametrize("scope_mode", ["full", "selected"])
884+
def test_same_turn_earlier_record_with_long_decimal_preserves_native_resume(
885+
tmp_path, monkeypatch, min_bytes, scope_mode):
886+
from argparse import Namespace
887+
888+
from loopx.cli_commands.quota_capture import read_context_capture
889+
from loopx.control_plane.turn_driver import codex_context_history as history_io
890+
891+
event = setup(tmp_path, monkeypatch)
892+
history = tmp_path / "rollout.jsonl"
893+
append(history, "session_meta", {"id": "session", "cwd": str(tmp_path),
894+
"cli_version": "0.167.0-alpha.3.2", "history_mode": "paginated"})
895+
turn_id = "long-decimal-turn"
896+
append(history, "event_msg", {"type": "task_started", "turn_id": turn_id})
897+
append(history, "turn_context", {"cwd": str(tmp_path), "model": "fixture"})
898+
raw_len = _write_large_decimal_rollout_record(history, min_bytes=min_bytes)
899+
if min_bytes < history_io._MAX_RECORD_BYTES:
900+
assert history_io._IO_CHUNK_BYTES < raw_len <= history_io._MAX_RECORD_BYTES
901+
else:
902+
assert raw_len > history_io._MAX_RECORD_BYTES
903+
history.chmod(0o600)
904+
event.update(transcript_path=str(history), model="fixture", permission_mode="bypassPermissions", turn_id=turn_id)
905+
address = "/interaction_contract/agent_channel/work_context/sources/0/content/text"
906+
narrative = "Preserve replay across long decimals. " * 280
907+
payload = {"ok": True, "goal_id": "fixture", "selected_todo": {"todo_id": "todo_current"},
908+
"goal_boundary": {"stop_condition": "Current boundary."},
909+
"interaction_contract": {"schema_version": "loopx_interaction_contract_v0",
910+
"agent_channel": {"work_context": {"sources": [{"source": "goal_state", "content": {
911+
"state_file": "fixture-goal.md", "full_source": True, "text": narrative,
912+
"revision": "sha256:" + hashlib.sha256(narrative.encode()).hexdigest(),
913+
}}]}}, "user_channel": {}, "cli_channel": {}}}
914+
_, first = project(tmp_path, payload=payload)
915+
if scope_mode == "full":
916+
pages = read_pages(tmp_path, first, size=2048)
917+
for i, page in enumerate(pages):
918+
body = json.dumps(page)
919+
parent, call = f"parent-{i}", f"reader-{i}"
920+
append(history, "response_item", {"type": "custom_tool_call", "call_id": parent, "name": "exec",
921+
"internal_chat_message_metadata_passthrough": {"turn_id": turn_id}})
922+
append(history, "event_msg", {"type": "item_completed", "turn_id": turn_id,
923+
"item": {"type": "CommandExecution", "id": call, "exit_code": 0}})
924+
context.codex_context_hook(str(tmp_path), {**event, "hook_event_name": "PostToolUse",
925+
"tool_use_id": call, "tool_response": body})
926+
append(history, "response_item", {"type": "custom_tool_call_output", "call_id": parent,
927+
"output": [{"type": "input_text", "text": body}]})
928+
state = context._state(tmp_path)
929+
assert "native_resume" in state["candidate"]
930+
assert history_io.native_resume_verified(state, {**event, "source": "resume"})
931+
context.codex_context_hook(str(tmp_path), {**event, "source": "resume"})
932+
assert "candidate" in context._state(tmp_path)
933+
_, wire = project(tmp_path, "second", payload={**payload, "heartbeat_receipt": {"turn_instance_id": "second"}})
934+
assert wire["mode"] == "delta" and wire["continuity_basis"] == "captured_file"
935+
else:
936+
selected = read_context_capture(Namespace(capture_file=first["recovery"]["path"],
937+
capture_sha256=first["recovery"]["sha256"], select=[address], offset=0,
938+
page_bytes=64000, max_page_output_bytes=64000, format="json"))
939+
assert selected["ok"] and selected["eof"]
940+
body = json.dumps(selected)
941+
append(history, "response_item", {"type": "custom_tool_call", "call_id": "parent-sel", "name": "exec",
942+
"internal_chat_message_metadata_passthrough": {"turn_id": turn_id}})
943+
append(history, "event_msg", {"type": "item_completed", "turn_id": turn_id,
944+
"item": {"type": "CommandExecution", "id": "reader-sel", "exit_code": 0}})
945+
context.codex_context_hook(str(tmp_path), {**event, "hook_event_name": "PostToolUse",
946+
"tool_use_id": "reader-sel", "tool_response": body})
947+
append(history, "response_item", {"type": "custom_tool_call_output", "call_id": "parent-sel",
948+
"output": [{"type": "input_text", "text": body}]})
949+
state = context._state(tmp_path)
950+
assert "selected_resume" in state
951+
retained = history_io.native_resume_sections(state, {**event, "source": "resume"})
952+
assert address in retained
953+
context.codex_context_hook(str(tmp_path), {**event, "source": "resume"})
954+
assert address in context._state(tmp_path).get("consumed_pointers", {})
955+
956+
957+
@pytest.mark.parametrize("bad_primitive", [b"01", b"1.", b"1e+", b"tru"])
958+
def test_large_earlier_record_rejects_malformed_json_primitives(tmp_path, monkeypatch, bad_primitive):
959+
from loopx.control_plane.turn_driver import codex_context_history as history_io
960+
961+
event = setup(tmp_path, monkeypatch)
962+
history = tmp_path / "rollout.jsonl"
963+
append(history, "session_meta", {"id": "session", "cwd": str(tmp_path),
964+
"cli_version": "0.167.0-alpha.3.2", "history_mode": "paginated"})
965+
turn_id = "malformed-primitive-turn"
966+
append(history, "event_msg", {"type": "task_started", "turn_id": turn_id})
967+
append(history, "turn_context", {"cwd": str(tmp_path), "model": "fixture"})
968+
offset = history.stat().st_size
969+
with history.open("ab") as stream:
970+
stream.write(b'{"type":"event_msg","payload":{"message":"' + (b"x" * (17 * 1024 * 1024))
971+
+ b'","unused":' + bad_primitive + b',"type":"background_event"}}\n')
972+
stop = history.stat().st_size - 1
973+
with history.open("rb") as stream, pytest.raises(ValueError):
974+
history_io._scan_turn_prefix_record(stream, offset, stop)
975+
history.chmod(0o600)
976+
event.update(transcript_path=str(history), model="fixture", permission_mode="bypassPermissions", turn_id=turn_id)
977+
payload = {"ok": True, "plan_summary": {"requirements": "Keep original evidence. " * 1000}}
978+
_, first = project(tmp_path, payload=payload)
979+
pages = read_pages(tmp_path, first)
980+
for i, page in enumerate(pages):
981+
body = json.dumps(page)
982+
parent, call = f"parent-{i}", f"reader-{i}"
983+
append(history, "response_item", {"type": "custom_tool_call", "call_id": parent, "name": "exec",
984+
"internal_chat_message_metadata_passthrough": {"turn_id": turn_id}})
985+
append(history, "event_msg", {"type": "item_completed", "turn_id": turn_id,
986+
"item": {"type": "CommandExecution", "id": call, "exit_code": 0}})
987+
context.codex_context_hook(str(tmp_path), {**event, "hook_event_name": "PostToolUse",
988+
"tool_use_id": call, "tool_response": body})
989+
append(history, "response_item", {"type": "custom_tool_call_output", "call_id": parent,
990+
"output": [{"type": "input_text", "text": body}]})
991+
assert "native_resume" not in context._state(tmp_path)["candidate"]
992+
context.codex_context_hook(str(tmp_path), {**event, "source": "resume"})
993+
assert "candidate" not in context._state(tmp_path)
994+
995+
996+
def test_json_slice_cursor_skip_primitive_rfc8259_and_chunk_boundaries():
997+
import io
998+
999+
from loopx.control_plane.turn_driver import codex_context_history as history_io
1000+
1001+
chunk = history_io._IO_CHUNK_BYTES
1002+
long_dec = b"0." + (b"9" * (chunk + 200))
1003+
pad = b" " * (chunk - 2)
1004+
valid_records = [
1005+
b'{"type":"event_msg","payload":{"type":"background_event","n":0,"z":-0,"f":123.45e+6,"e":1E01}}',
1006+
b'{"type":"event_msg","payload":{"type":"background_event","d":' + long_dec + b"}}",
1007+
b'{"type":"event_msg","payload":{"type":"background_event","k":"' + (b"a" * (chunk - 56))
1008+
+ b'","t":true,"f":false,"n":null}}',
1009+
b'{"type":"event_msg","payload":{"type":"background_event","k":' + pad + b"true}}",
1010+
]
1011+
for raw in valid_records:
1012+
parsed = history_io._scan_turn_prefix_record(io.BytesIO(raw), 0, len(raw))
1013+
assert parsed["type"] == "event_msg"
1014+
assert parsed["payload"]["type"] == "background_event"
1015+
1016+
invalid_primitives = [
1017+
b"01", b"-01", b"00", b"1.", b"1.e2", b"1e", b"1e+", b"1E-",
1018+
b"tru", b"fals", b"nul", b"NaN", b"Infinity", b"-Infinity", b".5", b"+1", b"-", b"truefalse", b"1.2.3",
1019+
]
1020+
for bad in invalid_primitives:
1021+
raw = b'{"type":"event_msg","payload":{"type":"background_event","bad":' + bad + b"}}"
1022+
with pytest.raises(ValueError):
1023+
history_io._scan_turn_prefix_record(io.BytesIO(raw), 0, len(raw))
1024+
cursor = history_io._JsonSliceCursor(io.BytesIO(bad), 0, len(bad))
1025+
with pytest.raises(ValueError):
1026+
cursor.skip_primitive()

0 commit comments

Comments
 (0)