File size: 31,073 Bytes
75ea5f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Action, parameter, step, subtask, and part metrics for CAD-Drawer.

The dataset is the sole source of ground truth. Prediction artifacts contribute
only a global row index (_idx) and raw model text (prediction).
Missing/unparseable/error rows remain in the fixed reference denominator.
"""

from collections import Counter, defaultdict
import gzip
import hashlib
import json
import os
from pathlib import Path
import re


if __package__:
    from . import action_metrics, action_parser as action_runner
else:
    import action_metrics
    import action_parser as action_runner


CANONICAL_TEST_FINAL_SHA256 = (
    "a0a9c3bd89641b33b4c45237157374f0db0e64711d6cf6a1260a419c47bdda7d"
)
CANONICAL_TEST_FINAL_SLOTS = 29239
STRATIFIED_TEST_50_SHA256 = (
    "ca1c3b0764f4774dca7b51d0b2bb9fd6660224d6e97e201974645895a45c5a32"
)
STRATIFIED_TEST_50_SLOTS = 3352
HELDOUT_TEST_364_SHA256 = (
    "991983a4945c1124ce067a521810ad7f04ef8fd65f8c5a6fc8ca1d2f95d8e9ec"
)
HELDOUT_TEST_364_SLOTS = 25887


REGISTERED_DATASET_CONTRACTS = {
    "canonical_test_final_414": {
        "sha256": CANONICAL_TEST_FINAL_SHA256,
        "slots": CANONICAL_TEST_FINAL_SLOTS,
        "parts": 414,
        "canonical_full_test": True,
    },
    "stratified_test_50_seed42": {
        "sha256": STRATIFIED_TEST_50_SHA256,
        "slots": STRATIFIED_TEST_50_SLOTS,
        "parts": 50,
        "canonical_full_test": False,
    },
    "heldout_test_364_seed42_complement": {
        "sha256": HELDOUT_TEST_364_SHA256,
        "slots": HELDOUT_TEST_364_SLOTS,
        "parts": 364,
        "canonical_full_test": False,
        "model_selection_heldout": True,
        "complement_of": "stratified_test_50_seed42",
    },
}


class ScoringError(RuntimeError):
    """Prediction artifact or reference contract is invalid."""


def identify_dataset_contract(records, dataset_hash):
    """Return a registered immutable benchmark contract, if one matches."""
    part_count = len({
        record.get("part_id") for record in records
        if record.get("part_id") is not None
    })
    for name, contract in REGISTERED_DATASET_CONTRACTS.items():
        if (
            len(records) == contract["slots"] and
            part_count == contract["parts"] and
            dataset_hash == contract["sha256"]
        ):
            return {"name": name, **contract}
    return None


def dataset_sha256(path, chunk_size=1024 * 1024):
    digest = hashlib.sha256()
    opener = gzip.open if Path(path).suffix.lower() == ".gz" else open
    with opener(path, "rb") as handle:
        while True:
            block = handle.read(chunk_size)
            if not block:
                break
            digest.update(block)
    return digest.hexdigest()


def read_jsonl(path):
    rows = []
    opener = gzip.open if Path(path).suffix.lower() == ".gz" else open
    with opener(path, "rt", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as exc:
                raise ScoringError(
                    "%s:%d is invalid JSON: %s" %
                    (path, line_number, exc)) from exc
            if not isinstance(value, dict):
                raise ScoringError(
                    "%s:%d must contain a JSON object" %
                    (path, line_number))
            rows.append(value)
    return rows


def reference_slice(records, start_index=0, limit=0):
    if isinstance(start_index, bool) or start_index < 0:
        raise ScoringError("start_index must be a non-negative integer")
    if isinstance(limit, bool) or limit < 0:
        raise ScoringError("limit must be a non-negative integer")
    if start_index > len(records):
        raise ScoringError(
            "start_index %d exceeds dataset size %d" %
            (start_index, len(records)))
    end_index = len(records)
    if limit:
        end_index = min(end_index, start_index + limit)
    return range(start_index, end_index)


def reference_indices(records, start_index=0, limit=0,
                      num_shards=1, shard_index=0):
    """Select a deterministic modulo shard from a canonical reference slice."""
    if isinstance(num_shards, bool) or num_shards <= 0:
        raise ScoringError("num_shards must be a positive integer")
    if (
        isinstance(shard_index, bool) or shard_index < 0 or
        shard_index >= num_shards
    ):
        raise ScoringError(
            "shard_index must be in [0, %d)" % num_shards)
    base = reference_slice(
        records, start_index=start_index, limit=limit)
    return [
        index for index in base
        if index % num_shards == shard_index
    ]


def load_prediction_map(path, allowed_indices):
    allowed = set(allowed_indices)
    predictions = {}
    for line_number, row in enumerate(read_jsonl(path), 1):
        if "_idx" not in row:
            raise ScoringError(
                "prediction record %d has no _idx" % line_number)
        index = row["_idx"]
        if isinstance(index, bool) or not isinstance(index, int):
            raise ScoringError(
                "prediction record %d has non-integer _idx=%r" %
                (line_number, index))
        if index not in allowed:
            raise ScoringError(
                "prediction record %d has out-of-slice _idx=%d" %
                (line_number, index))
        if index in predictions:
            raise ScoringError(
                "duplicate prediction _idx=%d (record %d)" %
                (index, line_number))
        predictions[index] = row
    return predictions


FORMAT_PATTERN = re.compile(
    r"^\s*<ui_reasoning\b[^>]*>.*?</ui_reasoning>\s*"
    r"<action\b[^>]*>.*?</action>\s*"
    r"<parameters\b[^>]*>.*?</parameters>\s*$",
    flags=re.IGNORECASE | re.DOTALL,
)


def is_format_compliant(text):
    if not isinstance(text, str):
        return False
    if not FORMAT_PATTERN.fullmatch(text):
        return False
    lowered = text.lower()
    return all(lowered.count("<%s" % tag) == 1 for tag in (
        "ui_reasoning", "action", "parameters"))


def _empty_counts():
    return {
        "slots": 0,
        "parseable": 0,
        "format_compliant": 0,
        "action_correct": 0,
        "parameter_correct": 0,
        "step_correct": 0,
    }


def _with_rates(counts):
    result = dict(counts)
    denominator = counts["slots"]
    for numerator, rate_name in (
        ("parseable", "parse_rate"),
        ("format_compliant", "format_compliance_rate"),
        ("action_correct", "action_accuracy"),
        ("parameter_correct", "parameter_accuracy"),
        ("step_correct", "step_accuracy"),
    ):
        result[rate_name] = (
            counts[numerator] / denominator if denominator else None)
    return result

def _record_part_fields(record):
    """Return the canonical identity fields for a complete part trajectory."""
    return {
        "part_key": (
            record.get("source_part_relpath") or record.get("part_id")),
        "part_id": record.get("part_id"),
    }


def _record_subtask_fields(record):
    """Return the canonical fields needed to identify and order a subtask."""
    present_task = record.get("present_task")
    if not isinstance(present_task, dict):
        present_task = {}
    task_progress = record.get("task_progress")
    if not isinstance(task_progress, dict):
        task_progress = {}
    return {
        "part_key": _record_part_fields(record)["part_key"],
        "task_id": (
            present_task.get("task_id") or record.get("task_id")),
        "action_index_in_task": task_progress.get("action_index_in_task"),
        "total_actions_in_task": task_progress.get("total_actions_in_task"),
    }


def build_subtask_contract(records):
    """Validate canonical subtask grouping and ordering for a dataset.

    A subtask is scoped by ``(part_key, task_id)``. ``part_key`` prefers the
    source-relative part path because task IDs restart for every part. This
    function does not inspect predictions; it validates only dataset metadata.
    Invalid metadata disables subtask-level metrics without changing slot-level
    Action/Parameter/Step scoring.
    """
    groups = defaultdict(list)
    index_to_key = {}
    errors = []

    for index, record in enumerate(records):
        present_task = record.get("present_task")
        nested_task_id = (
            present_task.get("task_id")
            if isinstance(present_task, dict) else None)
        top_task_id = record.get("task_id")
        if (
            nested_task_id is not None and top_task_id is not None and
            str(nested_task_id) != str(top_task_id)
        ):
            errors.append(
                "_idx=%d has conflicting nested/top-level task_id (%r/%r)" % (
                    index, nested_task_id, top_task_id))
            continue
        fields = _record_subtask_fields(record)
        missing = [
            name for name, value in fields.items()
            if value is None or value == ""
        ]
        if missing:
            errors.append(
                "_idx=%d missing %s" % (index, ",".join(missing)))
            continue
        action_index = fields["action_index_in_task"]
        total_actions = fields["total_actions_in_task"]
        if (
            isinstance(action_index, bool) or
            not isinstance(action_index, int) or action_index <= 0 or
            isinstance(total_actions, bool) or
            not isinstance(total_actions, int) or total_actions <= 0
        ):
            errors.append(
                "_idx=%d has invalid task progress (%r/%r)" % (
                    index, action_index, total_actions))
            continue
        key = (str(fields["part_key"]), str(fields["task_id"]))
        groups[key].append({
            "_idx": index,
            "action_index_in_task": action_index,
            "total_actions_in_task": total_actions,
        })
        index_to_key[index] = key

    for key, rows in sorted(groups.items()):
        rows.sort(key=lambda item: item["_idx"])
        declared_totals = {
            item["total_actions_in_task"] for item in rows}
        if len(declared_totals) != 1:
            errors.append(
                "subtask %r has inconsistent total_actions_in_task=%r" % (
                    key, sorted(declared_totals)))
            continue
        declared_total = next(iter(declared_totals))
        observed_order = [
            item["action_index_in_task"] for item in rows]
        expected_order = list(range(1, declared_total + 1))
        if len(rows) != declared_total or observed_order != expected_order:
            errors.append(
                "subtask %r expected ordered actions %r but observed %r" % (
                    key, expected_order, observed_order))
        global_indices = [item["_idx"] for item in rows]
        if global_indices != list(range(
                global_indices[0], global_indices[-1] + 1)):
            errors.append(
                "subtask %r is not contiguous in the dataset" % (key,))

    return {
        "valid": not errors,
        "groups": groups,
        "index_to_key": index_to_key,
        "error_count": len(errors),
        "errors_preview": errors[:50],
    }


def build_part_contract(records):
    """Validate canonical part grouping and global trajectory ordering."""
    groups = defaultdict(list)
    index_to_key = {}
    errors = []

    for index, record in enumerate(records):
        fields = _record_part_fields(record)
        part_key = fields["part_key"]
        if part_key is None or part_key == "":
            errors.append("_idx=%d missing part identity" % index)
            continue
        key = str(part_key)
        groups[key].append({
            "_idx": index,
            "part_id": fields["part_id"],
        })
        index_to_key[index] = key

    for key, rows in sorted(groups.items()):
        rows.sort(key=lambda item: item["_idx"])
        global_indices = [item["_idx"] for item in rows]
        if global_indices != list(range(
                global_indices[0], global_indices[-1] + 1)):
            errors.append(
                "part %r is not contiguous in the dataset" % key)

    return {
        "valid": not errors,
        "groups": groups,
        "index_to_key": index_to_key,
        "error_count": len(errors),
        "errors_preview": errors[:50],
    }


def _empty_subtask_metrics():
    return {
        "subtasks_touched": 0,
        "complete_subtasks": 0,
        "partial_subtasks_excluded": 0,
        "successful_subtasks": 0,
        "subtask_exact_match": None,
        "prefix_correct_steps": 0,
        "complete_subtask_steps": 0,
        "subtask_prefix_completion_macro": None,
        "subtask_prefix_step_accuracy": None,
        "subtask_metrics_complete": False,
    }


def _empty_part_metrics():
    return {
        "parts_touched": 0,
        "complete_parts": 0,
        "partial_parts_excluded": 0,
        "successful_parts": 0,
        "part_exact_match": None,
        "step_correct_steps": 0,
        "prefix_correct_steps": 0,
        "complete_part_steps": 0,
        "part_step_accuracy_macro": None,
        "part_step_accuracy_micro": None,
        "part_prefix_completion_macro": None,
        "part_prefix_step_accuracy": None,
        "part_metrics_complete": False,
    }


def _validate_reference(index, record):
    try:
        expected = action_runner.parse_model_output(
            action_runner.assistant_text(record))
    except Exception as exc:
        raise ScoringError(
            "canonical reference _idx=%d cannot be parsed: %s" %
            (index, exc)) from exc
    label = record.get("label_action_type")
    if label is not None and label != expected.action:
        raise ScoringError(
            "canonical reference _idx=%d action label %r != parsed %r" %
            (index, label, expected.action))
    return expected

def _score_subtask_metrics(contract, selected_indices, details):
    """Aggregate per-slot step success into complete subtasks."""
    result = _empty_subtask_metrics()
    result.update({
        "subtask_contract_valid": contract["valid"],
        "subtask_contract_error_count": contract["error_count"],
        "subtask_contract_errors_preview": contract["errors_preview"],
    })
    selected = set(selected_indices)
    detail_by_index = {item["_idx"]: item for item in details}
    complete_groups = []
    partial_groups = []

    for key, rows in contract["groups"].items():
        group_indices = [item["_idx"] for item in rows]
        overlap = selected.intersection(group_indices)
        if not overlap:
            continue
        result["subtasks_touched"] += 1
        if len(overlap) == len(group_indices):
            complete_groups.append((key, rows))
        else:
            partial_groups.append((key, rows))
            for index in overlap:
                detail_by_index[index]["subtask_metric_included"] = False
                detail_by_index[index]["subtask_partial_in_slice"] = True

    result["complete_subtasks"] = len(complete_groups)
    result["partial_subtasks_excluded"] = len(partial_groups)
    result["subtask_metrics_complete"] = (
        contract["valid"] and not partial_groups)

    if not contract["valid"]:
        return result

    macro_prefix_sum = 0.0
    for key, rows in complete_groups:
        flags = [
            bool(detail_by_index[item["_idx"]]["step_success"])
            for item in rows
        ]
        prefix_correct = 0
        for flag in flags:
            if not flag:
                break
            prefix_correct += 1
        successful = all(flags)
        total_steps = len(flags)
        prefix_fraction = (
            prefix_correct / total_steps if total_steps else 0.0)
        result["successful_subtasks"] += int(successful)
        result["prefix_correct_steps"] += prefix_correct
        result["complete_subtask_steps"] += total_steps
        macro_prefix_sum += prefix_fraction

        for item in rows:
            detail = detail_by_index[item["_idx"]]
            detail.update({
                "subtask_metric_included": True,
                "subtask_partial_in_slice": False,
                "subtask_success": successful,
                "subtask_prefix_correct_steps": prefix_correct,
                "subtask_prefix_completion": prefix_fraction,
            })

    denominator = result["complete_subtasks"]
    if denominator:
        result["subtask_exact_match"] = (
            result["successful_subtasks"] / denominator)
        result["subtask_prefix_completion_macro"] = (
            macro_prefix_sum / denominator)
    step_denominator = result["complete_subtask_steps"]
    if step_denominator:
        result["subtask_prefix_step_accuracy"] = (
            result["prefix_correct_steps"] / step_denominator)
    return result


def _score_part_metrics(contract, selected_indices, details):
    """Aggregate per-slot correctness into complete part trajectories."""
    result = _empty_part_metrics()
    result.update({
        "part_contract_valid": contract["valid"],
        "part_contract_error_count": contract["error_count"],
        "part_contract_errors_preview": contract["errors_preview"],
    })
    selected = set(selected_indices)
    detail_by_index = {item["_idx"]: item for item in details}
    complete_groups = []
    partial_groups = []

    for key, rows in contract["groups"].items():
        group_indices = [item["_idx"] for item in rows]
        overlap = selected.intersection(group_indices)
        if not overlap:
            continue
        result["parts_touched"] += 1
        if len(overlap) == len(group_indices):
            complete_groups.append((key, rows))
        else:
            partial_groups.append((key, rows))
            for index in overlap:
                detail_by_index[index]["part_metric_included"] = False
                detail_by_index[index]["part_partial_in_slice"] = True

    result["complete_parts"] = len(complete_groups)
    result["partial_parts_excluded"] = len(partial_groups)
    result["part_metrics_complete"] = (
        contract["valid"] and not partial_groups)

    if not contract["valid"]:
        return result

    macro_step_sum = 0.0
    macro_prefix_sum = 0.0
    for key, rows in complete_groups:
        flags = [
            bool(detail_by_index[item["_idx"]]["step_success"])
            for item in rows
        ]
        correct_steps = sum(flags)
        prefix_correct = 0
        for flag in flags:
            if not flag:
                break
            prefix_correct += 1
        successful = all(flags)
        total_steps = len(flags)
        step_fraction = (
            correct_steps / total_steps if total_steps else 0.0)
        prefix_fraction = (
            prefix_correct / total_steps if total_steps else 0.0)

        result["successful_parts"] += int(successful)
        result["step_correct_steps"] += correct_steps
        result["prefix_correct_steps"] += prefix_correct
        result["complete_part_steps"] += total_steps
        macro_step_sum += step_fraction
        macro_prefix_sum += prefix_fraction

        for item in rows:
            detail = detail_by_index[item["_idx"]]
            detail.update({
                "part_metric_included": True,
                "part_partial_in_slice": False,
                "part_success": successful,
                "part_total_steps": total_steps,
                "part_step_correct_steps": correct_steps,
                "part_step_accuracy": step_fraction,
                "part_prefix_correct_steps": prefix_correct,
                "part_prefix_completion": prefix_fraction,
            })

    part_denominator = result["complete_parts"]
    if part_denominator:
        result["part_exact_match"] = (
            result["successful_parts"] / part_denominator)
        result["part_step_accuracy_macro"] = (
            macro_step_sum / part_denominator)
        result["part_prefix_completion_macro"] = (
            macro_prefix_sum / part_denominator)

    step_denominator = result["complete_part_steps"]
    if step_denominator:
        result["part_step_accuracy_micro"] = (
            result["step_correct_steps"] / step_denominator)
        result["part_prefix_step_accuracy"] = (
            result["prefix_correct_steps"] / step_denominator)
    return result


def score_predictions(dataset_path, prediction_path, start_index=0, limit=0,
                      num_shards=1, shard_index=0):
    """Score a prediction JSONL against a fixed canonical reference slice."""
    dataset_path = Path(dataset_path).resolve()
    prediction_path = Path(prediction_path).resolve()
    records = read_jsonl(dataset_path)
    subtask_contract = build_subtask_contract(records)
    part_contract = build_part_contract(records)
    index_list = reference_indices(
        records,
        start_index=start_index,
        limit=limit,
        num_shards=num_shards,
        shard_index=shard_index,
    )
    predictions = load_prediction_map(prediction_path, index_list)

    overall = _empty_counts()
    by_action = defaultdict(_empty_counts)
    confusion = defaultdict(Counter)
    details = []
    missing_indices = []
    inference_error_slots = 0

    for index in index_list:
        record = records[index]
        task_fields = _record_subtask_fields(record)
        expected = _validate_reference(index, record)
        action_name = expected.action
        overall["slots"] += 1
        by_action[action_name]["slots"] += 1

        prediction_row = predictions.get(index)
        prediction_text = (
            prediction_row.get("prediction")
            if prediction_row is not None else None)
        if prediction_row is None:
            missing_indices.append(index)
            parse_error = "missing_prediction_record"
            generated = None
        else:
            inference_error = prediction_row.get("error")
            if inference_error:
                inference_error_slots += 1
                prediction_text = None
                generated = None
                parse_error = "inference_error: %s" % inference_error
            else:
                parse_error = None
                try:
                    generated = action_runner.parse_model_output(
                        prediction_text)
                except Exception as exc:
                    generated = None
                    parse_error = str(exc)

        comparison = {
            "action_match": False,
            "parameter_match": False,
            "step_success": False,
        }
        pred_action = "<missing>" if prediction_row is None else "<parse_error>"
        if generated is not None:
            overall["parseable"] += 1
            by_action[action_name]["parseable"] += 1
            pred_action = generated.action
            comparison = action_metrics.compare_to_reference(
                generated, expected, record=record,
                screen_size=action_runner.EXPECTED_SCREEN)
        format_compliant = is_format_compliant(prediction_text)
        if format_compliant:
            overall["format_compliant"] += 1
            by_action[action_name]["format_compliant"] += 1

        for key, metric_name in (
            ("action_match", "action_correct"),
            ("parameter_match", "parameter_correct"),
            ("step_success", "step_correct"),
        ):
            if comparison[key]:
                overall[metric_name] += 1
                by_action[action_name][metric_name] += 1
        confusion[action_name][pred_action] += 1
        details.append({
            "_idx": index,
            "part_id": record.get("part_id"),
            "part_key": task_fields["part_key"],
            "task_id": task_fields["task_id"],
            "action_index_in_task": task_fields["action_index_in_task"],
            "total_actions_in_task": task_fields["total_actions_in_task"],
            "gt_action": action_name,
            "pred_action": pred_action,
            "prediction_present": prediction_row is not None,
            "parse_ok": generated is not None,
            "parse_error": parse_error,
            "format_compliant": format_compliant,
            "action_match": comparison["action_match"],
            "parameter_match": comparison["parameter_match"],
            "step_success": comparison["step_success"],
        })

    subtask_metrics = _score_subtask_metrics(
        subtask_contract, index_list, details)
    part_metrics = _score_part_metrics(
        part_contract, index_list, details)
    dataset_hash = dataset_sha256(dataset_path)
    coverage_complete = len(predictions) == len(index_list)
    full_dataset = (
        start_index == 0 and limit == 0 and num_shards == 1 and
        len(index_list) == len(records))
    dataset_contract = identify_dataset_contract(records, dataset_hash)
    dataset_contract_name = (
        dataset_contract["name"] if dataset_contract else None)
    canonical_contract = bool(
        dataset_contract and dataset_contract["canonical_full_test"])
    stratified_test_50_contract = (
        dataset_contract_name == "stratified_test_50_seed42")
    heldout_test_364_contract = (
        dataset_contract_name == "heldout_test_364_seed42_complement")
    registered_benchmark_metrics_valid = (
        coverage_complete and full_dataset and dataset_contract is not None and
        inference_error_slots == 0 and
        subtask_metrics["subtask_metrics_complete"] and
        part_metrics["part_metrics_complete"])
    summary = {
        "protocol": "cad_drawer_evaluation_v1",
        "metric_suite_version": "cad_drawer_l1_metrics_v4",
        "dataset": str(dataset_path),
        "dataset_sha256": dataset_hash,
        "prediction_file": str(prediction_path),
        "dataset_total_slots": len(records),
        "slice_start_index": start_index,
        "slice_end_index_exclusive": (
            index_list[-1] + 1 if index_list else start_index),
        "reference_slots": len(index_list),
        "num_shards": num_shards,
        "shard_index": shard_index,
        "prediction_records": len(predictions),
        "missing_slots": len(missing_indices),
        "missing_indices_preview": missing_indices[:50],
        "inference_error_slots": inference_error_slots,
        "coverage_complete": coverage_complete,
        "evaluation_slice_complete": coverage_complete,
        "registered_dataset_contract": dataset_contract_name,
        "registered_dataset_contract_details": dataset_contract,
        "canonical_test_final_contract": canonical_contract,
        "stratified_test_50_contract": stratified_test_50_contract,
        "heldout_test_364_contract": heldout_test_364_contract,
        "inference_clean": inference_error_slots == 0,
        "registered_benchmark_metrics_valid": (
            registered_benchmark_metrics_valid),
        "official_full_test_metrics_valid": (
            registered_benchmark_metrics_valid and canonical_contract),
        "official_test_50_metrics_valid": (
            registered_benchmark_metrics_valid and
            stratified_test_50_contract),
        "official_test_364_metrics_valid": (
            registered_benchmark_metrics_valid and
            heldout_test_364_contract),
        "metrics": _with_rates(overall),
        "subtask_metrics": subtask_metrics,
        "part_metrics": part_metrics,
        "by_gt_action": {
            name: _with_rates(counts)
            for name, counts in sorted(by_action.items())
        },
        "action_confusion": {
            expected: dict(sorted(predicted.items()))
            for expected, predicted in sorted(confusion.items())
        },
        "definitions": {
            "action_accuracy": "predicted action equals the GT action",
            "parameter_accuracy": (
                "parameters match under the GT action schema; independent "
                "from predicted action correctness"),
            "step_accuracy": (
                "per-slot conjunction of action_match and parameter_match"),
            "subtask_exact_match": (
                "fraction of complete reference subtasks whose every "
                "step is correct"),
            "subtask_prefix_completion_macro": (
                "mean, with equal weight per complete subtask, of the "
                "consecutive correct prefix length divided by task length"),
            "subtask_prefix_step_accuracy": (
                "total consecutive correct prefix slots divided by all slots "
                "in complete subtasks; longer subtasks receive more weight"),
            "subtask_scope": (
                "subtasks are grouped by part identity and task_id; partial "
                "subtasks at a requested slice boundary are excluded and make "
                "subtask_metrics_complete false"),
            "part_step_accuracy_macro": (
                "mean per-part fraction of independently correct reference "
                "steps; every complete part has equal weight"),
            "part_step_accuracy_micro": (
                "total correct steps divided by all steps in complete parts; "
                "equivalent to overall step accuracy on a complete full run"),
            "part_prefix_completion_macro": (
                "mean per-part fraction of consecutive correct steps before "
                "the first failure; every complete part has equal weight"),
            "part_prefix_step_accuracy": (
                "total consecutive correct prefix steps divided by all steps "
                "in complete parts; longer parts receive more weight"),
            "part_exact_match": (
                "fraction of complete reference part trajectories whose "
                "every step is correct"),
            "part_scope": (
                "parts are grouped by source-relative part identity and must "
                "be contiguous; partial parts are excluded"),
            "parse_rate": (
                "canonical FreeCAD action parser accepts the model output"),
            "denominator": (
                "all canonical reference slots in the requested slice; "
                "missing, inference-error, and parse-error slots score zero"),
        },
    }
    return summary, details


def write_json(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(
        path.name + ".tmp.%d" % os.getpid())
    with temporary.open("w", encoding="utf-8") as handle:
        json.dump(value, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temporary, path)


def write_jsonl(path, rows):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False) + "\n")