Repository navigation
Expand file tree
/
Copy pathtest_trajectory_assessment_store.py
More file actions
1555 lines (1455 loc) · 80.5 KB
/
Copy pathtest_trajectory_assessment_store.py
File metadata and controls
1555 lines (1455 loc) · 80.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Scoped pack-to-process journey with actual files and a disposable child."""
from __future__ import annotations
import hashlib
import json
import os
import subprocess
import sys
from datetime import datetime, timedelta, timezone
import pytest
from loopx.control_plane.effect_runtime import EffectRuntimeRejected
from loopx.capabilities.benchmark_toolkit.trajectory_assessment_store import (
PackUnavailable,
cancel_pack,
discover,
execute_pack,
inspect_pack,
read_citation,
register_pack,
)
@pytest.fixture
def pack(tmp_path):
sources = tmp_path / "sources"
sources.mkdir()
evidence = "Prior question\nThe native measurement did not improve utility · 原始测量。\n".encode(
"utf-8"
)
(sources / "result.txt").write_bytes(evidence)
data = {
"schema_version": "trajectory_assessment_input_v1",
"scope": dict(
goal_id="solver",
case_id="case",
run_id="run",
revision="fixed",
window="one episode · 观察窗口",
),
"objective": "Improve native utility · 原始目标",
"selection": dict(
rule="synthetic complete population", population_episodes=1, exhaustive=True
),
"sources": [
dict(
id="source",
artifact="result.txt",
artifact_sha256=hashlib.sha256(evidence).hexdigest(),
first_line=2,
text=evidence.decode().split("\n")[1],
)
],
"episodes": [
dict(
id="episode",
question="Does it help?",
source_ids=["source"],
eligible_metrics=["benefit_test"],
)
],
}
input_path = tmp_path / "input.json"
input_path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
scope = dict(runtime_root=tmp_path / "runtime", owner_goal_id="research-owner")
registered = register_pack(
**scope, input_path=input_path, source_root=sources, title="Case · 原始目标"
)
operation = {
**scope,
"pack_id": registered["pack_id"],
"analysis_key": registered["analysis_key"],
}
output = {
"assessments": [
dict(
episode_id="episode",
metric="benefit_test",
verdict="yes",
reason="A negative native test still tests benefit · 负向测量。",
citations=[dict(source_id="source", first_line=2, last_line=2)],
)
],
"limitations": ["Synthetic process; not model quality evidence"],
"synthesis": {
"summary": {"text": "A valid negative result narrows the next investigation.", "episode_ids": ["episode"],
"citations": [dict(source_id="source", first_line=2, last_line=2)]},
"findings": [], "next_experiments": [],
},
}
executable = tmp_path / "codex-fixture"
executable.write_text(
f"""#!{sys.executable}
import json,sys
from pathlib import Path
assert "\\u539f\\u59cb\\u76ee\\u6807" in sys.stdin.buffer.read().decode("utf-8")
Path(sys.argv[sys.argv.index('-o')+1]).write_bytes({json.dumps(output, ensure_ascii=False).encode("utf-8")!r})
sys.stderr.buffer.write("\\u5408\\u6210\\u8bca\\u65ad".encode("utf-8"))
sys.stdout.buffer.write((json.dumps({{'type':'turn.completed','message':'\\u5206\\u6790\\u5b8c\\u6210','usage':{{'input_tokens':10,'output_tokens':2}}}},ensure_ascii=False)+'\\n').encode("utf-8"))
""",
encoding="utf-8",
)
executable.chmod(0o700)
return scope, operation, registered, input_path, sources, str(executable)
def test_scope_discovery_execute_read_citation_and_changed_source_history(pack):
scope, operation, registered, _, sources, provider = pack
listing = discover(**scope)
assert listing["default_pack_id"] == registered["pack_id"]
assert (
listing["packs"][0]["scope"]["goal_id"] == "solver"
) # never relabel owner as analyzed solver
assert "sources" not in listing["packs"][0]
before = inspect_pack(**scope)
assert before["job"] is None and before["result"] is None
assert not list(
(scope["runtime_root"] / "benchmark" / "trajectory-assessments").glob(
"*/jobs/*"
)
)
assert execute_pack(**operation, codex=provider)["status"] == "succeeded"
view = inspect_pack(**scope)
assert view["result"]["metrics"][1]["yes"] == 1
assert "directory" not in view["job"] and "process_id" not in view["job"]
assert execute_pack(**operation, codex="must-not-run")["reused"] is True
citation = read_citation(**operation, source_id="source", first_line=2, last_line=2)
assert (
citation["text"]
== "The native measurement did not improve utility · 原始测量。"
)
with pytest.raises(PackUnavailable, match="citation_not_in_result"):
read_citation(**operation, source_id="source", first_line=1, last_line=2)
(sources / "result.txt").write_text("changed", encoding="utf-8")
assert discover(**scope)["packs"][0]["reason_code"] == "source_changed"
with pytest.raises(PackUnavailable, match="source_changed"):
execute_pack(**operation, codex="must-not-run")
historical = inspect_pack(**scope)
assert (
historical["applicability"] == "historical"
and historical["result"] == view["result"]
)
assert (
read_citation(**operation, source_id="source", first_line=2, last_line=2)[
"text"
]
== citation["text"]
)
def test_repeated_artifact_excerpts_share_one_fresh_read(pack, monkeypatch):
scope, _, _, input_path, sources, _ = pack
data = json.loads(input_path.read_text())
data["sources"].append({**data["sources"][0], "id": "prior", "first_line": 1, "text": "Prior question"})
data["episodes"][0]["source_ids"].append("prior")
input_path.write_text(json.dumps(data))
calls = []
original = type(input_path).read_bytes
def observed(path):
if path == sources / "result.txt":
calls.append(path)
return original(path)
monkeypatch.setattr(type(input_path), "read_bytes", observed)
registered = register_pack(**scope, input_path=input_path, source_root=sources, title="Multiple excerpts")
assert len(calls) == 1
calls.clear()
before = inspect_pack(**scope, pack_id=registered["pack_id"])
assert before["availability"] == "available" and len(calls) == 1
# No cross-request cache: same-length replacement with restored timestamps
# must still invalidate the pack, rather than trusting path/size/mtime.
path = sources / "result.txt"
stat = path.stat()
original_bytes = original(path)
path.write_bytes(original_bytes.replace(b"Prior", b"Other"))
os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns))
calls.clear()
after = inspect_pack(**scope, pack_id=registered["pack_id"])
assert after["reason_code"] == "source_changed" and len(calls) == 1
@pytest.mark.parametrize("correction,reason", [
({"artifact_sha256": "0" * 64}, "source_changed"),
({"text": "An unsupported second excerpt"}, "excerpt_mismatch"),
])
def test_shared_artifact_does_not_skip_later_digest_or_excerpt(pack, correction, reason):
scope, _, _, input_path, sources, _ = pack
data = json.loads(input_path.read_text())
data["sources"].append({**data["sources"][0], "id": "later", **correction})
data["episodes"][0]["source_ids"].append("later")
input_path.write_text(json.dumps(data))
with pytest.raises(PackUnavailable, match=reason):
register_pack(**scope, input_path=input_path, source_root=sources, title="Invalid later excerpt")
def test_continuation_reuses_identical_excerpts_despite_other_capture_bytes(pack):
scope, operation, registered, path, sources, provider = pack
assert execute_pack(**operation, codex=provider)["status"] == "succeeded"
original = inspect_pack(**scope, pack_id=registered["pack_id"])["result"]
old_directory = next((scope["runtime_root"] / "benchmark" / "trajectory-assessments").glob("*/jobs")) / operation["analysis_key"]
old_bytes = {p.name: p.read_bytes() for p in old_directory.iterdir() if p.is_file()}
evidence = (sources / "result.txt").read_bytes() + b"Unselected capture metadata changed\n"
(sources / "result.txt").write_bytes(evidence)
data = json.loads(path.read_text())
data["scope"]["revision"] = "capture-2"
data["sources"][0]["artifact_sha256"] = hashlib.sha256(evidence).hexdigest()
path.write_text(json.dumps(data))
successor = register_pack(**scope, input_path=path, source_root=sources, title="Updated capture", base_pack_id=registered["pack_id"])
assert register_pack(**scope, input_path=path, source_root=sources, title="Updated capture", base_pack_id=registered["pack_id"])["pack_id"] == successor["pack_id"]
before = inspect_pack(**scope)
assert before["job"] is None and before["result"] is None
assert before["continuation"]["can_reuse"] is True
assert before["continuation"]["sources"] == dict(added=[], revised=[], removed=[])
new_operation = {**scope, "pack_id": successor["pack_id"], "analysis_key": successor["analysis_key"]}
completed = execute_pack(**new_operation, codex="must-not-run")
assert completed["reused"] and completed["reused_from_analysis_key"] == operation["analysis_key"]
reused_output = json.loads((old_directory.parent / successor["analysis_key"] / "model-output.json").read_text())
assert set(reused_output) == {"assessments", "limitations", "synthesis"}
assert reused_output["synthesis"] == original["synthesis"]
view = inspect_pack(**scope)
assert view["result"]["scope"]["revision"] == "capture-2"
assert view["result"]["metrics"] == original["metrics"]
assert view["result"]["evidence_manifest"][0]["artifact_sha256"] == data["sources"][0]["artifact_sha256"]
assert read_citation(**new_operation, source_id="source", first_line=2, last_line=2)["applicability"] == "current"
assert all((old_directory / name).read_bytes() == contents for name, contents in old_bytes.items())
def test_new_evidence_reassesses_old_judgments_and_complete_denominator(pack, tmp_path):
scope, operation, registered, path, sources, provider = pack
execute_pack(**operation, codex=provider)
previous = inspect_pack(**scope)["result"]
data = json.loads(path.read_text())
later = b"The earlier proxy was not representative; no native test occurred.\n"
(sources / "later.txt").write_bytes(later)
data["sources"].append(dict(id="later", artifact="later.txt", artifact_sha256=hashlib.sha256(later).hexdigest(), first_line=1, text=later.decode().strip()))
data["episodes"][0]["source_ids"].append("later")
data["episodes"].append(dict(id="follow-up", question="Did follow-up test utility?", source_ids=["later"], eligible_metrics=["benefit_test"]))
data["selection"]["population_episodes"] = 2
data["scope"].update(revision="corrected", window="original and later evidence")
path.write_text(json.dumps(data))
successor = register_pack(**scope, input_path=path, source_root=sources, title="Later evidence", base_pack_id=registered["pack_id"])
before = inspect_pack(**scope)
assert before["continuation"]["can_reuse"] is False
assert before["continuation"]["reassessed_episode_ids"] == ["episode", "follow-up"]
assert before["continuation"]["new_pair_count"] == 1
assert before["continuation"]["compared_pair_count"] is None
revised = {"assessments": [dict(episode_id=e, metric="benefit_test", verdict=v, reason="Later evidence corrects the earlier interpretation", citations=[dict(source_id="later", first_line=1, last_line=1)] if v != "unknown" else []) for e, v in [("episode", "no"), ("follow-up", "unknown")]], "limitations": ["Synthetic counterevidence"]}
revised["synthesis"] = {"summary": {"text": "The earlier interpretation was refuted by later evidence.", "episode_ids": ["episode"],
"citations": [dict(source_id="later", first_line=1, last_line=1)]}, "findings": [], "next_experiments": []}
executable = tmp_path / "reassessment"
executable.write_text(f"#!{sys.executable}\nimport sys\nfrom pathlib import Path\nprompt=sys.stdin.read()\nassert 'The earlier proxy' in prompt and '原始测量' in prompt\nPath(sys.argv[sys.argv.index('-o')+1]).write_text({json.dumps(revised)!r})\n")
executable.chmod(0o700)
new_operation = {**scope, "pack_id": successor["pack_id"], "analysis_key": successor["analysis_key"]}
execute_pack(**new_operation, codex=str(executable))
view = inspect_pack(**scope)
benefit = next(row for row in view["result"]["metrics"] if row["metric"] == "benefit_test")
assert (benefit["yes"], benefit["no"], benefit["unknown"], benefit["eligible"]) == (0, 1, 1, 2)
assert view["continuation"]["verdict_changes"] == [dict(episode_id="episode", metric="benefit_test", before="yes", after="no")]
assert view["continuation"]["compared_pair_count"] == 1
assert inspect_pack(**scope, pack_id=registered["pack_id"])["result"] == previous
def test_disjoint_research_units_have_zero_comparisons_without_overwriting_prior_result(pack, tmp_path):
scope, operation, registered, path, sources, provider = pack
execute_pack(**operation, codex=provider)
previous = inspect_pack(**scope)["result"]
old_files = {p: p.read_bytes() for p in scope["runtime_root"].glob("benchmark/trajectory-assessments/*/jobs/*/*") if p.is_file()}
raw = json.loads(next(p for p in old_files if p.name == "model-output.json").read_text())
data = json.loads(path.read_text())
data["scope"]["revision"] = "different-research-unit"
data["episodes"][0]["id"] = "new-question"
raw["assessments"][0]["episode_id"] = "new-question"
raw["synthesis"]["summary"]["episode_ids"] = ["new-question"]
path.write_text(json.dumps(data))
successor = register_pack(**scope, input_path=path, source_root=sources, title="Different research unit", base_pack_id=registered["pack_id"])
assert inspect_pack(**scope)["continuation"]["compared_pair_count"] is None
executable = tmp_path / "disjoint-output-fixture"
executable.write_text(f"#!{sys.executable}\nimport sys\nfrom pathlib import Path\nsys.stdin.read()\nPath(sys.argv[sys.argv.index('-o')+1]).write_text({json.dumps(raw)!r})\n")
executable.chmod(0o700)
execute_pack(**scope, pack_id=successor["pack_id"], analysis_key=successor["analysis_key"], codex=str(executable))
delta = inspect_pack(**scope)["continuation"]
assert (delta["compared_pair_count"], delta["new_pair_count"], delta["removed_pair_count"]) == (0, 1, 1)
assert delta["verdict_changes"] == []
assert inspect_pack(**scope, pack_id=registered["pack_id"])["result"] == previous
assert all(p.read_bytes() == content for p, content in old_files.items())
def test_continuation_does_not_cross_owner_run_or_revoked_source(pack, tmp_path):
scope, operation, registered, path, sources, provider = pack
execute_pack(**operation, codex=provider)
data = json.loads(path.read_text())
data["scope"]["run_id"] = "unrelated"
path.write_text(json.dumps(data))
with pytest.raises(EffectRuntimeRejected, match="different Goal/case/run"):
register_pack(**scope, input_path=path, source_root=sources, title="Wrong run", base_pack_id=registered["pack_id"])
with pytest.raises(PackUnavailable, match="pack_not_registered"):
register_pack(**{**scope, "owner_goal_id": "other-owner"}, input_path=path, source_root=sources, title="Wrong owner", base_pack_id=registered["pack_id"])
data["scope"].update(run_id="run", revision="current")
path.write_text(json.dumps(data))
copied = tmp_path / "current-sources"
copied.mkdir()
(copied / "result.txt").write_bytes((sources / "result.txt").read_bytes())
successor = register_pack(**scope, input_path=path, source_root=copied, title="Current snapshot", base_pack_id=registered["pack_id"])
(sources / "result.txt").unlink()
view = inspect_pack(**scope)
assert view["availability"] == "available"
assert not view["continuation"]["base_available"] and not view["continuation"]["can_reuse"]
assert view["continuation"]["compared_pair_count"] is None
assert view["continuation"]["reassessed_episode_ids"] == ["episode"]
result = execute_pack(**scope, pack_id=successor["pack_id"], analysis_key=successor["analysis_key"], codex=provider)
assert result["status"] == "succeeded" and not result["reused"]
def test_display_usage_captures_bind_registered_successor_versions():
from pathlib import Path
from loopx.capabilities.benchmark_toolkit.trajectory_assessment_store import _pack_id
fixture = Path(__file__).resolve().parents[2] / "apps/presentation/dashboard/src/data/fixtures/research-usage-real-captures.json"
data = json.loads(fixture.read_text())
lineage = {row["registered_pack_id"]: row for row in data["lineage"]}
for captured in data["packs"]:
source = lineage[captured["pack_id"]]
assert captured["continuation"]["base_pack_id"] == source["original_pack_id"]
usage = {key: value for key, value in captured["solver_usage"].items()
if key not in {"applicability", "reason_code"}}
assert usage["artifact_sha256"] == source["source_sha256"]
record = {"owner_goal_id": data["owner_goal_id"], "title": captured["title"],
"analysis_key": captured["analysis_key"], "solver_usage": usage,
"base_pack_id": source["original_pack_id"]}
assert _pack_id(data["owner_goal_id"], record) == captured["pack_id"]
def test_registration_can_preserve_the_current_selection(pack):
scope, _, original, input_path, sources, _ = pack
args = dict(**scope, input_path=input_path, source_root=sources,
title="Another captured version", base_pack_id=original["pack_id"])
alternate = register_pack(**args, select_default=False)
catalog = discover(**scope)
assert catalog["default_pack_id"] == original["pack_id"]
assert {p["pack_id"] for p in catalog["packs"]} == {original["pack_id"], alternate["pack_id"]}
assert inspect_pack(**scope, pack_id=alternate["pack_id"])["job"] is None
# Selection is not part of frozen evidence identity; legacy callers still
# select their registration without mutating either captured version.
assert register_pack(**args)["pack_id"] == alternate["pack_id"]
assert discover(**scope)["default_pack_id"] == alternate["pack_id"]
empty = {**scope, "runtime_root": scope["runtime_root"] / "empty"}
first = register_pack(**{**args, **empty, "base_pack_id": None}, select_default=False)
assert discover(**empty)["default_pack_id"] == first["pack_id"]
def test_native_results_register_through_real_cli_and_read_without_analysis(pack, tmp_path):
scope, _, original, input_path, sources, _ = pack
native = {
"schema_version": "trajectory_native_outcomes_v1",
"scope": json.loads(input_path.read_text())["scope"],
"start": "2026-01-01T00:00:00Z", "end": "2026-01-01T00:10:00Z",
"complete": True, "metric": {"name": "error", "unit": "points", "higher_is_better": False},
"retained_result_id": "native-1",
"samples": [{"submission_index": 1, "result_id": "native-1", "candidate_ref": "candidate-a",
"submitted_at": "2026-01-01T00:01:00Z", "observed_at": "2026-01-01T00:02:00Z",
"valid": True, "value": 2, "citation": {"source_id": "source", "first_line": 2, "last_line": 2}}],
}
native_path = sources / "native-outcomes.json"
native_path.write_text(json.dumps(native))
registry = tmp_path / "native-registry.json"
registry.write_text(json.dumps({"goals": []}))
result = subprocess.run([sys.executable, "-m", "loopx.cli", "--registry", str(registry),
"--runtime-root", str(scope["runtime_root"]), "--format", "json", "benchmark", "trajectory-pack-register",
"--goal-id", scope["owner_goal_id"], "--input-json", str(input_path), "--source-root", str(sources),
"--title", "Native outcome window", "--native-outcomes-json", native_path.name,
"--base-pack-id", original["pack_id"], "--preserve-default"],
capture_output=True, text=True, check=True)
registered = json.loads(result.stdout)
assert discover(**scope)["default_pack_id"] == original["pack_id"]
assert registered["analysis_key"] == original["analysis_key"]
assert "native_outcomes" not in original
assert registered["native_outcomes"]["projection"]["initial"]["value"] == 2
view = inspect_pack(**scope, pack_id=registered["pack_id"])
assert view["job"] is None and view["result"] is None
assert view["continuation"]["base_pack_id"] == original["pack_id"]
assert not view["continuation"]["base_available"]
assert view["native_outcomes"]["projection"]["retained"]["candidate_ref"] == "candidate-a"
citation = read_citation(**scope, pack_id=registered["pack_id"], analysis_key=registered["analysis_key"],
source_id="source", first_line=2, last_line=2)
assert citation["text"] == "The native measurement did not improve utility · 原始测量。"
with pytest.raises(PackUnavailable, match="citation_not_in_result"):
read_citation(**scope, pack_id=registered["pack_id"], analysis_key=registered["analysis_key"],
source_id="source", first_line=1, last_line=2)
native["samples"][0]["value"] = 3
native_path.write_text(json.dumps(native))
old = inspect_pack(**scope, pack_id=registered["pack_id"])
assert old["native_outcomes"]["applicability"] == "historical"
assert old["native_outcomes"]["projection"]["initial"]["value"] == 2
assert read_citation(**scope, pack_id=registered["pack_id"], analysis_key=registered["analysis_key"],
source_id="source", first_line=2, last_line=2)["applicability"] == "historical"
assert not list((scope["runtime_root"] / "benchmark" / "trajectory-assessments").glob("*/jobs/*"))
def test_native_improvement_citations_are_readable_without_model_execution(pack):
scope, _, _, input_path, sources, _ = pack
evidence = "Native results\nolder best: 100\nbaseline: 12\nretained: 15\nApplied retained source; verified hash\n"
(sources / "result.txt").write_text(evidence)
data = json.loads(input_path.read_text())
data["sources"][0].update(first_line=1, text=evidence,
artifact_sha256=hashlib.sha256(evidence.encode()).hexdigest())
input_path.write_text(json.dumps(data))
native = {
"schema_version": "trajectory_native_outcomes_v1", "scope": data["scope"],
"start": "2026-01-01T00:00:00Z", "end": "2026-01-01T00:10:00Z", "complete": False,
"metric": {"name": "utility", "unit": "points", "higher_is_better": True},
"retained_result_id": "result-9",
"comparison": {"baseline_result_id": "result-7",
"retention_citation": {"source_id": "source", "first_line": 5, "last_line": 5}},
"samples": [{"submission_index": index, "result_id": f"result-{index}", "candidate_ref": f"candidate-{index}",
"submitted_at": "2026-01-01T00:01:00Z", "observed_at": "2026-01-01T00:02:00Z",
"valid": True, "value": value, "citation": {"source_id": "source", "first_line": line, "last_line": line}}
for index, value, line in [(2, 100, 2), (7, 12, 3), (9, 15, 4)]],
}
path = sources / "comparison.json"
path.write_text(json.dumps(native))
registered = register_pack(**scope, input_path=input_path, source_root=sources,
title="Source-bound retained improvement", native_outcomes_json=path.name)
operation = {**scope, "pack_id": registered["pack_id"], "analysis_key": registered["analysis_key"]}
view = inspect_pack(**scope, pack_id=registered["pack_id"])
assert view["native_outcomes"]["projection"]["retained_improvement"]["value"] == 3
assert view["native_outcomes"]["projection"]["initial"] is None
assert view["result"] is None and view["job"] is None
assert read_citation(**operation, source_id="source", first_line=3, last_line=3)["text"] == "baseline: 12"
assert read_citation(**operation, source_id="source", first_line=5, last_line=5)["text"] == "Applied retained source; verified hash"
with pytest.raises(PackUnavailable, match="citation_not_in_result"):
read_citation(**operation, source_id="source", first_line=1, last_line=1)
path.write_text("{}")
old = inspect_pack(**scope, pack_id=registered["pack_id"])
assert old["native_outcomes"]["applicability"] == "historical"
assert old["native_outcomes"]["projection"]["retained_improvement"]["value"] == 3
assert read_citation(**operation, source_id="source", first_line=5, last_line=5)["applicability"] == "historical"
def test_native_capture_cannot_borrow_another_run_or_escape_source_root(pack):
scope, _, _, input_path, sources, _ = pack
path = sources / "wrong-native.json"
raw = {"schema_version": "trajectory_native_outcomes_v1", "scope": {
**json.loads(input_path.read_text())["scope"], "run_id": "foreign"}}
path.write_text(json.dumps(raw))
with pytest.raises(EffectRuntimeRejected, match="scope differs"):
register_pack(**scope, input_path=input_path, source_root=sources, title="wrong", native_outcomes_json=path.name)
with pytest.raises(PackUnavailable, match="invalid_source_path"):
register_pack(**scope, input_path=input_path, source_root=sources, title="wrong", native_outcomes_json="../input.json")
@pytest.mark.skipif(
os.name != "posix", reason="C locale coercion is a POSIX regression"
)
def test_utf8_pack_and_child_roundtrip_with_ascii_default_locale(pack):
scope, _, registered, input_path, sources, executable = pack
script = r"""
import codecs, locale, sys
from pathlib import Path
from loopx.capabilities.benchmark_toolkit.trajectory_assessment import prepare, read_job
from loopx.capabilities.benchmark_toolkit.trajectory_assessment_store import (
PackUnavailable, discover, execute_pack, inspect_pack, read_citation, register_pack,
)
assert sys.flags.utf8_mode == 0
assert codecs.lookup(locale.getencoding()).name == "ascii"
input_path, sources, runtime = map(Path, sys.argv[1:4])
scope = dict(runtime_root=runtime, owner_goal_id="research-owner")
prepared = prepare(input_path, model="gpt-6.1-sol", effort="max", service_tier="fast")
assert prepared["input"]["objective"] == "Improve native utility · 原始目标"
registered = register_pack(**scope, input_path=input_path, source_root=sources, title="Case · 原始目标")
assert registered["pack_id"] == sys.argv[4]
assert registered["analysis_key"] == prepared["analysis_key"]
assert discover(**scope)["packs"][0]["title"] == "Case · 原始目标"
assert inspect_pack(**scope)["job"] is None
operation = dict(**scope, pack_id=registered["pack_id"], analysis_key=registered["analysis_key"])
first = execute_pack(**operation, codex=sys.argv[5])
assert first["status"] == "succeeded" and first["usage"] == dict(input_tokens=10, output_tokens=2)
view = inspect_pack(**scope)
assert view["result"]["assessments"][0]["reason"] == "A negative native test still tests benefit · 负向测量。"
assert view["result"]["metrics"][1]["yes"] == 1
assert "directory" not in view["job"] and "process_id" not in view["job"]
assert execute_pack(**operation, codex="must-not-run")["reused"] is True
directory = next(runtime.glob("benchmark/trajectory-assessments/*/jobs/*"))
assert read_job(directory)["scope"]["window"] == "one episode · 观察窗口"
assert "原始目标" in (directory / "prompt.txt").read_text(encoding="utf-8")
assert "分析完成" in (directory / "events.jsonl").read_text(encoding="utf-8")
assert (directory / "stderr.txt").read_text(encoding="utf-8") == "合成诊断"
citation = dict(source_id="source", first_line=2, last_line=2)
assert read_citation(**operation, **citation)["text"] == "The native measurement did not improve utility · 原始测量。"
(sources / "result.txt").write_bytes(b"changed")
assert discover(**scope)["packs"][0]["reason_code"] == "source_changed"
try:
execute_pack(**operation, codex="must-not-run")
except PackUnavailable as error:
assert str(error) == "source_changed"
else:
raise AssertionError("Changed sources must not run a new analysis")
assert inspect_pack(**scope)["result"] == view["result"]
assert read_citation(**operation, **citation)["applicability"] == "historical"
"""
result = subprocess.run(
[
sys.executable,
"-X",
"utf8=0",
"-c",
script.encode("ascii", "backslashreplace").decode("ascii"),
str(input_path),
str(sources),
str(scope["runtime_root"]),
registered["pack_id"],
executable,
],
env={
**os.environ,
"LC_ALL": "C",
"LANG": "C",
"PYTHONUTF8": "0",
"PYTHONCOERCECLOCALE": "0",
"PYTHONIOENCODING": "ascii",
},
capture_output=True,
text=True,
encoding="utf-8",
timeout=60,
)
assert result.returncode == 0, result.stdout + result.stderr
def test_owner_isolation_unknown_ids_and_keys_are_rejected(pack):
scope, operation, _, _, _, _ = pack
other = {**scope, "owner_goal_id": "other-owner"}
assert discover(**other)["packs"] == []
with pytest.raises(PackUnavailable, match="pack_not_registered"):
inspect_pack(**other, pack_id=operation["pack_id"])
for value in ("../escape", "/tmp/arbitrary", "a" * 64):
with pytest.raises(PackUnavailable):
inspect_pack(**scope, pack_id=value)
with pytest.raises(PackUnavailable, match="analysis_key_mismatch"):
execute_pack(**{**operation, "analysis_key": "a" * 64}, codex="must-not-run")
with pytest.raises(PackUnavailable, match="analysis_key_mismatch"):
cancel_pack(**{**operation, "analysis_key": "a" * 64})
def test_digest_rejections_preserve_registration_and_create_no_job(pack):
scope, operation, _, _, _, _ = pack
root = scope["runtime_root"]
before = {
p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()
}
malformed = (
"a" * 63,
"a" * 65,
"A" * 64,
"g" * 64,
"sha256:" + "a" * 64,
" " + "a" * 64,
"a" * 64 + " ",
"\n" + "a" * 64,
"a" * 64 + "\n",
"a" * 64 + "\r\n",
"a" * 64 + "\0",
True,
64,
{"id": "a" * 64},
["a" * 64],
)
for value in malformed:
with pytest.raises(PackUnavailable, match="^invalid_identifier$"):
inspect_pack(**scope, pack_id=value)
for value in (*malformed, "", None, False, 0, {}, []):
with pytest.raises(PackUnavailable, match="^invalid_identifier$"):
execute_pack(**{**operation, "analysis_key": value}, codex="must-not-run")
for value in ("0" * 64, "0123456789abcdef" * 4, "f" * 64):
with pytest.raises(PackUnavailable, match="^pack_not_registered$"):
inspect_pack(**scope, pack_id=value)
assert {
p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()
} == before
def test_registration_requires_real_hash_literal_excerpt_and_contained_path(
pack, tmp_path
):
scope, _, _, input_path, sources, _ = pack
original = json.loads(input_path.read_text(encoding="utf-8"))
for change, message in (
({"text": "invented"}, "excerpt_mismatch"),
({"artifact_sha256": "a" * 64}, "source_changed"),
({"artifact": "../outside.txt"}, "invalid_source_path"),
):
data = json.loads(json.dumps(original))
data["sources"][0].update(change)
input_path.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(PackUnavailable, match=message):
register_pack(
**scope, input_path=input_path, source_root=sources, title="bad"
)
outside = tmp_path / "outside.txt"
outside.write_text("outside", encoding="utf-8")
(sources / "link.txt").symlink_to(outside)
original["sources"][0]["artifact"] = "link.txt"
input_path.write_text(json.dumps(original), encoding="utf-8")
with pytest.raises(PackUnavailable, match="invalid_source_path"):
register_pack(**scope, input_path=input_path, source_root=sources, title="bad")
assert len(discover(**scope)["packs"]) == 1
def test_missing_source_blocks_new_execution_and_leaves_registration_visible(pack):
scope, operation, _, _, sources, _ = pack
(sources / "result.txt").unlink()
view = inspect_pack(**scope)
assert (
view["reason_code"] == "source_unavailable"
and view["availability"] == "unavailable"
)
with pytest.raises(PackUnavailable, match="source_unavailable"):
execute_pack(**operation, codex="must-not-run")
@pytest.mark.parametrize("encoding", ["default", None, "source_text_aliases_v1", "source_text_aliases_with_literals_v1", "source_text_aliases_with_literal_values_v1", "source_text_aliases_with_literal_values_v2", "source_text_aliases_with_literal_values_v3", "source_text_aliases_with_literal_values_v4"])
@pytest.mark.parametrize("context", [False, True])
def test_full_history_display_uses_the_same_job_and_preserves_original_versions(pack, tmp_path, encoding, context):
from loopx.capabilities.benchmark_toolkit.trajectory_assessment import prepare
scope, _, initial, input_path, sources, _ = pack
data = json.loads(input_path.read_text())
history = {"ok": True, "goal_id": "solver", "total": 2, "next_cursor": None, "items": [
dict(schema_version="loopx_explore_result_event_v0", event_id="question-old", result_id="question", goal_id="solver", event_kind="node",
node_kind="question", recorded_at="2026-01-01T00:00:00Z", title="Does V18 help?", summary="Not established.", status="open"),
dict(schema_version="loopx_explore_result_event_v0", event_id="question-new", result_id="question", goal_id="solver", event_kind="node",
node_kind="question", recorded_at="2026-01-02T00:00:00Z", title="Does V19 help?", summary="Still unknown.", status="blocked"),
]}
if encoding in {"default", "source_text_aliases_with_literal_values_v1", "source_text_aliases_with_literal_values_v2", "source_text_aliases_with_literal_values_v3", "source_text_aliases_with_literal_values_v4"}:
history["items"][0]["summary"] = "Trial4failed2checks"
text = json.dumps(history, ensure_ascii=False)
(sources / "history.json").write_text(text)
data["sources"].append(dict(id="history", artifact="history.json", artifact_sha256=hashlib.sha256(text.encode()).hexdigest(), first_line=1, text=text))
data["display_snapshot"] = dict(schema_version="research_display_snapshot_v1", source_id="history", source_namespace="source-a")
if encoding is not None and encoding != "default":
data["display_snapshot"]["translation_encoding"] = encoding
context_citation = dict(source_id="source", first_line=2, last_line=2)
if context:
data["display_snapshot"]["contexts"] = [dict(event_id="question-old", field="summary", citations=[context_citation])]
input_path.write_text(json.dumps(data))
registered = register_pack(**scope, input_path=input_path, source_root=sources, title="Whole history · synthetic",
config=None if encoding == "default" else initial["config"])
if encoding == "default":
prepared = prepare(input_path, model="gpt-6.1-sol", effort="max", service_tier="fast")
assert prepared["input"]["display_snapshot"]["translation_encoding"] == "source_text_aliases_with_literal_values_v4"
assert prepared["analysis_key"] == registered["analysis_key"]
assert json.loads(input_path.read_text()) == data
current = inspect_pack(**scope, pack_id=registered["pack_id"], output_language="zh")
assert current["display_request"]["eligible"] == 4 and current["job"] is None
provider = tmp_path / "display-provider"
provider.write_text(f"#!{sys.executable}\n" + '''
import json,sys
from pathlib import Path
prompt = sys.stdin.read()
fields = json.loads(prompt.split("\\n\\ndisplay_fields:\\n")[1])
def translation(field):
if field.get("literals") == ["Trial4failed2checks"]:
assert field["explanation_numbers"] == ["4", "2"]
return "第4次尝试有2项检查未通过(" + field["text"] + ")。"
return "译文:" + field["text"]
output = {"assessments":[{"episode_id":"episode","metric":"benefit_test","verdict":"unknown","reason":"合成过程测试,未验证实际收益。","citations":[]}],
"limitations":["合成译文,非模型质量验收。"], "episode_questions":[{"episode_id":"episode","question":"是否有帮助?"}],
"synthesis":{"summary":{"text":"原生测量为负,不能推断更广泛的收益。","episode_ids":["episode"],"citations":[{"source_id":"source","first_line":2,"last_line":2}]},"findings":[],"next_experiments":[]},
"display_translations":[{"field_id":f["field_id"], "text":translation(f)} for f in fields[:-1]]}
Path(sys.argv[sys.argv.index('-o')+1]).write_text(json.dumps(output))
print(json.dumps({"type":"turn.completed", "usage":{"input_tokens":19,"output_tokens":7}}))
''')
provider.chmod(0o700)
operation = dict(**scope, pack_id=registered["pack_id"], analysis_key=current["analysis_key"], output_language="zh")
assert execute_pack(**operation, codex=str(provider))["status"] == "succeeded"
result = inspect_pack(**scope, pack_id=registered["pack_id"], output_language="zh")
assert result["result"]["display"]["coverage"] == dict(eligible=4, translated=3, missing=1, invalid=0)
if context:
field = next(field for field in result["result"]["display"]["fields"] if field["field"] == "summary")
assert field["context_citations"] == [context_citation]
assert read_citation(**operation, **context_citation)["text"] == data["sources"][0]["text"]
with pytest.raises(PackUnavailable, match="citation_not_in_result"):
read_citation(**operation, source_id="history", first_line=1, last_line=1)
else:
assert not any("context_citations" in field for field in result["result"]["display"]["fields"])
if encoding in {"default", "source_text_aliases_with_literal_values_v1", "source_text_aliases_with_literal_values_v2", "source_text_aliases_with_literal_values_v3", "source_text_aliases_with_literal_values_v4"}:
assert any(field["text"] == "第4次尝试有2项检查未通过(Trial4failed2checks)。"
for field in result["result"]["display"]["fields"])
assert result["job"]["usage"]["input_tokens"] == 19 # one shared attempt, not four new jobs
assert len(result["result"]["metrics"]) == 6 and result["result"]["metrics"][1]["unknown"] == 1
assert execute_pack(**operation, codex="must-not-run")["reused"] is True
assert inspect_pack(**scope, pack_id=registered["pack_id"], output_language="en")["result"] is None
with pytest.raises(PackUnavailable, match="analysis_key"):
execute_pack(**{**operation, "output_language": "en"}, codex="must-not-run")
successful_provider = provider.read_text().replace("for f in fields[:-1]", "for f in fields")
provider.write_text(f"#!{sys.executable}\nimport sys\nsys.exit(9)\n")
with pytest.raises(ValueError, match="Codex exited 9"):
execute_pack(**operation, codex=str(provider), retry=True)
prior = inspect_pack(**scope, pack_id=registered["pack_id"], output_language="zh")
assert prior["job"]["status"] == "failed" and prior["job"]["attempt"] == 2
assert prior["result_attempt"] == 1 and prior["result_job"]["usage"]["input_tokens"] == 19
assert prior["result"] == result["result"]
if encoding == "default":
# A failed retry keeps the prior successful response reusable. Readback
# contains restored literals, so it cannot substitute for raw output.
successor_input = json.loads(input_path.read_text())
successor_input["scope"]["revision"] = "successor-capture"
successor_path = tmp_path / "successor.json"
successor_path.write_text(json.dumps(successor_input))
successor = register_pack(**scope, input_path=successor_path, source_root=sources,
title="Same evidence, new capture", base_pack_id=registered["pack_id"])
successor_view = inspect_pack(**scope, pack_id=successor["pack_id"], output_language="zh")
assert successor_view["continuation"]["base_available"] and successor_view["continuation"]["can_reuse"]
assert successor_view["job"] is None
reuse = execute_pack(**scope, pack_id=successor["pack_id"], analysis_key=successor_view["analysis_key"],
output_language="zh", codex="must-not-run")
assert reuse["status"] == "succeeded" and reuse["reused"]
reused = inspect_pack(**scope, pack_id=successor["pack_id"], output_language="zh")
assert reused["result"]["display"] == prior["result"]["display"]
assert reused["result"]["metrics"] == prior["result"]["metrics"]
assert reused["continuation"]["verdict_changes"] == []
provider.write_text(successful_provider)
assert execute_pack(**operation, codex=str(provider), retry=True)["status"] == "succeeded"
result = inspect_pack(**scope, pack_id=registered["pack_id"], output_language="zh")
assert result["result"]["display"]["coverage"]["missing"] == 0 and result["result_attempt"] == 3
assert execute_pack(**operation, codex="must-not-run", retry=True)["reused"] is True
old = result["result"]["display"]
(sources / "history.json").write_text(text + " ")
changed = inspect_pack(**scope, pack_id=registered["pack_id"], output_language="zh")
assert changed["applicability"] == "historical" and changed["result"]["display"] == old
with pytest.raises(PackUnavailable, match="source_changed"):
execute_pack(**operation, codex="must-not-run")
assert json.loads(input_path.read_text()) == data
def test_method_upgrade_reads_verified_old_result_without_rejudging(pack, monkeypatch):
from loopx.capabilities.benchmark_toolkit import (
trajectory_assessment_store as store,
)
scope, operation, _, _, _, provider = pack
execute_pack(**operation, codex=provider)
current = inspect_pack(**scope)
original_prepare = store._prepared
def upgraded_method(record, output_language=None):
# Simulate a new method identity at the typed-owner boundary. The real
# old method, child process and stored receipt were exercised above.
return {
**original_prepare(record, output_language),
"analysis_key": "b" * 64,
"method_version": "future-method",
}
monkeypatch.setattr(store, "_prepared", upgraded_method)
historical = inspect_pack(**scope)
assert historical["reason_code"] == "method_changed"
assert historical["applicability"] == "historical"
assert historical["result"] == current["result"]
assert historical["result"]["method_version"] != "future-method"
assert (
read_citation(**operation, source_id="source", first_line=2, last_line=2)[
"applicability"
]
== "historical"
)
with pytest.raises(PackUnavailable, match="method_changed"):
execute_pack(**operation, codex="must-not-run")
result_file = next(
scope["runtime_root"].glob(
"benchmark/trajectory-assessments/*/jobs/*/assessment.json"
)
)
result_file.write_text("{}", encoding="utf-8")
with pytest.raises(PackUnavailable, match="historical_result_unverified"):
inspect_pack(**scope)
def test_revised_producer_preserves_frozen_legacy_job_and_requires_new_execution(pack):
from loopx.capabilities.benchmark_toolkit.trajectory_assessment import prepare
scope, operation, current, input_path, sources, provider = pack
assert current["config"]["research_synthesis_revision"] == 2
prepared = prepare(input_path, model="gpt-6.1-sol", effort="max", service_tier="fast")
assert prepared["analysis_key"] == current["analysis_key"]
legacy = register_pack(**scope, input_path=input_path, source_root=sources,
title="Frozen legacy analysis", config={key: value for key, value in current["config"].items()
if key != "research_synthesis_revision"})
legacy_operation = {**scope, "pack_id": legacy["pack_id"], "analysis_key": legacy["analysis_key"]}
execute_pack(**legacy_operation, codex=provider)
old = inspect_pack(**scope, pack_id=legacy["pack_id"])
before = {path: path.read_bytes() for path in scope["runtime_root"].glob("**/jobs/*/*") if path.is_file()}
assert current["analysis_key"] != legacy["analysis_key"]
pending = inspect_pack(**scope, pack_id=current["pack_id"])
assert pending["job"] is None and pending["result"] is None
execute_pack(**operation, codex=provider)
new = inspect_pack(**scope, pack_id=current["pack_id"])
assert new["result"]["method_version"] == "research-episodes-synthesis-v2"
assert new["result"]["metrics"] == old["result"]["metrics"]
assert inspect_pack(**scope, pack_id=legacy["pack_id"]) == old
assert all(path.read_bytes() == content for path, content in before.items())
retained = {path: path.read_bytes() for path in scope["runtime_root"].glob("**/jobs/*/*") if path.is_file()}
selection = register_pack(**scope, input_path=input_path, source_root=sources,
title="Case-selection analysis", config={**current["config"], "research_synthesis_revision": 3},
base_pack_id=current["pack_id"])
selection_operation = {**scope, "pack_id": selection["pack_id"], "analysis_key": selection["analysis_key"]}
assert selection["analysis_key"] != current["analysis_key"]
assert inspect_pack(**scope, pack_id=selection["pack_id"])["job"] is None
execute_pack(**selection_operation, codex=provider)
selected = inspect_pack(**scope, pack_id=selection["pack_id"])
assert selected["result"]["method_version"] == "research-episodes-synthesis-v3"
assert selected["result"]["metrics"] == new["result"]["metrics"]
assert inspect_pack(**scope, pack_id=current["pack_id"]) == new
assert all(path.read_bytes() == content for path, content in retained.items())
retained = {path: path.read_bytes() for path in scope["runtime_root"].glob("**/jobs/*/*") if path.is_file()}
decision = register_pack(**scope, input_path=input_path, source_root=sources,
title="Decision-scoped analysis", config={**current["config"], "research_synthesis_revision": 4},
base_pack_id=selection["pack_id"])
decision_operation = {**scope, "pack_id": decision["pack_id"], "analysis_key": decision["analysis_key"]}
assert decision["analysis_key"] != selection["analysis_key"]
pending = inspect_pack(**scope, pack_id=decision["pack_id"])
assert pending["job"] is None and pending["result"] is None
execute_pack(**decision_operation, codex=provider)
decided = inspect_pack(**scope, pack_id=decision["pack_id"])
assert decided["result"]["method_version"] == "research-episodes-synthesis-v4"
assert decided["result"]["metrics"] == selected["result"]["metrics"]
assert inspect_pack(**scope, pack_id=selection["pack_id"]) == selected
assert all(path.read_bytes() == content for path, content in retained.items())
# Every version uses the same literal, source-qualified reader.
for op in [legacy_operation, operation, selection_operation, decision_operation]:
assert read_citation(**op, source_id="source", first_line=2, last_line=2)["text"] == (
"The native measurement did not improve utility · 原始测量。")
def _usage_fixture():
def counts(i, c, o):
return dict(input_tokens=i, cached_input_tokens=c, output_tokens=o)
events = [
dict(type="session_meta", payload=dict(id="solver-session")),
dict(type="event_msg", payload=dict(type="task_started", turn_id="a")),
dict(
type="event_msg",
payload=dict(
type="token_count",
info=dict(
total_token_usage=counts(100, 60, 10),
last_token_usage=counts(100, 60, 10),
),
),
),
dict(type="event_msg", payload=dict(type="task_complete", turn_id="a")),
dict(type="event_msg", payload=dict(type="task_started", turn_id="b")),
dict(
type="event_msg",
payload=dict(
type="token_count",
info=dict(
total_token_usage=counts(140, 80, 15),
last_token_usage=counts(40, 20, 5),
),
),
),
dict(type="event_msg", payload=dict(type="task_complete", turn_id="b")),
]
for i, event in enumerate(events):
event["timestamp"] = f"2026-01-01T00:00:0{i}Z"
return "\n".join(json.dumps(e) for e in events) + "\n"
def _request_usage_fixture():
"""Two Turns; one compaction request absent from the legacy counters."""
def tokens(i, c, o):
return dict(
input_tokens=i,
cached_input_tokens=c,
output_tokens=o,
cache_write_input_tokens=0,
reasoning_output_tokens=0,
total_tokens=i + o,
)
def request(response, turn, usage, thread, turn_usage=None):
return dict(
type="token_usage_record",
payload=dict(
thread_id="solver-session",
session_id="solver-session",
turn_id=turn,
root_turn_id=turn,
response_id=response,
usage=usage,
thread_token_usage=thread,
turn_token_usage=turn_usage or usage,
private_response_text="SYNTHETIC-PRIVATE-DO-NOT-TRANSPORT",
),
)
rows = [json.loads(line) for line in _usage_fixture().splitlines()]
compact = request(
"compact", "a", tokens(20, 10, 7), tokens(120, 70, 17), tokens(120, 70, 17)
)
rows[2:2] = [request("one", "a", tokens(100, 60, 10), tokens(100, 60, 10))]
rows[4:4] = [
compact,
dict(
type="compacted",
payload=dict(
compaction_response_id="compact",
latest_token_usage_record=compact["payload"],
replacement_history="SYNTHETIC-PRIVATE-DO-NOT-TRANSPORT",
),
),
]
rows[8:8] = [request("two", "b", tokens(40, 20, 5), tokens(160, 90, 22))]
for i, row in enumerate(rows):
row["timestamp"] = (
datetime(2026, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=i)
).isoformat()
return "\n".join(json.dumps(row) for row in rows) + "\n"
@pytest.mark.parametrize("counter_basis", ["ordinary_requests", "all_requests"])
def test_request_usage_native_cli_replay_privacy_and_historical_readback(
pack, monkeypatch, counter_basis
):
import loopx.capabilities.benchmark_toolkit.trajectory_assessment_store as store
scope, _, old, input_path, sources, _ = pack
capture = sources / "usage.jsonl"
rows = _request_usage_fixture().splitlines()
if counter_basis == "all_requests":
data = [json.loads(row) for row in rows]
counter = data[9]["payload"]["info"]
counter["total_token_usage"].update(input_tokens=160, cached_input_tokens=90, output_tokens=22, total_tokens=182)
counter["last_token_usage"].update(input_tokens=60, cached_input_tokens=30, output_tokens=12, total_tokens=72)
rows = [json.dumps(row) for row in data]
# Exercise the real large-snapshot transport with repeated observations,
# while the independent three-request total remains 160 input / 22 output.
rows[3:3] = [rows[2]] * 2500
capture.write_text("\n".join(rows) + "\n")
args = dict(
**scope,
input_path=input_path,
source_root=sources,
title=old["title"],
usage_jsonl="usage.jsonl",
usage_session_id="solver-session",
)
actual = store.effect_runtime_result
transported = []
def observe(command, params, **kwargs):
if command == "benchmark.trajectory.codex-usage":
transported.append(params)
return actual(command, params, **kwargs)
monkeypatch.setattr(store, "effect_runtime_result", observe)
registered = register_pack(**args)
view = inspect_pack(**scope)
facts = view["solver_usage"]["projection"]
assert facts["input_tokens"] == (160 if counter_basis == "all_requests" else 140)
assert facts["output_tokens"] == (22 if counter_basis == "all_requests" else 15)
coverage = facts["request_coverage"]
assert coverage["status"] == "verified"
assert coverage["counter_basis"] == counter_basis
assert coverage["all_requests"]["output_tokens"] == 22
assert coverage["compaction"]["output_tokens"] == 7
assert coverage["unique_requests"] == 3 and coverage["compaction_requests"] == 1
assert coverage["duplicate_records"] == 2500
assert len(json.dumps(transported).encode()) > 1024 * 1024
assert transported and "SYNTHETIC-PRIVATE" not in json.dumps(transported)
assert "SYNTHETIC-PRIVATE" not in json.dumps(view)
registry = sources.parent / "request-registry.json"
registry.write_text('{"projects":{}}')
prefix = [
sys.executable,
"-m",
"loopx.entrypoint",
"--registry",
str(registry),
"--runtime-root",
str(scope["runtime_root"]),
"--format",
"json",
"benchmark",
]
cli_args = [
"trajectory-pack-register",
"--goal-id",
scope["owner_goal_id"],
"--input-json",
str(input_path),
"--source-root",
str(sources),
"--title",