Skip to content

Commit 2650f8e

Browse files
authored
Merge pull request #7757 from shangzh0/codex/trajectory-capture-streaming-20261101
2 parents 04c5799 + 99eb924 commit 2650f8e

2 files changed

Lines changed: 106 additions & 9 deletions

File tree

‎loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,20 @@ def _request_usage_record(value: object) -> object:
130130
)
131131
return result
132132

133+
134+
def _usage_rows(path: Path, digest):
135+
"""Hash the exact captured bytes while parsing one JSONL record at a time."""
136+
with path.open("rb") as stream:
137+
for line_number, line in enumerate(stream, 1):
138+
digest.update(line)
139+
yield line_number, json.loads(line.decode("utf-8"))
140+
141+
142+
def _source_digest(path: Path) -> str:
143+
with path.open("rb") as stream:
144+
return hashlib.file_digest(stream, "sha256").hexdigest()
145+
146+
133147
def _usage_capture(
134148
source_root: Path,
135149
artifact: str,
@@ -139,12 +153,12 @@ def _usage_capture(
139153
loopx_input_json: str | None = None,
140154
input_goal_id: str | None = None,
141155
) -> dict:
142-
data = _source_path(source_root, artifact).read_bytes()
156+
path = _source_path(source_root, artifact)
157+
digest = hashlib.sha256()
143158
events = []
144159
# Transport only the provider's counter/lifecycle fields, not model text,
145160
# account metadata or tool outputs. TS owns all accounting decisions.
146-
for line_number, line in enumerate(data.decode("utf-8").splitlines(), 1):
147-
event = json.loads(line)
161+
for line_number, event in _usage_rows(path, digest):
148162
if not isinstance(event, dict):
149163
raise ValueError("Usage capture contains a non-object event")
150164
payload = event.get("payload") or {}
@@ -236,7 +250,7 @@ def _usage_capture(
236250
)
237251
return {
238252
"artifact": artifact,
239-
"artifact_sha256": hashlib.sha256(data).hexdigest(),
253+
"artifact_sha256": digest.hexdigest(),
240254
"projection": projection,
241255
**({"input_artifacts": input_artifacts} if input_artifacts else {}),
242256
}
@@ -248,14 +262,14 @@ def _captured_view(record: dict, field: str) -> dict | None:
248262
return None
249263
reason = None
250264
try:
251-
data = _source_path(
265+
path = _source_path(
252266
Path(record["source_root"]), captured["artifact"]
253-
).read_bytes()
254-
if hashlib.sha256(data).hexdigest() != captured["artifact_sha256"]:
267+
)
268+
if _source_digest(path) != captured["artifact_sha256"]:
255269
reason = "source_changed"
256270
for artifact in captured.get("input_artifacts", []):
257-
data = _source_path(Path(record["source_root"]), artifact["artifact"]).read_bytes()
258-
if hashlib.sha256(data).hexdigest() != artifact["artifact_sha256"]:
271+
path = _source_path(Path(record["source_root"]), artifact["artifact"])
272+
if _source_digest(path) != artifact["artifact_sha256"]:
259273
reason = "source_changed"
260274
except (OSError, ValueError):
261275
reason = "source_unavailable"
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""Large private captures must not require a full text copy to observe costs."""
2+
import hashlib
3+
import json
4+
import os
5+
import tracemalloc
6+
7+
import pytest
8+
9+
from loopx.capabilities.benchmark_toolkit.trajectory_assessment_store import (
10+
_captured_view, _usage_rows, _usage_capture,
11+
)
12+
13+
14+
def test_hash_and_line_provenance_preserve_utf8_crlf_and_no_final_newline(tmp_path):
15+
path = tmp_path / 'capture.jsonl'
16+
raw = '{"text":"合成结果"}\r\n{"value":2}'.encode()
17+
path.write_bytes(raw)
18+
digest = hashlib.sha256()
19+
assert list(_usage_rows(path, digest)) == [(1, {'text': '合成结果'}), (2, {'value': 2})]
20+
assert digest.hexdigest() == hashlib.sha256(raw).hexdigest()
21+
path.write_bytes(b'{}\n{broken')
22+
with pytest.raises(ValueError):
23+
list(_usage_rows(path, hashlib.sha256()))
24+
25+
26+
def test_current_readback_rehashes_same_size_same_timestamp_mutations(tmp_path):
27+
path = tmp_path / 'capture.bin'
28+
path.write_bytes(b'original')
29+
stamp = path.stat().st_mtime_ns
30+
captured = {'artifact': path.name, 'artifact_sha256': hashlib.sha256(b'original').hexdigest(),
31+
'projection': {'input_tokens': 123}}
32+
record = {'source_root': str(tmp_path), 'solver_usage': captured}
33+
assert _captured_view(record, 'solver_usage')['applicability'] == 'current'
34+
path.write_bytes(b'changed!')
35+
os.utime(path, ns=(stamp, stamp))
36+
historical = _captured_view(record, 'solver_usage')
37+
assert historical['reason_code'] == 'source_changed'
38+
assert historical['projection'] == captured['projection']
39+
path.unlink()
40+
assert _captured_view(record, 'solver_usage')['reason_code'] == 'source_unavailable'
41+
42+
43+
def test_large_ignored_text_has_bounded_observation_and_verification_memory(tmp_path):
44+
path = tmp_path / 'large.jsonl'
45+
digest = hashlib.sha256()
46+
row = json.dumps({'type': 'response_item', 'payload': {
47+
'type': 'message', 'role': 'assistant', 'content': [{'text': 'x' * 65536}]}}).encode() + b'\n'
48+
with path.open('wb') as stream:
49+
for _ in range(512):
50+
stream.write(row)
51+
digest.update(row)
52+
# Start after fixture construction; measure the real parsing/hash path.
53+
tracemalloc.start()
54+
try:
55+
check = hashlib.sha256()
56+
assert sum(1 for _ in _usage_rows(path, check)) == 512
57+
captured = {'artifact': path.name, 'artifact_sha256': digest.hexdigest(), 'projection': {}}
58+
assert _captured_view({'source_root': str(tmp_path), 'solver_usage': captured}, 'solver_usage')['applicability'] == 'current'
59+
_, peak = tracemalloc.get_traced_memory()
60+
finally:
61+
tracemalloc.stop()
62+
assert check.hexdigest() == digest.hexdigest()
63+
assert peak < 4 * 1024 * 1024, f'32 MiB capture required {peak} bytes of Python allocation'
64+
65+
66+
def test_real_counter_projection_retains_capture_digest_and_source_lines(tmp_path):
67+
usage = {'input_tokens': 100, 'cached_input_tokens': 60, 'output_tokens': 5}
68+
rows = [
69+
{'type': 'session_meta', 'payload': {'id': 'session'}},
70+
{'type': 'event_msg', 'payload': {'type': 'task_started', 'turn_id': 'turn'}},
71+
{'type': 'response_item', 'payload': {'type': 'message', 'role': 'assistant', 'content': [{'text': '合成输出'}]}},
72+
{'type': 'event_msg', 'payload': {'type': 'token_count', 'info': {'total_token_usage': usage, 'last_token_usage': usage}}},
73+
{'type': 'event_msg', 'payload': {'type': 'task_complete', 'turn_id': 'turn'}},
74+
]
75+
for i, row in enumerate(rows):
76+
row['timestamp'] = f'2026-01-01T00:00:0{i}Z'
77+
raw = '\r\n'.join(json.dumps(r, ensure_ascii=False) for r in rows).encode()
78+
(tmp_path / 'usage.jsonl').write_bytes(raw)
79+
result = _usage_capture(tmp_path, 'usage.jsonl', 'session')
80+
assert result['artifact_sha256'] == hashlib.sha256(raw).hexdigest()
81+
assert result['projection']['input_tokens'] == 100
82+
assert result['projection']['turns'][0]['first_line'] == 2
83+
assert result['projection']['turns'][0]['last_line'] == 5

0 commit comments

Comments
 (0)