-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_grading_substrate_parity.py
More file actions
4631 lines (3960 loc) · 203 KB
/
Copy pathtest_grading_substrate_parity.py
File metadata and controls
4631 lines (3960 loc) · 203 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
"""Substrate-parity guard rail for the grading key manifest.
Twenty locks. Locks 1-15 are over :mod:`tolokaforge.core.grading.key_manifest`:
what each grading key is, which substrate scores it, and whether the two agree.
Locks 16-20 are over what a grade *does* and *says*, which the manifest does not
describe — the proposition a hash source compares against, what the hash reads a
record's numeric-looking strings as, what ``Grade.reasons`` carries for a component
that took a verdict, and whose mistake a comparison no trajectory could make is:
1. every field either substrate's grading config declares is claimed by exactly
one manifest entry, and every claimed field resolves; a position below a claimed
field is addressed by an element path, which is the only such mechanism;
2. the exemption sets are frozen here — in the test module, never beside the
manifest data they guard — so widening one is a reviewable edit, every entry
matching lock 3's predicate names both evaluators and owns a fixture, and every
entry carrying an ``enforcing_test`` — at any tier, since a canonically proven
claim may still record where it was observed in production — has that nodeid
resolve to a test function pytest would collect;
3. every key claiming both substrates at ``DIFFERENTIAL_CANONICAL`` demonstrably
moves both substrates' component scores, through each substrate's real
production evaluator and its real combine;
4. every key both substrates declare survives adapter translation;
5. every ledger key's ``runner_field`` resolves to a place in the runner
``GradingConfig`` dump *and* is declared in ``accountable_author_keys()``, the
per-key human claim that a recording site files it, so a malformed or
undeclared entry fails here rather than at grade time in production — lock 15
is what drives the site itself;
6. both substrates fold a hash verdict and a JSONPath score into one
``state_checks`` component by the author's weight, pinned cell by cell to
arithmetic this module computes for itself;
7. the hash verdict either substrate can produce is binary — source-audited for
the producers whose verdict leaves as a bare float in a tuple, and a type
invariant of ``HashGradingResult`` for the producer whose verdict leaves
inside it — which is what makes lock 6's canonical-tier hash inputs the only
values that path yields rather than a stand-in for it;
8. every ``DIFFERENTIAL_CANONICAL`` claim lock 3's predicate cannot reach is
enumerated here, and the tables those claims rest on — lock 6's weight sweep,
lock 9's method answers, lock 19's folding matrix — stay substantive; lock 19's
own nodeid is resolved besides, so that one differential cannot be deleted or
renamed with the set unchanged;
9. both substrates aggregate one split pair of deterministic components by the
author's ``combine.method``, each method pinned to a score written out here;
10. both substrates score one ``trace_checks`` pack to the same component through
their own grading path — the core engine's ``grade_trajectory``, and the
runner's ``GradeTrial`` over its real gRPC handlers — and the per-constraint
facts a reviewer reads off the grade rather than off the score, ``severity``,
the winning route and ``undecided``, reach the host from both;
11. both substrates read each per-constraint field that shapes how a kind scores
without carrying a score itself, over packs a build ignoring the field would
score identically;
12. the constraint vocabulary the manifest addresses, the one the evaluator and
the runtime ledger read, and the one an author can write are the same set;
13. a state source that declares nothing leaves ``state_checks`` unscored on both
substrates, and the one asymmetry the rule permits — a probe-only pack, which
only the runner can read, and which is the whole of what a pack declaring a probe
may be — is asserted against the manifest's own claim rather than assumed;
14. every scored component a pack produces declares a share of ``combine.weights``
on both substrates, and a fold with no share to read decides rather than
defaulting to one;
15. every ledger key's recording site is *driven*: a real
``RegisterTrial → ExecuteTool → GradeTrial`` populates the key, lets its
evaluator run, and the outcome the ledger reports is the one the manifest
implies. Editing a declaration cannot satisfy it — deleting a recording site,
downgrading it to a skip, filing ``EVALUATED`` over an evaluation that never
ran, or driving a config that never populated the key each fail it;
16. both substrates score ``state_checks.hash.expect_initial_state`` alike — the
proposition "the trial left the state as it found it", with each substrate
computing both sides of the comparison in its own hash algebra, because the two
label the same equivalence classes under different digests and no stored digest
is readable in both (#915);
17. the ``custom_checks`` segment of ``Grade.reasons`` names the check that decided
the trial, and is one text on both substrates — extracted from each substrate's
``reasons`` by splitting on the segment separator rather than compared whole,
because the two legitimately differ elsewhere in that string (#994);
18. every component :data:`GRADE_COMPONENTS` registers narrates itself in a real
grade: a trial driven through ``RegisterTrial → GradeTrial`` on a config
populating that component carries the marker production emits for it. The fold
enumerates the registry and the renderer enumerates by hand, so this is what
holds the second list to the first — and the row names the marker rather than
asking whether the grade said anything, because a component whose branch went or
whose marker was renamed leaves the grade just as full either way;
19. a record field's numeric-looking string folds on both substrates when — and only
when — ``state_checks.numeric_string_fields`` names that field: a matrix pairing a
representation difference against a genuine one, under the empty list, the list
naming the field that differs and a list of the same length naming another
declared field, so a build reading the list's length rather than the names it
holds fails one row alone.
20. a binding reference whose two runtime types the operator can never satisfy fails
the call it was read on rather than the constraint, on both substrates: a pack
addressing an argument the gate types at its first segment only scores ``1.0``
where one candidate made the comparison beside one that could not, and ``0.0``
where none could — with the sentence naming the reference on the verdict that
crosses the wire, since a diagnostic the author never reads leaves an authoring
mistake looking like the agent's.
The exemption sets and the differential fixtures are the enforcement mechanism:
adding a grading key to one substrate only cannot pass this suite without an
explicit, reviewable edit to one of the frozen constants below.
Locks 3, 6, 7, 9, 10, 11, 15, 16, 17, 18, 19 and 20 drive a real trial, and each reads
it through one fixture loader, so what a ``grading_parity`` pack can express bounds what
they can prove — for locks 15 and 18 that bound covers the keys their driver tables
send to a parity pack, the hash family, the probes and the judge being driven from
tasks written out in this module instead, for lock 17 it is one pack declaring one
check, so the shapes it reaches are all-passed and all-failed, and lock 20 reads a pack
under ``tests/data/tasks`` because the shape it needs is one no parity pack may declare. Lock 18's
``state_checks`` row drives one of that component's three sources; the sub-source
counterpart is three unit locks — ``test_runner_jsonpath_grading.py`` on the JSONPath
and db-probe sentences, and ``test_grading_correctness.py`` on the hash verdict — so
this module's table is not the whole guarantee for that slot.
That loader's contract — a tool call belongs to the message that requested it, and
carries that call's own result text — is locked at the end of this module.
"""
import ast
import asyncio
import importlib
import json
import re
import shutil
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from types import MappingProxyType, UnionType
from typing import Any, Union, get_args, get_origin, get_type_hints
import pytest
import yaml
from pydantic import BaseModel, ValidationError
from tests.utils.combine_method_verdicts import (
COMBINE_METHOD_COMPONENTS,
COMBINE_METHOD_PASS_THRESHOLD,
COMBINE_METHOD_VERDICTS,
)
from tests.utils.grading_parity_packs import (
FIXTURE_TIMESTAMP,
TrialCase,
load_case,
wire_message,
)
from tests.utils.runner_requests import execute_request, register_request, trial_spec_json
from tolokaforge.adapters.native import NativeAdapter
from tolokaforge.core import models as core_models
from tolokaforge.core.grading import composite as composite_module
from tolokaforge.core.grading import (
default_transcript_rule_matcher as default_transcript_rule_matcher_module,
)
from tolokaforge.core.grading.checks_helpers import CUSTOM_CHECKS_REASON_PREFIX
from tolokaforge.core.grading.combine import GradingEngine
from tolokaforge.core.grading.combine_method import COMBINE_METHODS
from tolokaforge.core.grading.combine_weights import MissingComponentWeight
from tolokaforge.core.grading.composite import _build_runner_check_transcript
from tolokaforge.core.grading.golden_replay import GoldenReplayRecord, resolve_initial_state
from tolokaforge.core.grading.grade_components import GRADE_COMPONENTS
from tolokaforge.core.grading.judge_result import JudgeResult, JudgeStatus, JudgeUsage
from tolokaforge.core.grading.key_manifest import (
GRADING_KEYS,
Enforcement,
GradingKey,
KeyKind,
SubstrateCoverage,
author_keys,
entry,
family_author_keys,
)
from tolokaforge.core.grading.state_checks import StateChecker, extract_db_state, state_digest
from tolokaforge.core.grading.trace_checks import evaluate_trace_checks
from tolokaforge.core.grading.trace_timeline import TrialTimeline
from tolokaforge.core.grading.transcript import evaluate_transcript_rules
from tolokaforge.core.models import (
Message,
RecordedToolCall,
ToolCall,
Trajectory,
)
from tolokaforge.runner import grading as runner_grading
from tolokaforge.runner import models as runner_models
from tolokaforge.runner import runner_pb2 as pb2
from tolokaforge.runner import service as runner_service_module
from tolokaforge.runner.grading import (
combine_grade_components,
evaluate_db_probes,
evaluate_jsonpath_checks,
resolve_state_checks_component,
)
from tolokaforge.runner.grading_ledger import (
LEDGER_KEYS,
LLM_JUDGE_KEY,
accountable_author_keys,
populated_ledger_keys,
runner_dump_path,
skip_note_prefix,
)
from tolokaforge.runner.models import (
TRACE_CONSTRAINT_KINDS,
KeyAccounting,
KeyAccountingRecord,
TraceConstraintExpr,
)
from tolokaforge.runner.service import (
RunnerServiceImpl,
TrialContextRuntime,
)
pytestmark = pytest.mark.canonical
_REPO_ROOT = Path(__file__).resolve().parents[2]
_PARITY_GLOB = "grading_parity/**/task.yaml"
_TASKS_GLOB = "tasks/**/task.yaml"
_ALL_KEYS_TASK = "all_keys"
COMPOSITION_PARITY_WEIGHTS: tuple[float, ...] = (0.0, 0.25, 0.6, 1.0)
"""The ``state_checks.hash.weight`` values lock 6 drives both substrates at.
The endpoints pin the two single-source limits — ``0.0`` scores the JSONPath
assertions alone, ``1.0`` the hash verdict alone. The interior weights are where a
fold that *selects* the dominant source instead of mixing the two diverges from
``j(1-w) + hw``, and the endpoints cannot see that: a rule returning ``j`` below
``w=0.5`` and ``h`` above it reproduces the blend at both ends. Lock 8 holds the
sweep to at least two of them.
"""
_COMPOSITION_KEY = "state_checks.hash.weight"
# The fixture satisfies one of its two assertions on both trial cases, so the
# JSONPath half of the fold is strictly partial and the blend is distinguishable
# from every rule that agrees with it at 0 and 1.
_COMPOSITION_JSONPATH_SCORE = 0.5
# Case name -> the hash verdict it produces against the hash of the state the pack's
# task declares it starts in. Lock 7 asserts core's evaluator really returns these.
_COMPOSITION_HASH_CASES: tuple[tuple[str, float], ...] = (
("hash_matching", 1.0),
("hash_diverging", 0.0),
)
_JSONPATHS_KEY = "state_checks.jsonpaths"
_PROBES_KEY = "state_checks.db_probes"
# The one in-repo pack whose only state source is a probe, so it is the only fixture
# that can show the RUNNER_ONLY asymmetry lock 13 asserts. It sits under
# ``tests/data/tasks/`` rather than in the parity corpus because that corpus's packs
# each isolate one key, and a probe-only pack isolates this one by construction.
_PROBE_PACK = "db_probe_grading"
_METHOD_KEY = "combine.method"
_METHOD_CASE = "split_components"
_HASH_SCORE_NAME = "hash_score"
_BINARY_HASH_VERDICT = frozenset({0.0, 1.0})
_UNSCORED_COMPONENT = -1.0
"""What ``GradeComponents`` carries for a component the runner did not score.
Every component evaluator in ``tolokaforge/runner/grading.py`` returns it when
handed nothing to evaluate, so a slot holding it means no evaluation happened
whatever the ledger recorded for the keys that feed it.
"""
_HASH_FAMILY_ROOT = "state_checks.hash"
_EXPECT_INITIAL_STATE_KEY = "state_checks.hash.expect_initial_state"
_GOLDEN_ACTIONS_KEY = "state_checks.hash.golden_actions"
_NUMERIC_STRING_FIELDS_KEY = "state_checks.numeric_string_fields"
# The one in-repo pack that both declares golden actions and gives them a world to be
# replayed in — a JSON initial-state file and an ``mcp_server`` whose tools they call.
# It sits under ``tests/data/tasks/`` for the reason :data:`_PROBE_PACK` does.
_GOLDEN_REPLAY_PACK = "shop_orders_02"
# Every function that can hand a hash verdict to the shared composer, as
# (repo-relative module, function name), partitioned by the shape the verdict
# leaves in. Tuple-verdict producers hand it on as a bare float in a tuple, so
# lock 7 audits their sources; the model-verdict producer returns it inside
# ``HashGradingResult``, which derives the score from ``hash_match``, so lock 7
# proves that invariant instead of reading its source. The union is asserted as
# set equality against the hash family's declared evaluators, so a fourth
# producer forces an edit here instead of landing with lock 7 green and lock
# 6's binariness premise false.
_TUPLE_VERDICT_PRODUCERS = frozenset(
{
("tolokaforge/core/grading/state_checks.py", "check_hash"),
("tolokaforge/core/grading/state_checks.py", "check_hash_against_golden_replay"),
}
)
_MODEL_VERDICT_PRODUCERS = frozenset(
{
("tolokaforge/runner/service.py", "_execute_hash_grading"),
}
)
# --------------------------------------------------------------------------
# Frozen exemption sets — the gate. Each is asserted as set equality against a
# set computed from the manifest, so drift cannot widen an exemption silently.
# --------------------------------------------------------------------------
# Non-BOTH keys that can never be both substrates. tracking_issue must be None.
_ARCHITECTURAL_EXEMPTIONS = frozenset(
{
"state_checks.db_probes",
"state_checks.hash.description",
"llm_judge",
"grading_method",
}
)
# Non-BOTH keys that should be both and are not yet. tracking_issue is required.
_DRIFT_EXEMPTIONS: frozenset[str] = frozenset()
# Scored keys that claim both substrates but are not differentially proven
# in-process. A key added here is a key whose parity claim rests on field
# resolution alone.
_NON_DIFFERENTIAL_SCORED_KEYS = frozenset(
{
"state_checks.hash",
"state_checks.hash.enabled",
"state_checks.hash.golden_actions",
}
)
# DIFFERENTIAL_CANONICAL entries lock 3's predicate does not reach, because it
# selects kind: SCORED_CHECK and these carry no component score of their own. Each
# one needs a differential of its own in this module; lock 8 holds the set.
_CANONICAL_DIFFERENTIALS_OUTSIDE_LOCK_3 = frozenset(
{
"state_checks.hash.weight",
"state_checks.numeric_string_fields",
"combine.method",
"combine.weights",
"trace_checks",
"trace_checks.constraints.weight",
"trace_checks.constraints.on_missing",
"trace_checks.constraints.severity",
"trace_checks.constraints.within",
"trace_checks.constraints.bind",
}
)
# The five per-constraint fields that shape how a kind scores without scoring
# anything themselves. Each owns a pack whose two trials a build ignoring the
# field would score identically, so discrimination is the field being read.
_TRACE_CONFIG_INPUT_KEYS: tuple[str, ...] = (
"trace_checks.constraints.weight",
"trace_checks.constraints.on_missing",
"trace_checks.constraints.severity",
"trace_checks.constraints.within",
"trace_checks.constraints.bind",
)
# FIELD_RESOLUTION_ONLY entries that need no tracking issue: aggregation and
# load-time config inputs, which have no violating trajectory by construction.
_NON_TRACKED_FIELD_RESOLUTION_KEYS = frozenset(
{
"combine.pass_threshold",
"state_checks.hash.description",
"state_checks.id_fields",
"state_checks.relaxed_validation",
"grading_method",
}
)
# Fields the field walker descends into instead of claiming as author keys.
_CONTAINER_FIELDS = frozenset(
{
"core:GradingConfig.combine",
"core:GradingConfig.state_checks",
"core:StateChecksConfig.hash",
"core:GradingConfig.transcript_rules",
"core:GradingConfig.trace_checks",
"runner:RunnerGradingConfig.state_checks",
"runner:RunnerGradingConfig.transcript_rules",
"runner:RunnerGradingConfig.trace_checks",
}
)
_SUBSTRATE_ROOTS: dict[str, type[BaseModel]] = {
"core": core_models.GradingConfig,
"runner": runner_models.RunnerGradingConfig,
}
# --------------------------------------------------------------------------
# Manifest introspection helpers
# --------------------------------------------------------------------------
def _field_of(item: GradingKey, substrate: str) -> str | None:
return item.core_field if substrate == "core" else item.runner_field
def _element_path_of(item: GradingKey, substrate: str) -> str | None:
return item.core_element_path if substrate == "core" else item.runner_element_path
def _claimed_fields(substrate: str) -> dict[str, list[str]]:
"""Model field paths claimed directly -> author keys.
An entry carrying an element path is not claiming the field: it claims one
place *inside* it, and several such entries share the field. Counting them as
claims would report the shared field as claimed twice over.
"""
claims: dict[str, list[str]] = {}
for item in GRADING_KEYS:
field = _field_of(item, substrate)
if field is None or _element_path_of(item, substrate) is not None:
continue
claims.setdefault(field, []).append(item.author_key)
return claims
def _union_options(annotation: Any) -> tuple[Any, ...]:
if get_origin(annotation) in (Union, UnionType):
return get_args(annotation)
return (annotation,)
def _direct_model(annotation: Any) -> type[BaseModel] | None:
"""The nested model a field holds directly, or None.
A ``list[SomeModel]`` field is a leaf: its elements are the shape of one
author key's value, not separate author keys.
"""
for option in _union_options(annotation):
if (
get_origin(option) is None
and isinstance(option, type)
and issubclass(option, BaseModel)
):
return option
return None
def _element_model(annotation: Any) -> type[BaseModel] | None:
"""The element model of a ``list[SomeModel]`` field, which ``_direct_model`` skips.
That skip is what makes an element path necessary: the walker treats such a
field as one leaf, so several author keys living inside its elements have no
address it can resolve until the manifest names one.
"""
for option in _union_options(annotation):
if get_origin(option) is not list:
continue
(element,) = get_args(option)
if isinstance(element, type) and issubclass(element, BaseModel):
return element
return None
def _resolve_element_path(model: type[BaseModel], element_path: str, *, what: str) -> None:
"""Walk ``element_path`` from ``model``, asserting every segment is a declared field.
Each segment resolves against the model the one before it holds, so a path
naming a field of the wrong model fails here rather than addressing nothing.
A ``list[SomeModel]`` segment continues into its element model, which is how
``all_of``'s nested expressions stay walkable.
"""
segments = element_path.split(".")
current: type[BaseModel] | None = model
for index, segment in enumerate(segments):
assert current is not None, (
f"{what}: element path {element_path!r} reads {segment!r} out of "
f"{segments[index - 1]!r}, which holds no model to resolve it against"
)
field = current.model_fields.get(segment)
assert field is not None, (
f"{what}: element path {element_path!r} does not resolve — {current.__name__} "
f"declares no field {segment!r}. It declares {sorted(current.model_fields)}"
)
current = _direct_model(field.annotation) or _element_model(field.annotation)
def _walk(substrate: str) -> tuple[set[str], set[str], dict[str, type[BaseModel]]]:
"""Walk a substrate's grading config from its root ``GradingConfig``.
Returns leaf field paths, substrate-prefixed container field paths, and the
reachable model registry (used to resolve manifest ``*_field`` paths).
"""
claimed = _claimed_fields(substrate)
leaves: set[str] = set()
containers: set[str] = set()
registry: dict[str, type[BaseModel]] = {}
queue = [_SUBSTRATE_ROOTS[substrate]]
while queue:
current = queue.pop()
if current.__name__ in registry:
continue
registry[current.__name__] = current
for name, field in current.model_fields.items():
qualified = f"{current.__name__}.{name}"
nested = _direct_model(field.annotation)
if nested is not None and qualified not in claimed:
containers.add(f"{substrate}:{qualified}")
queue.append(nested)
continue
leaves.add(qualified)
return leaves, containers, registry
def _assert_element_paths_resolve(substrate: str, registry: dict[str, type[BaseModel]]) -> None:
"""Every element-addressed entry names a list of models and a path inside it."""
for item in GRADING_KEYS:
element_path = _element_path_of(item, substrate)
field = _field_of(item, substrate)
if element_path is None or field is None:
continue
what = f"{item.author_key} ({substrate})"
model_name, _, field_name = field.partition(".")
model = registry.get(model_name)
assert model is not None, (
f"{what}: {substrate}_field {field!r} names {model_name!r}, which is not "
f"reachable from the {substrate} GradingConfig"
)
declared = model.model_fields.get(field_name)
assert declared is not None, (
f"{what}: {substrate}_field {field!r} does not resolve — {model_name} has no "
f"field {field_name!r}"
)
element = _element_model(declared.annotation)
assert element is not None, (
f"{what}: {substrate}_element_path {element_path!r} is walked from the element "
f"model of {field!r}, which is not a list of models"
)
_resolve_element_path(element, element_path, what=what)
def _differential_entries() -> tuple[GradingKey, ...]:
"""Test 3's predicate, stated once and reused by test 2."""
return tuple(
item
for item in GRADING_KEYS
if item.kind is KeyKind.SCORED_CHECK
and item.coverage.startswith("BOTH")
and item.enforcement is Enforcement.DIFFERENTIAL_CANONICAL
)
def _assert_nodeid_is_collectable(label: str, nodeid: str) -> None:
"""The nodeid names a module-level function pytest would collect.
Resolved by parsing the module, never by importing it: the integration tier
pulls testcontainers and a docker daemon, neither of which the canonical tier
has. That is also the limit of what this can prove — the nodeid resolves and is
collectable; whether it *passes* is what running that tier answers.
"""
module_path, separator, function_name = nodeid.partition("::")
assert separator, (
f"{label} {nodeid!r} is a module path, not a pytest nodeid, so it names a file that "
"may hold no test function at all"
)
module_file = _REPO_ROOT / module_path
assert module_file.is_file(), (
f"{label} names module {module_path!r}, which does not exist on disk, so nothing "
"proves the differential"
)
declared = {
node.name
for node in ast.parse(module_file.read_text()).body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
}
collectable = sorted(name for name in declared if name.startswith("test_"))
assert function_name in declared, (
f"{label} names {function_name!r}, which {module_path} does not declare at module "
f"level. It declares {collectable}"
)
assert function_name.startswith("test_"), (
f"{label} names {function_name!r}, which pytest does not collect as a test — the nodeid "
"resolves to a function no run of that module would execute"
)
def _assert_enforcing_test_is_collectable(item: GradingKey) -> None:
"""The integration test the entry names exists as a function pytest would collect."""
_assert_nodeid_is_collectable(f"{item.author_key}: enforcing_test", item.enforcing_test)
def _split_dotted(path: str) -> tuple[Any, list[str]]:
"""A dotted path's longest importable module prefix, and the attributes after it."""
parts = path.split(".")
for boundary in range(len(parts), 0, -1):
try:
module = importlib.import_module(".".join(parts[:boundary]))
except ImportError:
continue
return module, parts[boundary:]
raise ImportError(f"no importable module prefix in {path!r}")
def _import_dotted(path: str) -> Any:
"""Resolve a dotted module/attribute path, longest importable prefix first."""
module, attributes = _split_dotted(path)
resolved: Any = module
for attribute in attributes:
resolved = getattr(resolved, attribute)
return resolved
def _evaluator_source(evaluator: str) -> tuple[str, str]:
"""A declared evaluator's source location: (repo-relative module, function name)."""
module, attributes = _split_dotted(evaluator)
assert attributes, f"{evaluator!r} names a module, not a function with source to read"
return str(Path(module.__file__).resolve().relative_to(_REPO_ROOT)), attributes[-1]
def _declared_hash_verdict_producers() -> dict[tuple[str, str], Any]:
"""Every evaluator the manifest names for a *scored* member of the hash family.
Keyed by source location — what the frozen producer partitions pin — with the
resolved callable as the value, so lock 7's model-verdict clause reads the
declared return type off the same walk its gate reads the set from.
``state_checks.hash.weight`` is ``CONFIG_INPUT`` — it names the composer that
consumes a verdict, not a function that produces one — so the ``SCORED_CHECK``
filter is what keeps the fold itself out of the audit.
"""
return {
_evaluator_source(evaluator): _import_dotted(evaluator)
for author_key in family_author_keys(_HASH_FAMILY_ROOT)
for evaluator in (entry(author_key).core_evaluator, entry(author_key).runner_evaluator)
if evaluator is not None and entry(author_key).kind is KeyKind.SCORED_CHECK
}
# --------------------------------------------------------------------------
# Fixture-pack helpers
# --------------------------------------------------------------------------
def _task_id_for(author_key: str) -> str:
return author_key.replace(".", "_")
def _pack_dir(test_data_dir: Path, author_key: str) -> Path:
return test_data_dir / "grading_parity" / _task_id_for(author_key)
def _adapter_for(test_data_dir: Path, tasks_glob: str) -> NativeAdapter:
return NativeAdapter({"base_dir": str(test_data_dir), "tasks_glob": tasks_glob})
def _parity_adapter(test_data_dir: Path) -> NativeAdapter:
return _adapter_for(test_data_dir, _PARITY_GLOB)
_MISSING = object()
def _yaml_node(data: Any, dotted_path: str) -> Any:
"""What ``dotted_path`` holds in an authored ``grading.yaml``, or ``_MISSING``."""
node = data
for segment in dotted_path.split("."):
if not isinstance(node, dict) or segment not in node:
return _MISSING
node = node[segment]
return node
def _yaml_declares(data: Any, dotted_path: str) -> bool:
return _yaml_node(data, dotted_path) is not _MISSING
def _yaml_element_declares(node: Any, segments: tuple[str, ...]) -> bool:
"""Whether ``segments`` resolves inside one authored list element.
A kind written inside a composite counts as declared: where a segment is not
at this level the walk follows the expressions the kinds hold, so an ``all_of``
holding a ``before`` declares ``before``. Descent stops outside a constraint
kind, because a matcher's ``args`` keys are the author's own argument names.
"""
if not segments:
return True
if not isinstance(node, dict):
return False
if segments[0] in node:
return _yaml_element_declares(node[segments[0]], segments[1:])
return any(
_yaml_element_declares(nested, segments)
for kind in TRACE_CONSTRAINT_KINDS
if kind in node
for nested in (node[kind] if isinstance(node[kind], list) else [node[kind]])
)
def _declared_author_keys(grading_yaml: dict[str, Any]) -> set[str]:
"""Every manifest key an authored ``grading.yaml`` declares.
An element-addressed key lives inside the elements of the list its parent key
names, so its declaredness is read there rather than at a dotted path of its
own — a kind is not a YAML key under ``constraints``, it is a key on one of the
constraints.
"""
declared: set[str] = set()
for key in author_keys():
element_path = entry(key).core_element_path
if element_path is None:
if _yaml_declares(grading_yaml, key):
declared.add(key)
continue
elements = _yaml_node(grading_yaml, key.rsplit(".", 1)[0])
if isinstance(elements, list) and any(
_yaml_element_declares(element, tuple(element_path.split("."))) for element in elements
):
declared.add(key)
return declared
_CONSTRAINT_KIND_KEYS = frozenset(
f"trace_checks.constraints.{kind.value}" for kind in TRACE_CONSTRAINT_KINDS
)
_BLOCK_SWITCH = "enabled"
def _authoring_the_same_key(declared_key: str, author_key: str) -> bool:
"""Whether ``declared_key`` is part of writing ``author_key`` down.
Four structural cases, none of them a second check. The ancestors a leaf
lives under: a constraint kind needs the block and the list around it. The
leaves of a key standing for a list: writing something in the list is what
authoring the list looks like. And another kind beside a kind — a composite
is an expression over other kinds and cannot be written without them, which
is why the sharper assertion on what a pack authors at *top level* is the one
that keeps a kind's pack about that kind.
The fourth is the switch that turns a block on. A source inside a block cannot
be written without it — ``state_checks.hash.expect_initial_state`` under an
``enabled: false`` block is read by nothing — and the switch carries no verdict
of its own: with it off there is no component to discriminate the two trials by,
so it cannot be what discriminated them.
"""
block, _, leaf = author_key.rpartition(".")
return (
declared_key == author_key
or author_key.startswith(f"{declared_key}.")
or declared_key.startswith(f"{author_key}.")
or {declared_key, author_key} <= _CONSTRAINT_KIND_KEYS
or (leaf != _BLOCK_SWITCH and declared_key == f"{block}.{_BLOCK_SWITCH}")
)
def _top_level_constraint_kinds(grading_yaml: dict[str, Any]) -> set[str]:
"""The kind each authored constraint *is*, ignoring what its composites nest."""
constraints = _yaml_node(grading_yaml, "trace_checks.constraints")
if not isinstance(constraints, list):
return set()
return {
kind
for element in constraints
if isinstance(element, dict) and isinstance(element.get("require"), dict)
for kind in element["require"]
if kind in TRACE_CONSTRAINT_KINDS
}
class _FixtureStateDBClient:
"""Serves a table map where a real trial reads it from the DB service.
``StateResponse.data`` is the trial's ``table -> rows`` map, which the fixture
holds under ``state.db`` — the same level ``build_check_context`` picks for the
core engine. Both substrates therefore read one set of rows, so a score
difference can only come from the grading path itself.
"""
def __init__(self, tables: dict[str, list[dict[str, Any]]]) -> None:
self._tables = tables
async def get_state(self, trial_id: str) -> runner_models.StateResponse:
return runner_models.StateResponse(
data=self._tables, version=1, full_hash="", stable_hash=""
)
def _core_verdict(
family: str,
grading_config: core_models.GradingConfig,
case: TrialCase,
task_dir: Path,
*,
task_initial_state: core_models.InitialStateConfig | None,
) -> tuple[float, float]:
"""(component score, combined score) from the core engine's real combine.
The engine is built the way ``adapters/base.py`` builds it for a real trial, so a
pack whose grading reads a task-level fact — the state it starts in, which the
hash block's ``expect_initial_state`` source compares against — is graded here
against the same fact production would hand it rather than against nothing.
"""
grade = GradingEngine(
grading_config, task_dir=task_dir, task_initial_state=task_initial_state
).grade_trajectory(case.core_trajectory, case.state)
component = getattr(grade.components, family, None)
assert component is not None, (
f"the core engine produced no {family!r} component — either that family has no "
"core GradeComponents slot or the fixture never exercised it"
)
return component, grade.score
def _runner_custom_checks_score(
task_description: runner_models.TaskDescription, case: TrialCase
) -> float:
"""The runner's ``custom_checks`` component, via its real delivery + executor.
``checks.py`` reaches the runner as a base64 ``tool_artifacts`` entry, so the
extraction step is part of the path under test: a pack the adapter failed to
bundle scores nothing here rather than passing on a directory the test handed
over. ``shutdown`` then removes the temp dir extraction created.
"""
servicer = RunnerServiceImpl(db_client=_FixtureStateDBClient(case.state["db"]))
try:
trial_id = f"{task_description.task_id}:0"
servicer._extract_tool_artifacts(trial_id, task_description.tool_artifacts)
context = TrialContextRuntime(trial_id=trial_id, task_description=task_description)
substrate = servicer._build_grading_substrate(trial_id, context)
score, _, _ = servicer._run_async(
servicer._grade_custom_checks(
trial_id, context, case.runner_messages, substrate=substrate
)
)
return score
finally:
servicer.shutdown()
def _write_case_state_into_the_trial_database(
servicer: RunnerServiceImpl, trial_id: str, tables: Mapping[str, list[dict[str, Any]]]
) -> None:
"""Move the trial's database to ``tables``, one upsert per record.
Generic over the fixture: every record of every table is written under the
upsert's own key resolution, so a pack's authored state reaches db-service
without this helper knowing which tables it holds. Upsert rather than a wholesale
replace because that is the mutation db-service offers for a record that may or
may not already be there — a case that expects a record *removed* would need a
delete this does not write, and the verdict would then disagree with the fixture
rather than quietly agree with it.
"""
for table, records in tables.items():
servicer._run_async(
servicer.db_client.mutate(
trial_id, table, [{"op": "upsert", "record": record} for record in records]
)
)
def _runner_state_checks_hash_verdict(
task_description: runner_models.TaskDescription,
case: TrialCase,
servicer: RunnerServiceImpl,
context: Any,
*,
trial_id: str,
) -> tuple[float, float]:
"""(state_checks component, trial score) from the runner's own ``GradeTrial``.
The hash evaluator reads the trial's database rather than the case's ``state``
mapping, so the case has to *be* the database: ``RegisterTrial`` provisions it
from the pack's ``initial_state`` — which is the expected side of the comparison —
and the trial's own records are written over it before grading.
The combined score is the runner's own fold off the same response, so both halves
of the return come from one real trial rather than from a second computation here.
"""
_register_pack(servicer, context, task_description, trial_id)
_replay_authored_calls(servicer, context, trial_id, case)
_write_case_state_into_the_trial_database(servicer, trial_id, case.state["db"])
response = _grade_registered_trial(
servicer, context, trial_id, json.dumps(case.runner_messages)
)
assert response.success is True, response.error
component = response.grade.components.state_checks
assert component != _UNSCORED_COMPONENT, (
"the runner graded the pack without scoring state_checks, so this cell carries "
"the unscored sentinel rather than a hash verdict — two of them read as "
f"agreement between the substrates and prove nothing: {response.grade.reasons!r}"
)
return component, response.grade.score
def _runner_verdict(
family: str,
task_description: runner_models.TaskDescription,
case: TrialCase,
*,
servicer: RunnerServiceImpl,
context: Any,
trial_id: str,
) -> tuple[float, float]:
"""(component score, combined score) from the runner's real evaluators.
``state_checks`` splits on what the pack declares rather than on the key under
test: a hash block naming a state the trial is compared against is scored by an
evaluator that resets and hashes a real database, which is reachable only through
a registered trial. A pack declaring no hash source keeps the in-process JSONPath
path, so no cell that passed before this arm existed is driven differently now.
"""
grading = task_description.grading
if family == "state_checks":
state_checks = grading.state_checks
undeclared = runner_models.HashComparisonBasis.UNDECLARED_INITIAL_STATE
if state_checks.hash_enabled and state_checks.hash_comparison_basis() is not undeclared:
return _runner_state_checks_hash_verdict(
task_description, case, servicer, context, trial_id=trial_id
)
component, _ = evaluate_jsonpath_checks(state_checks.jsonpath_checks, state=case.state)
components = {"jsonpath_score": component}
elif family == "transcript_rules":
result = evaluate_transcript_rules(case.runner_timeline, grading.transcript_rules)
component = result.score
components = {"transcript_score": component}
elif family == "custom_checks":
component = _runner_custom_checks_score(task_description, case)
components = {"custom_checks_score": component}
elif family == "trace_checks":
# One evaluator serves both substrates, so the equality this lock ends on
# holds by construction; what a cell proves is that the pack loads through
# the adapter onto the runner's own model and that the kind discriminates
# there. That the runner's GradeTrial really reaches this evaluator is a
# separate claim, driven over real gRPC by lock 10.
component = evaluate_trace_checks(case.runner_timeline, grading.trace_checks).score
components = {"trace_checks_score": component}
else:
pytest.fail(
f"no runner differential driver for the {family!r} family — add one rather "
"than silently skipping the key"
)
combined = combine_grade_components(components, grading.model_dump())
return component, combined.score
# --------------------------------------------------------------------------
# 1. Every declared config field is claimed by exactly one manifest entry
# --------------------------------------------------------------------------
def test_manifest_covers_every_declared_config_field():
containers: set[str] = set()
for substrate in _SUBSTRATE_ROOTS:
leaves, substrate_containers, registry = _walk(substrate)
containers |= substrate_containers
claims = _claimed_fields(substrate)
unclaimed = sorted(leaf for leaf in leaves if leaf not in claims)
assert not unclaimed, (
f"{substrate} grading config declares fields with no key_manifest entry: "
f"{unclaimed}. Add a GradingKey for each — a field neither substrate's "
"manifest claims is a key that can silently no-op."
)
duplicated = {path: keys for path, keys in claims.items() if len(keys) > 1}
assert not duplicated, f"{substrate} fields claimed by more than one entry: {duplicated}"
for path, keys in sorted(claims.items()):
model_name, _, field_name = path.partition(".")
model = registry.get(model_name)
assert model is not None, (
f"{keys[0]}: {substrate}_field {path!r} names {model_name!r}, which is not "
f"reachable from the {substrate} GradingConfig"
)
assert field_name in model.model_fields, (
f"{keys[0]}: {substrate}_field {path!r} does not resolve — "
f"{model_name} has no field {field_name!r}"
)
_assert_element_paths_resolve(substrate, registry)
assert containers == _CONTAINER_FIELDS, (
"the set of grading config fields walked into as containers changed. Every "
"container's leaves must be claimed individually; a new container here means "
"a new key family landed on a substrate."
)
def test_a_position_inside_a_claimed_field_is_addressed_by_an_element_path():
"""An element path is the manifest's one address for a place below a field.
An entry whose author key sits under another entry's, on a substrate where that
parent claims a field, names a position inside that field's value rather than a
field of its own. Read as a set equality so both halves are findings: a key
inside a claimed field carrying no element path addresses nothing the suite can
walk, and an element path under a parent that claims no field is walked from
nowhere. The field the path starts at is then checked to be the parent's own.
"""
by_key = {item.author_key: item for item in GRADING_KEYS}
for substrate in _SUBSTRATE_ROOTS:
inside_a_claimed_field = {
item.author_key
for item in GRADING_KEYS
if (parent := by_key.get(item.author_key.rpartition(".")[0])) is not None
and _field_of(parent, substrate) is not None
}
element_addressed = {
item.author_key
for item in GRADING_KEYS
if _element_path_of(item, substrate) is not None
}
assert element_addressed, (