File size: 50,107 Bytes
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
98fac1e
 
a450c7f
 
 
 
 
 
 
 
 
 
 
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
 
 
 
 
 
 
 
 
 
 
 
 
 
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
98fac1e
 
 
a450c7f
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
 
 
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
 
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
 
 
 
 
98fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a450c7f
 
 
98fac1e
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
#!/usr/bin/env python3
"""Tests for the NativePort Web-Access API Benchmarks dataset package.

Standard library only:

    python3 -m unittest discover -s tests -v

Tests that exercise the generator against the real snapshot look for it at
/tmp/nativeport-evals-current.json, overridable with the NP_EVALS_JSON environment
variable. Determinism and exact-number behaviour are additionally proven against an
embedded fixture, so those properties are covered even without the snapshot at hand.
"""

from __future__ import annotations

import csv
import hashlib
import importlib.util
import json
import os
import re
import tempfile
import unicodedata
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
CSV_PATH = DATA / "benchmarks.csv"
METRIC_ROWS_PATH = DATA / "metric_rows.jsonl"
JSONL_PATH = DATA / "benchmarks.jsonl"
SUMMARY_PATH = DATA / "summary.json"

DATA_FILE_NAMES = ("metric_rows.jsonl", "benchmarks.csv", "benchmarks.jsonl", "summary.json")

# The Hugging Face configs declared in the card's front matter and the file backing
# each. Both must be JSONL: the Hub resolves one packaged loader for the whole
# repository from the declared config data files and applies it to every config, so
# mixing formats parses one config with the other's reader. The CSV backs no config.
HUB_CONFIG_DATA_FILES = {
    "metric_rows": "data/metric_rows.jsonl",
    "evaluations": "data/benchmarks.jsonl",
}
README_PATH = ROOT / "README.md"
LICENSE_PATH = ROOT / "LICENSE"
MAKEFILE_PATH = ROOT / "Makefile"

SOURCE_PATH = Path(os.environ.get("NP_EVALS_JSON", "/tmp/nativeport-evals-current.json"))

BACKLINK = (
    "https://nativeport.ai/methodology/"
    "?utm_source=huggingface&utm_medium=referral"
    "&utm_campaign=backlink_hf_web_access_benchmarks_20260811"
)

# The licence approved for publication. These three values must agree with each other
# and with the LICENSE file; nothing in the package may assert a different licence.
LICENSE_HUB_ID = "cc-by-4.0"          # Hugging Face front-matter identifier
LICENSE_SPDX_ID = "CC-BY-4.0"         # SPDX identifier
LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
LICENSE_LEGALCODE_URL = "https://creativecommons.org/licenses/by/4.0/legalcode"

# SHA-256 of the CC BY 4.0 legal code reduced to its alphanumeric words (see
# normalise_legal_text). Pinning the normalised form makes the assertion insensitive to
# line wrapping, indentation and quote style while still detecting any change of
# wording, however small. The digest was taken from the legal code served by
# https://creativecommons.org/licenses/by/4.0/legalcode.en and independently
# cross-checked against the SPDX license-list text for CC-BY-4.0; the two agree word
# for word apart from list enumerators the CC page renders with CSS counters.
CC_BY_4_0_NORMALISED_SHA256 = (
    "b94bf421a55fe7bc2d698d314ee46b5e22bfcc7afbf93301978a35fd8bddd9ba"
)

# Files that ship to the public Hugging Face repository.
PUBLIC_UPLOAD_SET = (
    "README.md",
    "LICENSE",
    "data/metric_rows.jsonl",
    "data/benchmarks.csv",
    "data/benchmarks.jsonl",
    "data/summary.json",
    "scripts/build_dataset.py",
    "tests/test_dataset.py",
    "Makefile",
)

# Review and tooling documents that stay internal. They may be absent — this suite
# ships with the public set and must pass without them.
INTERNAL_ONLY = ("APPROVAL.md", "VALIDATION.md", "scripts/validate.py")


def normalise_legal_text(text):
    """Reduce legal text to lowercase alphanumeric words separated by single spaces."""
    return " ".join(re.findall(r"[a-z0-9]+", unicodedata.normalize("NFKC", text).lower()))


def load_builder():
    spec = importlib.util.spec_from_file_location(
        "build_dataset", ROOT / "scripts" / "build_dataset.py"
    )
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


build_dataset = load_builder()


def read_csv_rows():
    with CSV_PATH.open(encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle))


def read_jsonl_records():
    with JSONL_PATH.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle]


def read_metric_row_records():
    with METRIC_ROWS_PATH.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle]


def csv_text_of(value):
    """The CSV rendering of one typed tidy value, per the generator's contract."""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, (int, float)):
        return json.dumps(value)
    return value


def read_summary():
    return json.loads(SUMMARY_PATH.read_text(encoding="utf-8"))


def sha256_of(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


# A miniature snapshot exercising the shapes that matter: a trailing-zero float, an
# integer-valued float, a small decimal, a zero, an empty note and a unicode label.
FIXTURE = {
    "schema_version": 1,
    "source": "https://nativeport.ai/evals.json",
    "latest_run": "2026-08-05",
    "verbs": {
        "search": {"label": "Search", "description": "A query in, ranked links out"},
        "extract_ai": {"label": "Extract · AI/schema", "description": "Fields from a page"},
    },
    "providers": {
        "beta": {
            "name": "Beta",
            "group": "Search",
            "category": "Search API",
            "page": "https://nativeport.ai/providers/beta/",
            "evals": [
                {
                    "verb": "search",
                    "label": "Search",
                    "composite": 7.5,
                    "rank": 2,
                    "of": 2,
                    "top": False,
                    "measured": "2026-08-05",
                    "note": "",
                    "metrics": [
                        {"key": "recall_at_10", "label": "Recall@10", "raw": 0.588, "value": "0.59"},
                        {"key": "latency_p50_ms", "label": "Latency p50", "raw": 886.0, "value": "886 ms"},
                        {"key": "error_rate_pct", "label": "Errors", "raw": 0, "value": "0%"},
                    ],
                }
            ],
        },
        "alpha": {
            "name": "Alpha",
            "group": "Search",
            "category": "Search API",
            "page": "https://nativeport.ai/providers/alpha/",
            "evals": [
                {
                    "verb": "search",
                    "label": "Search",
                    "composite": 9.13,
                    "rank": 1,
                    "of": 2,
                    "top": True,
                    "measured": "2026-08-04",
                    "note": "Comma, and \"quotes\" in the note.",
                    "metrics": [
                        {"key": "recall_at_10", "label": "Recall@10", "raw": 0.62, "value": "0.62"},
                        {"key": "latency_p50_ms", "label": "Latency p50", "raw": 815.5, "value": "816 ms"},
                        {
                            "key": "cost_per_useful_usd",
                            "label": "Cost",
                            "raw": 0.000484,
                            "value": "$0.00048 / useful result",
                        },
                        {"key": "error_rate_pct", "label": "Errors", "raw": 0.0, "value": "0%"},
                    ],
                },
                {
                    "verb": "extract_ai",
                    "label": "Extract · AI/schema",
                    "composite": 0.0,
                    "rank": 1,
                    "of": 1,
                    "top": True,
                    "measured": "2026-08-05",
                    "note": "Every extraction failed.",
                    "metrics": [
                        {"key": "field_accuracy", "label": "Field accuracy", "raw": 0.0, "value": "0.00"},
                        {"key": "latency_p50_ms", "label": "Latency p50", "raw": 0.0, "value": "0 ms"},
                        {"key": "error_rate_pct", "label": "Errors", "raw": 100.0, "value": "100%"},
                    ],
                },
            ],
        },
        "unscored": {
            "name": "Unscored",
            "group": "Search",
            "category": "Search API",
            "page": "https://nativeport.ai/providers/unscored/",
            "evals": [],
        },
    },
    "run": {
        "name": "2026-08-05",
        "scored_providers": 2,
        "catalog_providers": 3,
        "scorecards": 3,
        "capabilities": 2,
        "unscored_pairs": [],
    },
}


def write_fixture(directory, document=None):
    path = Path(directory) / "fixture-evals.json"
    path.write_text(
        json.dumps(document if document is not None else FIXTURE, ensure_ascii=False),
        encoding="utf-8",
    )
    return path


class GeneratorDeterminismTest(unittest.TestCase):
    """The generator must be a pure function of its input bytes."""

    def test_two_builds_from_the_fixture_are_byte_identical(self):
        with tempfile.TemporaryDirectory() as workspace:
            source = write_fixture(workspace)
            digests = []
            for run in ("first", "second"):
                out = Path(workspace) / run
                build_dataset.build(source, out)
                digests.append(
                    tuple(
                        sha256_of(out / name)
                        for name in DATA_FILE_NAMES
                    )
                )
            self.assertEqual(digests[0], digests[1])

    def test_outputs_carry_no_wall_clock_timestamp(self):
        with tempfile.TemporaryDirectory() as workspace:
            source = write_fixture(workspace)
            out = Path(workspace) / "out"
            summary = build_dataset.build(source, out)
            blob = json.dumps(summary)
            for field in ("generated_at", "timestamp", "build_time", "created_at"):
                self.assertNotIn(field, blob)

    def test_ordering_is_stable_and_independent_of_source_order(self):
        """Records sort by (capability, rank, provider), not by dict insertion order."""

        def records_without_snapshot_hash(path):
            # Reordering the source changes its bytes, so the snapshot hash legitimately
            # differs; everything else must be identical.
            out = []
            for line in path.read_text(encoding="utf-8").splitlines():
                record = json.loads(line)
                record.pop("snapshot_sha256")
                out.append(record)
            return out

        with tempfile.TemporaryDirectory() as workspace:
            out = Path(workspace) / "out"
            build_dataset.build(write_fixture(workspace), out)
            first = records_without_snapshot_hash(out / "benchmarks.jsonl")

            shuffled = json.loads(json.dumps(FIXTURE))
            shuffled["providers"] = {
                key: shuffled["providers"][key] for key in ("unscored", "alpha", "beta")
            }
            other = Path(workspace) / "shuffled"
            build_dataset.build(write_fixture(other.parent, shuffled), other)
            second = records_without_snapshot_hash(other / "benchmarks.jsonl")

            self.assertEqual(first, second)
            self.assertEqual(
                [record["evaluation_id"] for record in first],
                ["alpha:extract_ai", "alpha:search", "beta:search"],
            )

    @unittest.skipUnless(SOURCE_PATH.exists(), f"snapshot not available at {SOURCE_PATH}")
    def test_committed_artifacts_match_a_fresh_rebuild(self):
        with tempfile.TemporaryDirectory() as workspace:
            out = Path(workspace) / "out"
            build_dataset.build(SOURCE_PATH, out)
            for name in DATA_FILE_NAMES:
                self.assertEqual(
                    sha256_of(out / name),
                    sha256_of(DATA / name),
                    f"{name} differs from a rebuild of the recorded snapshot",
                )


class ExactNumericPreservationTest(unittest.TestCase):
    """Measured values must survive the pipeline character for character."""

    def test_refuses_a_token_it_cannot_reproduce_exactly(self):
        document = json.loads(json.dumps(FIXTURE))
        document["providers"]["alpha"]["evals"][0]["metrics"][0]["raw"] = 1.10
        with tempfile.TemporaryDirectory() as workspace:
            # 1.10 must reach the parser as text, so patch the serialised form directly.
            path = Path(workspace) / "fixture-evals.json"
            blob = json.dumps(document, ensure_ascii=False).replace('"raw": 1.1,', '"raw": 1.10,', 1)
            self.assertIn('"raw": 1.10,', blob)
            path.write_text(blob, encoding="utf-8")
            with self.assertRaises(build_dataset.BuildError) as caught:
                build_dataset.build(path, Path(workspace) / "out")
            self.assertIn("round-trip", str(caught.exception))

    def test_exact_number_keeps_the_source_token(self):
        for token in ("0.938", "886.0", "0.0003", "0.000484", "0", "100.0", "9.13"):
            text, value = build_dataset.exact_number(token, "$.test")
            self.assertEqual(text, token)
            self.assertEqual(json.dumps(value), token)

    @unittest.skipUnless(SOURCE_PATH.exists(), f"snapshot not available at {SOURCE_PATH}")
    def test_every_published_number_equals_its_source_token(self):
        document = json.loads(SOURCE_PATH.read_text(encoding="utf-8"), parse_float=str, parse_int=str)
        expected = {}
        for provider_id, provider in document["providers"].items():
            for entry in provider.get("evals", []):
                key = f"{provider_id}:{entry['verb']}"
                expected[key] = {
                    "composite": entry["composite"],
                    "rank": entry["rank"],
                    "of": entry["of"],
                    "metrics": {m["key"]: m["raw"] for m in entry["metrics"]},
                }
        self.assertTrue(expected)

        seen = set()
        for row in read_csv_rows():
            reference = expected[row["evaluation_id"]]
            self.assertEqual(row["composite_score"], reference["composite"])
            self.assertEqual(row["rank"], reference["rank"])
            self.assertEqual(row["rank_of"], reference["of"])
            self.assertEqual(row["metric_raw"], reference["metrics"][row["metric_key"]])
            seen.add((row["evaluation_id"], row["metric_key"]))
        self.assertEqual(
            len(seen), sum(len(value["metrics"]) for value in expected.values())
        )

        for record in read_jsonl_records():
            reference = expected[record["evaluation_id"]]
            self.assertEqual(json.dumps(record["composite_score"]), reference["composite"])
            self.assertEqual(json.dumps(record["rank"]), reference["rank"])
            self.assertEqual(json.dumps(record["rank_of"]), reference["of"])
            for metric in record["metrics"]:
                self.assertEqual(
                    json.dumps(metric["raw_value"]),
                    reference["metrics"][metric["metric_key"]],
                    f"{record['evaluation_id']}/{metric['metric_key']}",
                )

    def test_display_values_are_not_substituted_for_measurements(self):
        for row in read_csv_rows():
            self.assertNotEqual(row["metric_raw"], "")
            float(row["metric_raw"])  # parses as a number, unlike "816 ms" or "$0.0003 / call"


class SchemaAndCountConsistencyTest(unittest.TestCase):
    def setUp(self):
        self.summary = read_summary()
        self.rows = read_csv_rows()
        self.records = read_jsonl_records()

    def test_csv_header_matches_the_generator_contract(self):
        with CSV_PATH.open(encoding="utf-8", newline="") as handle:
            header = next(csv.reader(handle))
        self.assertEqual(header, build_dataset.TIDY_FIELDS)

    def test_row_counts_agree_across_artifacts(self):
        self.assertEqual(len(self.rows), self.summary["metric_row_count"])
        self.assertEqual(len(read_metric_row_records()), self.summary["metric_row_count"])
        self.assertEqual(len(self.records), self.summary["evaluation_count"])
        self.assertEqual(
            sum(len(record["metrics"]) for record in self.records),
            self.summary["metric_row_count"],
        )
        self.assertEqual(
            len({row["evaluation_id"] for row in self.rows}),
            self.summary["evaluation_count"],
        )

    def test_counts_are_computed_not_asserted(self):
        summary = self.summary
        self.assertEqual(
            summary["provider_count_represented"],
            len({row["provider_id"] for row in self.rows}),
        )
        self.assertEqual(
            summary["capability_count"], len({row["capability_id"] for row in self.rows})
        )
        self.assertEqual(
            summary["provider_count_in_catalog_without_evaluations"],
            summary["provider_count_in_source_catalog"] - summary["provider_count_represented"],
        )
        self.assertTrue(all(summary["cross_check"].values()), summary["cross_check"])

    def test_coverage_is_not_overstated(self):
        """The catalog is larger than the scored set; the dataset must say so."""
        summary = self.summary
        self.assertLess(
            summary["provider_count_represented"], summary["provider_count_in_source_catalog"]
        )
        self.assertGreater(summary["provider_count_in_catalog_without_evaluations"], 0)

    def test_measured_date_range_is_derived_from_the_rows(self):
        dates = sorted({row["measured_date"] for row in self.rows})
        self.assertEqual(self.summary["measured_date_min"], dates[0])
        self.assertEqual(self.summary["measured_date_max"], dates[-1])
        self.assertEqual(self.summary["measured_dates"], dates)
        for value in dates:
            self.assertRegex(value, r"^\d{4}-\d{2}-\d{2}$")

    def test_summary_records_matching_output_hashes(self):
        for name, entry in self.summary["outputs"].items():
            self.assertEqual(entry["sha256"], sha256_of(DATA / name), name)
            self.assertEqual(entry["bytes"], (DATA / name).stat().st_size, name)

    def test_every_csv_row_maps_onto_a_jsonl_record(self):
        nested = {
            record["evaluation_id"]: {m["metric_key"]: m for m in record["metrics"]}
            for record in self.records
        }
        for row in self.rows:
            metric = nested[row["evaluation_id"]][row["metric_key"]]
            self.assertEqual(row["metric_label"], metric["metric_label"])
            self.assertEqual(row["metric_display"], metric["display_value"])
            self.assertEqual(int(row["metric_index"]), metric["metric_index"])

    def test_capability_metric_keys_are_documented_in_the_summary(self):
        for capability in self.summary["capabilities"]:
            observed = {
                row["metric_key"]
                for row in self.rows
                if row["capability_id"] == capability["capability_id"]
            }
            self.assertEqual(observed, set(capability["metric_keys"]))
            self.assertEqual(
                capability["evaluation_count"],
                len(
                    {
                        row["evaluation_id"]
                        for row in self.rows
                        if row["capability_id"] == capability["capability_id"]
                    }
                ),
            )

    def test_excluded_commercial_fields_did_not_leak(self):
        blob = "".join(
            (DATA / name).read_text(encoding="utf-8") for name in DATA_FILE_NAMES
        )
        for field in (
            "pricing_entry",
            "choose_if",
            "avoid_if",
            "latency_note",
            "call_body",
            "call_method",
            "Authorization",
            "sign_up",
        ):
            self.assertNotIn(field, blob, f"{field} leaked into the published data")


class HubConfigFormatTest(unittest.TestCase):
    """Both declared configs must be backed by the same data format.

    The Hub resolves one packaged loader for the whole repository from the declared
    config data files and applies it to every config. A repository that mixes CSV and
    JSONL across configs therefore has one config parsed by the other's reader:
    `load_dataset(..., "evaluations")` failed on the published revision, and the
    datasets-server first-rows call for it failed with it. These tests pin the fix.
    """

    def setUp(self):
        self.front = README_PATH.read_text(encoding="utf-8")
        self.front = self.front[4 : self.front.find("\n---\n", 4)]

    def declared_configs(self):
        """(config_name, path) pairs read from the front matter, in declared order."""
        pairs, config_name = [], None
        for line in self.front.splitlines():
            stripped = line.strip()
            if stripped.startswith("- config_name:"):
                config_name = stripped.split(":", 1)[1].strip()
            elif stripped.startswith("path:"):
                pairs.append((config_name, stripped.split(":", 1)[1].strip()))
        return pairs

    def test_front_matter_declares_the_expected_config_to_file_mapping(self):
        self.assertEqual(dict(self.declared_configs()), HUB_CONFIG_DATA_FILES)
        self.assertEqual(self.declared_configs(), list(HUB_CONFIG_DATA_FILES.items()))

    def test_generator_and_card_agree_on_the_config_mapping(self):
        self.assertEqual(build_dataset.HUB_CONFIG_DATA_FILES, HUB_CONFIG_DATA_FILES)
        self.assertEqual(read_summary()["hub_config_data_files"], HUB_CONFIG_DATA_FILES)

    def test_every_config_data_file_is_jsonl(self):
        """The regression itself: one format across all declared configs."""
        suffixes = {Path(path).suffix for _, path in self.declared_configs()}
        self.assertEqual(suffixes, {".jsonl"}, f"configs mix formats: {suffixes}")
        for _, relative in self.declared_configs():
            self.assertTrue((ROOT / relative).is_file(), relative)

    def test_no_config_points_at_the_csv(self):
        for _, relative in self.declared_configs():
            self.assertNotEqual(relative, "data/benchmarks.csv")
        self.assertEqual(
            read_summary()["downloadable_only_artifacts"], ["data/benchmarks.csv"]
        )

    def test_every_config_data_file_parses_as_json_lines(self):
        """Not just the extension: every line of every config file is one JSON object."""
        for config_name, relative in self.declared_configs():
            path = ROOT / relative
            with path.open(encoding="utf-8") as handle:
                lines = handle.read().splitlines()
            self.assertTrue(lines, relative)
            for number, line in enumerate(lines, start=1):
                try:
                    record = json.loads(line)
                except json.JSONDecodeError as exc:
                    self.fail(f"{config_name} ({relative}) line {number}: {exc}")
                self.assertIsInstance(record, dict, f"{relative} line {number}")

    def test_config_records_are_uniform_in_fields_and_types(self):
        """One type per field across every record.

        The loader infers one Arrow column type per field from the records it reads. A
        field that is an integer on one line and a float or a string on another is the
        other common way a config loads locally but fails the viewer's first-rows call.
        """
        for config_name, relative in self.declared_configs():
            lines = (ROOT / relative).read_text(encoding="utf-8").splitlines()
            records = [json.loads(line) for line in lines]
            types = {}
            for index, record in enumerate(records):
                self.assertEqual(
                    list(record),
                    list(records[0]),
                    f"{config_name} record {index}: field set or order differs",
                )
                for field, value in record.items():
                    types.setdefault(field, set()).add(type(value).__name__)
            mixed = {field: sorted(seen) for field, seen in types.items() if len(seen) > 1}
            self.assertEqual(mixed, {}, f"{config_name}: fields change type between records")

    def test_csv_is_still_published_as_a_downloadable_artifact(self):
        self.assertTrue(CSV_PATH.is_file())
        self.assertIn("benchmarks.csv", read_summary()["outputs"])
        self.assertIn("data/benchmarks.csv", PUBLIC_UPLOAD_SET)
        readme = " ".join(README_PATH.read_text(encoding="utf-8").split())
        self.assertIn("`data/benchmarks.csv` is a download rather than a config", readme)
        self.assertIn("| `data/benchmarks.csv` | 297 |", readme)


class TidyMirrorEquivalenceTest(unittest.TestCase):
    """data/benchmarks.csv and data/metric_rows.jsonl are the same tidy rows.

    The CSV is the approved artifact; the JSONL is what the `metric_rows` config loads.
    They are written from one row builder, and these tests hold them to that: same
    fields in the same order, same count, same order of rows, and every value equal —
    numbers compared as text, so a rounded or reformatted measurement fails here.
    """

    def setUp(self):
        self.rows = read_csv_rows()
        self.records = read_metric_row_records()

    def test_both_tidy_views_carry_the_same_row_count(self):
        summary = read_summary()
        self.assertEqual(len(self.rows), summary["metric_row_count"])
        self.assertEqual(len(self.records), summary["metric_row_count"])
        self.assertEqual(len(self.rows), len(self.records))

    def test_field_names_and_order_are_identical(self):
        with CSV_PATH.open(encoding="utf-8", newline="") as handle:
            header = next(csv.reader(handle))
        self.assertEqual(header, build_dataset.TIDY_FIELDS)
        for index, record in enumerate(self.records):
            self.assertEqual(list(record), build_dataset.TIDY_FIELDS, f"record {index}")

    def test_rows_are_semantically_identical_in_the_same_order(self):
        for index, (row, record) in enumerate(zip(self.rows, self.records)):
            self.assertEqual(
                (record["evaluation_id"], record["metric_key"]),
                (row["evaluation_id"], row["metric_key"]),
                f"row {index}: the two tidy views are ordered differently",
            )
            for field in build_dataset.TIDY_FIELDS:
                self.assertEqual(
                    csv_text_of(record[field]),
                    row[field],
                    f"row {index} field {field}",
                )

    def test_numbers_are_preserved_exactly_not_reformatted(self):
        """Every numeric field is a JSON number whose text is the CSV token verbatim."""
        numeric = ("metric_raw", "composite_score", "metric_index", "rank", "rank_of",
                   "composite_scale_max")
        compared = 0
        for row, record in zip(self.rows, self.records):
            for field in numeric:
                value = record[field]
                self.assertIsInstance(value, (int, float), field)
                self.assertNotIsInstance(value, bool, field)
                self.assertEqual(json.dumps(value), row[field], f"{field} in {row['evaluation_id']}")
                compared += 1
            self.assertIsInstance(record["is_capability_top"], bool)
            self.assertEqual(csv_text_of(record["is_capability_top"]), row["is_capability_top"])
        self.assertEqual(compared, len(self.rows) * len(numeric))

    def test_tidy_jsonl_agrees_with_the_nested_evaluations(self):
        """The third view must carry the same measurements as the other two."""
        nested = {
            record["evaluation_id"]: {m["metric_key"]: m for m in record["metrics"]}
            for record in read_jsonl_records()
        }
        seen = set()
        for record in self.records:
            metric = nested[record["evaluation_id"]][record["metric_key"]]
            self.assertEqual(json.dumps(record["metric_raw"]), json.dumps(metric["raw_value"]))
            self.assertEqual(record["metric_display"], metric["display_value"])
            self.assertEqual(record["metric_label"], metric["metric_label"])
            self.assertEqual(record["metric_index"], metric["metric_index"])
            seen.add((record["evaluation_id"], record["metric_key"]))
        self.assertEqual(len(seen), len(self.records))
        self.assertEqual(
            len(seen), sum(len(metrics) for metrics in nested.values())
        )

    def test_generator_emits_both_tidy_views_from_one_builder(self):
        """A fixture build: change nothing, and the two files still agree row for row."""
        with tempfile.TemporaryDirectory() as workspace:
            out = Path(workspace) / "out"
            build_dataset.build(write_fixture(workspace), out)
            with (out / "benchmarks.csv").open(encoding="utf-8", newline="") as handle:
                rows = list(csv.DictReader(handle))
            records = [
                json.loads(line)
                for line in (out / "metric_rows.jsonl").read_text(encoding="utf-8").splitlines()
            ]
            self.assertEqual(len(rows), len(records))
            self.assertEqual(len(rows), 10)  # 3 + 4 + 3 metrics in the fixture
            for row, record in zip(rows, records):
                self.assertEqual(list(record), build_dataset.TIDY_FIELDS)
                for field in build_dataset.TIDY_FIELDS:
                    self.assertEqual(csv_text_of(record[field]), row[field], field)


class RankingIntegrityTest(unittest.TestCase):
    def setUp(self):
        self.records = read_jsonl_records()

    def test_rank_is_within_bounds(self):
        for record in self.records:
            self.assertGreaterEqual(record["rank"], 1, record["evaluation_id"])
            self.assertLessEqual(record["rank"], record["rank_of"], record["evaluation_id"])

    def test_top_flag_agrees_with_rank(self):
        for record in self.records:
            self.assertEqual(
                record["is_capability_top"], record["rank"] == 1, record["evaluation_id"]
            )

    def test_composite_is_inside_the_declared_scale(self):
        for record in self.records:
            self.assertEqual(record["composite_scale_max"], 10)
            self.assertGreaterEqual(record["composite_score"], 0, record["evaluation_id"])
            self.assertLessEqual(record["composite_score"], 10, record["evaluation_id"])

    def test_ranks_are_unique_and_complete_within_each_capability(self):
        by_capability = {}
        for record in self.records:
            by_capability.setdefault(record["capability_id"], []).append(record)
        for capability_id, group in by_capability.items():
            ranks = sorted(record["rank"] for record in group)
            self.assertEqual(ranks, list(range(1, len(group) + 1)), capability_id)
            self.assertEqual(
                {record["rank_of"] for record in group}, {len(group)}, capability_id
            )

    def test_no_duplicate_evaluation_keys(self):
        keys = [record["evaluation_id"] for record in self.records]
        self.assertEqual(len(keys), len(set(keys)))
        pairs = [(record["provider_id"], record["capability_id"]) for record in self.records]
        self.assertEqual(len(pairs), len(set(pairs)))
        for record in self.records:
            self.assertEqual(
                record["evaluation_id"],
                f"{record['provider_id']}:{record['capability_id']}",
            )

    def test_metric_keys_are_unique_within_an_evaluation(self):
        for record in self.records:
            keys = [metric["metric_key"] for metric in record["metrics"]]
            self.assertEqual(len(keys), len(set(keys)), record["evaluation_id"])
            self.assertEqual(
                [metric["metric_index"] for metric in record["metrics"]],
                list(range(len(keys))),
                record["evaluation_id"],
            )


class UrlPolicyTest(unittest.TestCase):
    URL_FIELDS = ("provider_page_url", "source_url")

    def test_data_urls_are_https(self):
        for row in read_csv_rows() + read_metric_row_records() + read_jsonl_records():
            for field in self.URL_FIELDS:
                self.assertTrue(row[field].startswith("https://"), f"{field}={row[field]}")

    def test_summary_urls_are_https(self):
        summary = read_summary()
        for field in ("source_url", "methodology_url", "leaderboards_url"):
            self.assertTrue(summary[field].startswith("https://"), field)

    def test_no_plain_http_anywhere_in_the_package(self):
        offenders = []
        for path in sorted(ROOT.rglob("*")):
            if not path.is_file() or "__pycache__" in path.parts:
                continue
            try:
                text = path.read_text(encoding="utf-8")
            except (UnicodeDecodeError, OSError):
                continue
            # self-avoiding pattern: matches "http://" but not this line
            offenders.extend(
                f"{path.relative_to(ROOT)}: {hit}"
                for hit in re.findall(r"htt[p]://[^\s\"'<>)\]]+", text)
            )
        self.assertEqual(offenders, [])

    def test_data_files_carry_no_campaign_tagged_urls(self):
        for name in DATA_FILE_NAMES:
            self.assertNotIn("utm_", (DATA / name).read_text(encoding="utf-8"), name)


class ReadmeCardTest(unittest.TestCase):
    def setUp(self):
        self.text = README_PATH.read_text(encoding="utf-8")

    def front_matter(self):
        return self.text[4 : self.text.find("\n---\n", 4)]

    def section(self, heading):
        """Body of one `## ` section, up to the next one."""
        start = self.text.index(heading) + len(heading)
        rest = self.text[start:]
        end = rest.find("\n## ")
        return rest if end == -1 else rest[:end]

    def flat(self, heading):
        """Section body with all runs of whitespace collapsed, so prose assertions do
        not depend on where the source happens to wrap."""
        return " ".join(self.section(heading).split())

    def test_front_matter_is_well_formed(self):
        self.assertTrue(self.text.startswith("---\n"))
        end = self.text.find("\n---\n", 4)
        self.assertNotEqual(end, -1, "front matter is not closed")
        front = self.text[4:end]
        self.assertNotIn("\t", front)
        top_keys = [
            line.split(":", 1)[0]
            for line in front.splitlines()
            if line and not line.startswith((" ", "-", "#"))
        ]
        self.assertEqual(
            top_keys,
            ["license", "pretty_name", "language", "tags", "size_categories", "configs"],
        )
        for line in front.splitlines():
            if line and not line.startswith((" ", "-")):
                self.assertIn(":", line, line)

    def test_title_and_pretty_name_match(self):
        self.assertIn("pretty_name: NativePort Web-Access API Benchmarks", self.text)
        self.assertIn("\n# NativePort Web-Access API Benchmarks\n", self.text)

    def test_front_matter_declares_the_approved_licence(self):
        """Exactly one licence key, carrying exactly the approved identifier."""
        front = self.front_matter()
        license_lines = [line for line in front.splitlines() if line.startswith("license")]
        self.assertEqual(license_lines, [f"license: {LICENSE_HUB_ID}"])
        # license_name / license_link belong to `license: other`; they must not appear.
        for key in ("license_name", "license_link", "license_details"):
            self.assertNotIn(key, front, key)
        for competing in (
            "cc-by-nc",
            "cc-by-sa",
            "cc-by-nd",
            "cc0-1.0",
            "odc-by",
            "odbl",
            "apache-2.0",
            "unlicense",
            "all-rights-reserved",
        ):
            self.assertNotIn(competing, front, competing)

    def test_licensing_section_names_cc_by_4_0_and_the_canonical_urls(self):
        section = self.flat("## Licensing")
        self.assertIn("Creative Commons Attribution 4.0 International", section)
        self.assertIn("CC BY 4.0", section)
        self.assertIn(LICENSE_URL, section)
        self.assertIn(LICENSE_LEGALCODE_URL, section)
        self.assertIn(LICENSE_SPDX_ID, section)
        self.assertIn("[`LICENSE`](LICENSE)", section)
        self.assertIn(f"license: {LICENSE_HUB_ID}", section)

    def test_licensing_section_no_longer_defers_the_decision(self):
        section = self.flat("## Licensing")
        for stale in (
            "not been finalised",
            "not finalised",
            "all-rights-reserved",
            "no open-data licence is asserted",
            "seek permission before redistribution",
            "Until a licence is published",
        ):
            self.assertNotIn(stale, section, stale)

    def test_licensing_section_scopes_the_grant_to_what_nativeport_can_license(self):
        section = self.flat("## Licensing")
        for phrase in (
            "NativePort licenses what it is in a position to license",
            "this dataset as a compilation",
            "the benchmark measurements NativePort itself produced",
            "The grant extends only to those rights and only to the extent NativePort holds them.",
        ):
            self.assertIn(phrase, section, phrase)

    def test_licensing_section_does_not_overstate_trademark_rights(self):
        """The licence covers NativePort's compilation, never third-party marks."""
        section = self.flat("## Licensing")
        lowered = section.lower()
        for overstatement in (
            "trademarks are licensed",
            "trademark rights are licensed",
            "licenses the trademarks",
            "licences the trademarks",
            "grants you the trademarks",
            "grant of trademark",
            "including any trademarks",
            "trademark licence is granted",
            "trademark license is granted",
        ):
            self.assertNotIn(overstatement, lowered, overstatement)

        # Every sentence that touches marks must withhold rather than grant: it carries
        # a negation, or it attributes the marks to their owners.
        denials = ("not ", "no ", "nor ", "never ", "remain the property", "outside what")
        sentences = [
            sentence
            for sentence in re.split(r"(?<=[.;])\s+", lowered)
            if "trademark" in sentence or " marks" in sentence
        ]
        self.assertTrue(sentences, "the licensing section must address trademarks")
        for sentence in sentences:
            self.assertTrue(
                any(denial in sentence for denial in denials),
                f"trademark sentence does not withhold a grant: {sentence}",
            )

    def test_licensing_section_states_attribution_and_warranty_terms(self):
        section = self.flat("## Licensing")
        for phrase in (
            "Credit *NativePort*",
            "state that the material is under CC BY 4.0 with a link to the licence",
            "indicate whether you modified it",
            "as-is and as-available, without warranties or conditions of any kind",
        ):
            self.assertIn(phrase, section, phrase)

    def test_trademark_notice_denies_any_licence_grant_in_marks(self):
        section = self.flat("## Trademark notice")
        self.assertIn(
            "The CC BY 4.0 licence described under [Licensing](#licensing) grants "
            "**no** rights in any of these marks",
            section,
        )

    def test_declared_data_files_exist(self):
        front = self.front_matter()
        for relative in re.findall(r"path:\s*(\S+)", front):
            self.assertTrue((ROOT / relative).is_file(), relative)

    def test_backlink_is_exact_and_appears_once(self):
        self.assertEqual(self.text.count(BACKLINK), 1)
        self.assertEqual(len(re.findall(r"utm_source=", self.text)), 1)
        self.assertEqual(len(re.findall(r"utm_campaign=", self.text)), 1)
        self.assertIn(
            f"[How we measure]({BACKLINK})",
            self.text.replace("\n", " ").replace("  ", " "),
        )

    def test_backlink_is_contextual_not_the_point_of_the_page(self):
        """The card must stand on its own: the link sits inside the methodology prose."""
        index = self.text.index(BACKLINK)
        self.assertGreater(index, len(self.text) // 3, "backlink appears too early to be contextual")
        self.assertIn("## Methodology", self.text[:index])

    def test_required_sections_exist(self):
        for heading in (
            "## Disclosure",
            "## Dataset structure",
            "## Usage",
            "## Methodology",
            "## Provenance and reproducibility",
            "## Limitations and scope",
            "## Update policy",
            "## Licensing",
            "## Trademark notice",
            "## Citation",
        ):
            self.assertIn(heading, self.text, heading)

    def test_first_party_disclosure_is_explicit(self):
        for phrase in (
            "produced by **NativePort**",
            "own first-party benchmark",
            "not an independent third-party evaluation",
        ):
            self.assertIn(phrase, self.text, phrase)

    def test_limitations_cover_the_known_risks(self):
        section = self.text[self.text.index("## Limitations and scope") :]
        section = section[: section.index("## Update policy")]
        for phrase in (
            "Coverage is partial",
            "Composites are capability-local",
            "Single point in time",
            "First-party measurement",
            "uptime",
        ):
            self.assertIn(phrase, section, phrase)

    def test_card_does_not_claim_the_whole_catalog_is_benchmarked(self):
        summary = read_summary()
        represented = summary["provider_count_represented"]
        catalog = summary["provider_count_in_source_catalog"]
        self.assertIn(f"**{represented} commercial web-access", self.text)
        self.assertIn(f"{represented} of the {catalog} providers in the source catalog", self.text)

    def test_headline_counts_match_the_generated_summary(self):
        summary = read_summary()
        self.assertIn(f"**{summary['evaluation_count']} provider × capability", self.text)
        self.assertIn(f"**{summary['capability_count']} capabilities**", self.text)
        self.assertIn(f"**{summary['metric_row_count']} metric rows**", self.text)
        self.assertIn(summary["snapshot_sha256"], self.text)
        self.assertIn(summary["latest_run"], self.text)

    def test_capability_comparison_caveat_is_present(self):
        self.assertIn("Latency and cost are not comparable across capabilities", self.text)
        self.assertIn("averaging a provider's composites across capabilities", self.text)

    def test_trademark_notice_disclaims_endorsement(self):
        section = self.text[self.text.index("## Trademark notice") :]
        for phrase in ("trademarks of their respective owners", "does not\nimply any affiliation"):
            self.assertIn(phrase, section, phrase)


class LicenseFileTest(unittest.TestCase):
    """LICENSE must be the complete, unmodified CC BY 4.0 legal code."""

    def setUp(self):
        self.assertTrue(LICENSE_PATH.is_file(), "LICENSE is missing from the package")
        self.raw = LICENSE_PATH.read_bytes()
        self.text = self.raw.decode("utf-8")
        self.normalised = normalise_legal_text(self.text)

    def test_license_file_is_plain_unix_utf8_text(self):
        self.assertNotIn(b"\r", self.raw, "LICENSE must use unix line endings")
        self.assertTrue(self.raw.endswith(b"\n"), "LICENSE must end with a newline")
        self.assertNotIn("\t", self.text, "LICENSE must not contain tab characters")
        self.assertGreater(
            len(self.raw), 16000, "LICENSE is too short to be the full legal code"
        )

    def test_license_text_is_the_canonical_cc_by_4_0_legal_code(self):
        digest = hashlib.sha256(self.normalised.encode("utf-8")).hexdigest()
        self.assertEqual(
            digest,
            CC_BY_4_0_NORMALISED_SHA256,
            "LICENSE wording differs from the canonical CC BY 4.0 legal code",
        )

    def test_license_carries_every_section_of_the_legal_code(self):
        self.assertIn(
            "creative commons attribution 4 0 international public license", self.normalised
        )
        for number, title in (
            (1, "definitions"),
            (2, "scope"),
            (3, "license conditions"),
            (4, "sui generis database rights"),
            (5, "disclaimer of warranties and limitation of liability"),
            (6, "term and termination"),
            (7, "other terms and conditions"),
            (8, "interpretation"),
        ):
            self.assertIn(f"section {number} {title}", self.normalised, title)
        self.assertTrue(
            self.text.rstrip().endswith("Creative Commons may be contacted at creativecommons.org."),
            "LICENSE is truncated before the closing paragraph",
        )

    def test_license_keeps_the_clauses_the_card_relies_on(self):
        for clause in (
            "worldwide royalty free non sublicensable non exclusive irrevocable license",
            "reproduce and share the licensed material in whole or in part",
            "produce reproduce and share adapted material",
            "patent and trademark rights are not licensed under this public license",
            "extract reuse reproduce and share all or a substantial portion of the "
            "contents of the database",
            "as is and as available",
        ):
            self.assertIn(clause, self.normalised, clause)

    def test_license_is_not_a_different_creative_commons_flavour(self):
        for wrong in (
            "noncommercial",
            "non commercial",
            "sharealike",
            "share alike",
            "noderivatives",
            "no derivatives",
            "cc0",
        ):
            self.assertNotIn(wrong, self.normalised, wrong)

    def test_license_agrees_with_the_identifier_declared_in_the_card(self):
        readme = README_PATH.read_text(encoding="utf-8")
        front = readme[4 : readme.find("\n---\n", 4)]
        self.assertIn(f"license: {LICENSE_HUB_ID}", front)
        self.assertIn("Creative Commons Attribution 4.0 International", self.text)


class PublicUploadSetTest(unittest.TestCase):
    """The approved upload set must be complete and self-sufficient.

    APPROVAL.md, VALIDATION.md and scripts/validate.py are internal review and tooling
    documents that do not ship, so nothing in the public set may depend on them.
    """

    def test_every_public_file_is_present(self):
        for relative in PUBLIC_UPLOAD_SET:
            self.assertTrue((ROOT / relative).is_file(), f"{relative} is missing")

    def test_card_does_not_point_at_internal_documents(self):
        readme = README_PATH.read_text(encoding="utf-8")
        for relative in INTERNAL_ONLY:
            self.assertNotIn(Path(relative).name, readme, relative)

    def test_makefile_tolerates_the_internal_validator_being_absent(self):
        makefile = MAKEFILE_PATH.read_text(encoding="utf-8")
        self.assertIn("scripts/build_dataset.py", makefile)
        self.assertIn(
            "if [ -f scripts/validate.py ]",
            makefile,
            "make validate must degrade gracefully when the internal validator does not ship",
        )
        self.assertIn("LICENSE", makefile, "make hashes must cover LICENSE")

    def test_make_hashes_covers_every_data_file(self):
        makefile = MAKEFILE_PATH.read_text(encoding="utf-8")
        for name in DATA_FILE_NAMES:
            self.assertIn(name, makefile, f"make hashes must cover {name}")


class NoSecretsOrStandInsTest(unittest.TestCase):
    """Patterns are written self-avoidingly so this file can be scanned by its own rules."""

    PATTERNS = [
        ("openai-style key", r"sk-[A-Za-z0-9]{16,}"),
        ("aws access key id", r"AKIA[0-9A-Z]{16}"),
        ("github token", r"gh[pousr]_[A-Za-z0-9]{20,}"),
        ("hugging face token", r"hf_[A-Za-z0-9]{20,}"),
        ("private key block", r"BEGIN [A-Z ]*PRIVATE KEY"),
        ("bearer credential", r"(?i)bearer\s+[A-Za-z0-9._\-]{16,}"),
        (
            "assigned credential",
            r"(?i)(api[_-]?key|secret|passwd|password|access[_-]?token)"
            r"\s*[:=]\s*[\"']?[A-Za-z0-9._\-]{12,}",
        ),
        ("unfinished-work marker", r"\bT[O]DO\b"),
        ("unfinished-work marker", r"\bFIX[M]E\b"),
        ("unfinished-work marker", r"\bX[X]X\b"),
        ("unresolved stand-in", r"\bT[B]D\b"),
        ("unresolved stand-in", r"CHANGE[M]E"),
        ("unresolved stand-in", r"(?i)\bplace[h]older\b"),
        ("template slot", r"<YOUR[_ ]"),
    ]

    def test_package_is_free_of_credentials_and_stand_ins(self):
        hits = []
        scanned = 0
        for path in sorted(ROOT.rglob("*")):
            if not path.is_file() or "__pycache__" in path.parts:
                continue
            try:
                text = path.read_text(encoding="utf-8")
            except (UnicodeDecodeError, OSError):
                continue
            scanned += 1
            for label, pattern in self.PATTERNS:
                for match in re.findall(pattern, text):
                    hits.append(f"{path.relative_to(ROOT)}: {label}: {str(match)[:40]}")
        self.assertGreater(scanned, 0)
        self.assertEqual(hits, [])

    def test_no_environment_or_key_material_is_referenced_in_the_data(self):
        blob = "".join(
            (DATA / name).read_text(encoding="utf-8") for name in DATA_FILE_NAMES
        )
        for needle in ("Bearer", "api.nativeport.ai", "accounts.nativeport.ai", "panel."):
            self.assertNotIn(needle, blob, needle)


if __name__ == "__main__":
    unittest.main(verbosity=2)