|
| 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