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
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
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
#!/usr/bin/env python3
"""Evaluate a SentenceTransformers retriever on Quarry.

This reuses the localizer dev-eval representation: child and parent-summary texts are
encoded independently, then each corpus vector is
``normalize(alpha * child + (1 - alpha) * parent)``.
"""
from __future__ import annotations

import argparse
from collections import defaultdict
from contextlib import nullcontext
from dataclasses import dataclass, replace
import gc
import hashlib
import json
import multiprocessing as mp
import os
from pathlib import Path
from queue import Empty
import shutil
import sqlite3
import sys
import time
from typing import Iterable

import numpy as np

HARNESS_ROOT = Path(__file__).resolve().parent / "harness"
if str(HARNESS_ROOT) not in sys.path:
    sys.path.insert(0, str(HARNESS_ROOT))

from localize_sft_core import (  # noqa: E402
    swerank_document_text as swerank_document_text,
    swerank_method_parent as swerank_method_parent,
)

from eval_nano_local import (  # noqa: E402
    bucketed_encode,
    collect_components,
    compose_parent_matrix,
)

PATCHPOINT_RETRIEVAL_INSTRUCTION = (
    "Given a github issue, identify the code that needs to be changed to fix the issue."
)
BGE_CODE_TOKENIZER_CONTRACT = "bge-code-eos-fix-v1"


@dataclass(frozen=True)
class QueryWork:
    repo: str
    revision: str
    task_id: str
    query_id: str
    query: str
    language: str
    gold_chunks: frozenset[int]
    gold_files: frozenset[str]


@dataclass(frozen=True)
class DocumentVectors:
    """One logical document matrix backed by a base cache and optional appended rows."""

    base: np.ndarray
    overlay: np.ndarray | None = None

    @property
    def shape(self) -> tuple[int, int]:
        overlay_rows = 0 if self.overlay is None else int(self.overlay.shape[0])
        return int(self.base.shape[0]) + overlay_rows, int(self.base.shape[1])

    def take(self, rows: np.ndarray) -> np.ndarray:
        if self.overlay is None:
            return self.base[rows]
        base_rows = int(self.base.shape[0])
        output = np.empty((len(rows), self.shape[1]), dtype=np.float32)
        from_base = rows < base_rows
        if np.any(from_base):
            output[from_base] = self.base[rows[from_base]]
        if np.any(~from_base):
            output[~from_base] = self.overlay[rows[~from_base] - base_rows]
        return output


def read_jsonl(path: Path) -> list[dict]:
    with path.open(encoding="utf-8") as handle:
        return [json.loads(line) for line in handle if line.strip()]


def row_key(row: dict) -> tuple[str, str, str]:
    return str(row["repo"]), str(row["task_id"]), str(row["query_id"])


def validate_cuda_runtime(devices: list[str], expected_gpu_uuid: str | None) -> None:
    cuda_devices = [device for device in devices if device.startswith("cuda")]
    if not cuda_devices:
        return
    import torch

    if not torch.cuda.is_available():
        raise RuntimeError("CUDA devices were requested but torch cannot access the NVIDIA driver")
    expected_uuids = (
        [value.strip() for value in expected_gpu_uuid.split(",") if value.strip()]
        if expected_gpu_uuid
        else []
    )
    if expected_uuids and len(expected_uuids) != len(cuda_devices):
        raise RuntimeError(
            f"expected {len(cuda_devices)} GPU UUIDs for {cuda_devices}, got {expected_uuids}"
        )
    visible: list[dict[str, object]] = []
    for position, device in enumerate(cuda_devices):
        index = int(device.partition(":")[2] or 0)
        if index >= torch.cuda.device_count():
            raise RuntimeError(
                f"requested {device}, but only {torch.cuda.device_count()} CUDA devices are visible"
            )
        properties = torch.cuda.get_device_properties(index)
        actual_uuid = f"GPU-{properties.uuid}"
        visible.append(
            {
                "device": device,
                "name": properties.name,
                "uuid": actual_uuid,
                "memory_bytes": properties.total_memory,
            }
        )
        expected_uuid = expected_uuids[position] if expected_uuids else None
        if expected_uuid and actual_uuid.lower() != expected_uuid.lower():
            raise RuntimeError(
                f"{device} maps to {actual_uuid}, expected UUID {expected_uuid}"
            )
    print(json.dumps({"event": "cuda_preflight", "visible": visible}), flush=True)


def _model_loading_encode_worker(
    device: str,
    model_path: str,
    max_seq_length: int,
    model_profile: str,
    hf_instruct_family: str | None,
    truncate_dim: int | None,
    input_queue,
    output_queue,
    ready_queue,
) -> None:
    from sentence_transformers import SentenceTransformer

    try:
        model, event, _query_prompt, _document_prompt = _load_pool_worker_model(
            device,
            model_path,
            max_seq_length,
            model_profile,
            hf_instruct_family,
            truncate_dim,
        )
    except BaseException as exc:
        ready_queue.put(
            {
                "event": "pool_worker_error",
                "device": device,
                "error_type": exc.__class__.__name__,
                "error": str(exc),
            }
        )
        raise
    ready_queue.put(event)
    encode_worker = getattr(SentenceTransformer, "_encode_multi_process_worker", None)
    if encode_worker is None:
        encode_worker = getattr(SentenceTransformer, "_multi_process_worker")
    encode_worker(device, model, input_queue, output_queue)


def start_model_loading_pool(
    model_path: str,
    max_seq_length: int,
    devices: list[str],
    model_profile: str,
    hf_instruct_family: str | None,
    truncate_dim: int | None,
    expected_query_prompt: str | None,
    expected_document_prompt: str | None,
) -> dict:
    context = mp.get_context("spawn")
    input_queue = context.Queue()
    output_queue = context.Queue()
    ready_queue = context.Queue()
    processes = []
    for device in devices:
        process = context.Process(
            target=_model_loading_encode_worker,
            args=(
                device,
                model_path,
                max_seq_length,
                model_profile,
                hf_instruct_family,
                truncate_dim,
                input_queue,
                output_queue,
                ready_queue,
            ),
            daemon=True,
        )
        process.start()
        processes.append(process)
        try:
            event = ready_queue.get(timeout=300)
        except Empty as exc:
            for running in processes:
                running.terminate()
            raise RuntimeError(f"model worker on {device} did not report ready") from exc
        try:
            validate_pool_worker_profile_event(
                event,
                expected_device=device,
                expected_query_prompt=expected_query_prompt,
                expected_document_prompt=expected_document_prompt,
            )
        except Exception:
            for running in processes:
                running.terminate()
            raise
        print(json.dumps(event), flush=True)
        print(json.dumps({"event": "model_worker_ready", "device": device}), flush=True)
    return {"input": input_queue, "output": output_queue, "processes": processes}


def resolve_gold_chunks(
    db_dir: Path, query_rows: list[dict], gold_rows: list[dict], tasks: list[dict]
) -> tuple[list[QueryWork], dict]:
    if [row_key(row) for row in query_rows] != [row_key(row) for row in gold_rows]:
        raise ValueError("queries and preimage gold rows are not exactly aligned")
    language_by_task = {str(row["task_id"]): str(row["language"]) for row in tasks}
    pairs_by_repo: dict[str, list[tuple[str, dict, dict]]] = defaultdict(list)
    for query, gold in zip(query_rows, gold_rows, strict=True):
        if str(query["revision"]) != str(gold["revision"]):
            raise ValueError(f"revision mismatch for {row_key(query)}")
        pairs_by_repo[str(query["repo"])].append((str(query["revision"]), query, gold))

    resolved: list[QueryWork] = []
    canonical_units = 0
    for repo, pairs in sorted(pairs_by_repo.items()):
        db_path = db_dir / repo / "embeddings.db"
        if not db_path.is_file():
            raise FileNotFoundError(f"missing PatchPoint DB: {db_path}")
        connection = sqlite3.connect(db_path)
        try:
            requested_ids = sorted(
                {
                    int(chunk_id)
                    for _revision, _query, gold in pairs
                    for chunk_id in gold.get("positive_chunk_ids", [])
                }
            )
            connection.execute("CREATE TEMP TABLE requested_gold (chunk_id INTEGER PRIMARY KEY)")
            connection.executemany(
                "INSERT INTO requested_gold (chunk_id) VALUES (?)",
                ((chunk_id,) for chunk_id in requested_ids),
            )
            rows = connection.execute(
                """SELECT c.chunk_id, c.revision, c.path, c.codeunit_name
                   FROM chunks c JOIN requested_gold r ON r.chunk_id = c.chunk_id"""
            )
            chunks = {
                int(chunk_id): (str(chunk_revision), str(path), str(fqmn))
                for chunk_id, chunk_revision, path, fqmn in rows
            }
        finally:
            connection.close()

        for revision, query, gold in pairs:
            gold_chunks = {int(chunk_id) for chunk_id in gold.get("positive_chunk_ids", [])}
            if not gold_chunks:
                raise ValueError(f"query {query['query_id']} has no canonical corpus-chunk gold")
            missing = sorted(gold_chunks - chunks.keys())
            if missing:
                raise ValueError(f"query {query['query_id']} references missing chunk IDs {missing[:10]}")
            wrong_revisions = sorted(
                chunk_id for chunk_id in gold_chunks if chunks[chunk_id][0] != revision
            )
            if wrong_revisions:
                raise ValueError(
                    f"query {query['query_id']} has chunk IDs from another revision: "
                    f"{wrong_revisions[:10]}"
                )
            for unit in gold.get("positive_units", []):
                fqmn = str(unit.get("fqmn") or "")
                unit_chunks = {int(chunk_id) for chunk_id in unit.get("chunk_ids", [])}
                if not fqmn or not unit_chunks:
                    raise ValueError(
                        f"query {query['query_id']} has a gold unit without FQMN/chunk IDs"
                    )
                if not unit_chunks <= gold_chunks:
                    raise ValueError(
                        f"query {query['query_id']} unit chunk IDs are absent from positive_chunk_ids"
                    )
                mismatched = sorted(
                    chunk_id
                    for chunk_id in unit_chunks
                    if chunks[chunk_id][2] != fqmn or chunks[chunk_id][1] != str(unit["path"])
                )
                if mismatched:
                    raise ValueError(
                        f"query {query['query_id']} has chunk/FQMN/path mismatch: {mismatched[:10]}"
                    )
                canonical_units += 1
            task_id = str(query["task_id"])
            resolved.append(
                QueryWork(
                    repo=repo,
                    revision=revision,
                    task_id=task_id,
                    query_id=str(query["query_id"]),
                    query=str(query["query"]),
                    language=language_by_task[task_id],
                    gold_chunks=frozenset(gold_chunks),
                    gold_files=frozenset(chunks[chunk_id][1] for chunk_id in gold_chunks),
                )
            )
    return resolved, {
        "queries": len(resolved),
        "canonical_units": canonical_units,
        "missing_chunk_ids": 0,
        "fqmn_mismatches": 0,
    }


def retain_function_retrievable_queries(
    work: list[QueryWork], db_dir: Path
) -> tuple[list[QueryWork], dict]:
    ids_by_repo: dict[str, set[int]] = defaultdict(set)
    for item in work:
        ids_by_repo[item.repo].update(item.gold_chunks)
    metadata: dict[tuple[str, int], tuple[str, str]] = {}
    for repo, chunk_ids in sorted(ids_by_repo.items()):
        connection = sqlite3.connect(db_dir / repo / "embeddings.db")
        try:
            ordered = sorted(chunk_ids)
            for start in range(0, len(ordered), 500):
                page = ordered[start : start + 500]
                placeholders = ",".join("?" for _ in page)
                rows = connection.execute(
                    f"""SELECT chunk_id, path, codeunit_name FROM chunks
                        WHERE chunk_id IN ({placeholders})""",
                    page,
                )
                for chunk_id, path, codeunit_name in rows:
                    metadata[(repo, int(chunk_id))] = (str(path), str(codeunit_name))
        finally:
            connection.close()
    retained: list[QueryWork] = []
    mixed_queries = 0
    dropped_queries = 0
    removed_gold_ids: set[tuple[str, int]] = set()
    for item in work:
        function_chunks = frozenset(
            chunk_id
            for chunk_id in item.gold_chunks
            if metadata[(item.repo, chunk_id)][1] != "__chunkless_file_summary__"
        )
        removed = item.gold_chunks - function_chunks
        removed_gold_ids.update((item.repo, chunk_id) for chunk_id in removed)
        if not function_chunks:
            dropped_queries += 1
            continue
        if removed:
            mixed_queries += 1
        retained.append(
            replace(
                item,
                gold_chunks=function_chunks,
                gold_files=frozenset(
                    metadata[(item.repo, chunk_id)][0] for chunk_id in function_chunks
                ),
            )
        )
    audit = {
        "input_queries": len(work),
        "retained_queries": len(retained),
        "dropped_chunkless_only_queries": dropped_queries,
        "mixed_queries_with_chunkless_gold_removed": mixed_queries,
        "distinct_chunkless_gold_ids_removed": len(removed_gold_ids),
    }
    print(json.dumps({"event": "function_retrievable_slice", **audit}), flush=True)
    return retained, audit


def cache_digest(args: argparse.Namespace, work: list[QueryWork]) -> str:
    payload = {
        "version": 6,
        "model": str(Path(args.model).resolve()) if Path(args.model).exists() else args.model,
        "model_profile": args.model_profile,
        "hf_instruct_family": (
            args.hf_instruct_family if args.model_profile == "hf-instruct" else None
        ),
        "max_seq_length": args.max_seq_length,
        "truncate_dim": args.truncate_dim,
        "document_shape": args.document_shape,
        "function_retrievable_only": args.function_retrievable_only,
        "tokenizer_contract": tokenizer_contract_marker(args),
        "db_dir": str(args.db_dir.resolve()),
        "final_dir": str(args.final_dir.resolve()),
        "query_keys": [(item.repo, item.query_id, item.revision) for item in work],
    }
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:24]


def document_cache_identity(args: argparse.Namespace) -> str:
    payload = {
        "model": str(Path(args.model).resolve()) if Path(args.model).exists() else args.model,
        "model_profile": args.model_profile,
        "hf_instruct_family": (
            args.hf_instruct_family if args.model_profile == "hf-instruct" else None
        ),
        "max_seq_length": args.max_seq_length,
        "truncate_dim": args.truncate_dim,
        "document_shape": args.document_shape,
        "tokenizer_contract": tokenizer_contract_marker(args),
    }
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:24]


def tokenizer_contract_marker(args: argparse.Namespace) -> str | None:
    if args.model_profile == "hf-instruct" and args.hf_instruct_family == "bge-code":
        return BGE_CODE_TOKENIZER_CONTRACT
    return None


def find_pooling_module(model):
    for module in model:
        if module.__class__.__name__ == "Pooling":
            return module
    raise ValueError("hf-instruct profile expected a SentenceTransformers Pooling module")


def pooling_audit(pooling) -> dict[str, object]:
    pooling_mode = getattr(pooling, "pooling_mode", None)
    return {
        "pooling_mode": pooling_mode,
        "cls": bool(getattr(pooling, "pooling_mode_cls_token", False))
        or pooling_mode == "cls",
        "mean": bool(getattr(pooling, "pooling_mode_mean_tokens", False))
        or pooling_mode == "mean",
        "max": bool(getattr(pooling, "pooling_mode_max_tokens", False))
        or pooling_mode == "max",
        "mean_sqrt_len": bool(
            getattr(pooling, "pooling_mode_mean_sqrt_len_tokens", False)
        )
        or pooling_mode == "mean_sqrt_len_tokens",
        "weightedmean": bool(
            getattr(pooling, "pooling_mode_weightedmean_tokens", False)
        )
        or pooling_mode == "weightedmean",
        "lasttoken": bool(getattr(pooling, "pooling_mode_lasttoken", False))
        or pooling_mode == "lasttoken",
        "include_prompt": bool(getattr(pooling, "include_prompt", False)),
        "word_embedding_dimension": (
            getattr(pooling, "word_embedding_dimension", None)
            or getattr(pooling, "pooling_output_dimension", None)
        ),
    }


def require_last_token_pooling(model, family: str) -> dict[str, object]:
    pooling = find_pooling_module(model)
    actual = pooling_audit(pooling)
    expected_enabled = {
        "cls": False,
        "mean": False,
        "max": False,
        "mean_sqrt_len": False,
        "weightedmean": False,
        "lasttoken": True,
        "include_prompt": True,
    }
    mismatches = {
        key: actual[key]
        for key, expected in expected_enabled.items()
        if actual[key] != expected
    }
    if mismatches:
        raise ValueError(
            f"hf-instruct {family} profile expected last-token-only pooling with "
            f"include_prompt=true; actual={actual!r}"
        )
    return actual


def resolve_hf_instruct_profile(
    model, family: str, attn_implementation: str
) -> tuple[str, None]:
    bundled_prompts = dict(model.prompts)
    pooling = require_last_token_pooling(model, family)
    tokenizer_contract = None
    if family == "qwen3":
        expected_bundled_prompts = {
            "query": (
                "Instruct: Given a web search query, retrieve relevant passages that "
                "answer the query\nQuery:"
            ),
            "document": "",
        }
        if bundled_prompts != expected_bundled_prompts:
            raise ValueError(
                "hf-instruct qwen3 prompt mismatch: "
                f"expected={expected_bundled_prompts!r}, actual={bundled_prompts!r}"
            )
        query_prompt_text = f"Instruct: {PATCHPOINT_RETRIEVAL_INSTRUCTION}\nQuery:"
    elif family == "bge-code":
        tokenizer_contract = apply_bge_code_tokenizer_contract(model.tokenizer)
        non_empty_prompts = {
            name: prompt for name, prompt in bundled_prompts.items() if prompt
        }
        if non_empty_prompts:
            raise ValueError(
                "hf-instruct bge-code expects empty bundled ST prompts; "
                f"actual={bundled_prompts!r}"
            )
        query_prompt_text = f"<instruct>{PATCHPOINT_RETRIEVAL_INSTRUCTION}\n<query>"
    else:
        raise ValueError(f"unknown hf-instruct family {family!r}")
    model.prompts["query"] = query_prompt_text
    print(
        json.dumps(
            {
                "event": "hf_instruct_profile_resolved",
                "family": family,
                "bundled_prompts": bundled_prompts,
                "query_prompt": model.prompts["query"],
                "document_prompt": None,
                "pooling": pooling,
                "padding_side": getattr(model.tokenizer, "padding_side", None),
                "tokenizer_contract": tokenizer_contract,
                "attn_implementation": attn_implementation,
            }
        ),
        flush=True,
    )
    return "query", None


def apply_bge_code_tokenizer_contract(tokenizer) -> dict[str, object]:
    eos_token_id = getattr(tokenizer, "eos_token_id", None)
    if eos_token_id is None:
        raise ValueError("hf-instruct bge-code tokenizer must define eos_token_id")

    tokenizer.add_eos_token = True
    update_post_processor = getattr(tokenizer, "update_post_processor", None)
    if callable(update_post_processor):
        update_post_processor()
    tokenizer.padding_side = "left"

    examples = [
        "hello world",
        "def f(x): return x + 1",
        "SELECT * FROM users WHERE id = 1",
    ]
    observed_last_ids = []
    for example in examples:
        input_ids = tokenizer(example, add_special_tokens=True)["input_ids"]
        if not input_ids or input_ids[-1] != eos_token_id:
            raise ValueError(
                "hf-instruct bge-code tokenizer failed to append eos: "
                f"text={example!r}, tail={input_ids[-5:]}"
            )
        observed_last_ids.append(input_ids[-1])

    truncation_length = 5
    truncated_ids = tokenizer(
        " ".join(["token"] * 64),
        add_special_tokens=True,
        truncation=True,
        max_length=truncation_length,
    )["input_ids"]
    if len(truncated_ids) != truncation_length or truncated_ids[-1] != eos_token_id:
        raise ValueError(
            "hf-instruct bge-code tokenizer truncation must preserve final eos: "
            f"max_length={truncation_length}, ids={truncated_ids}"
        )

    return {
        "marker": BGE_CODE_TOKENIZER_CONTRACT,
        "class": tokenizer.__class__.__name__,
        "module": tokenizer.__class__.__module__,
        "eos_token_id": eos_token_id,
        "add_eos_token": bool(getattr(tokenizer, "add_eos_token", False)),
        "padding_side": getattr(tokenizer, "padding_side", None),
        "observed_last_ids": observed_last_ids,
        "truncated_length": len(truncated_ids),
        "truncated_last_id": truncated_ids[-1],
    }


def configure_model_profile(
    model,
    model_profile: str,
    hf_instruct_family: str | None,
    attn_implementation: str | None,
) -> tuple[str, str | None]:
    if model_profile == "voyage":
        expected = {
            "query": "Represent the query for retrieving supporting documents: ",
            "document": "Represent the document for retrieval: ",
        }
        actual = {name: model.prompts.get(name) for name in expected}
        if actual != expected:
            raise ValueError(f"Voyage prompt mismatch: expected={expected!r}, actual={actual!r}")
        return "query", "document"
    if model_profile == "swerank-small":
        expected_query = "Represent this query for searching relevant code: "
        if model.prompts.get("query") != expected_query:
            raise ValueError(
                f"SweRank-small query prompt mismatch: expected={expected_query!r}, "
                f"actual={model.prompts.get('query')!r}"
            )
        return "query", None
    if model_profile == "granite":
        expected = {
            "query": "Given a GitHub issue, retrieve code that must be changed to fix it.\nQuery: ",
            "document": "Passage: Code chunk from repository.\n",
        }
        actual = {name: model.prompts.get(name) for name in expected}
        if actual != expected:
            raise ValueError(f"Granite prompt mismatch: expected={expected!r}, actual={actual!r}")
        return "query", "document"
    if model_profile == "nemotron-embed":
        # Nemotron-3-Embed ships e5-style prefixes in its ST config; verify and use
        # them as-is (mean pooling, L2-normalized output are checkpoint-configured).
        expected = {"query": "query: ", "document": "passage: "}
        actual = {name: model.prompts.get(name) for name in expected}
        if actual != expected:
            raise ValueError(
                f"Nemotron prompt mismatch: expected={expected!r}, actual={actual!r}"
            )
        return "query", "document"
    if model_profile == "hf-instruct":
        if hf_instruct_family is None:
            raise ValueError("--model-profile hf-instruct requires --hf-instruct-family")
        if attn_implementation is None:
            raise ValueError("hf-instruct requires an explicit attention implementation")
        return resolve_hf_instruct_profile(model, hf_instruct_family, attn_implementation)
    expected_query = (
        "Instruct: Given a github issue, identify the code that needs to be changed "
        "to fix the issue.\nQuery: "
    )
    if model.prompts.get("query") != expected_query:
        raise ValueError(
            f"SweRank-large query prompt mismatch: expected={expected_query!r}, "
            f"actual={model.prompts.get('query')!r}"
        )
    return "query", None


def _model_load_kwargs(
    profile: str,
    family: str | None,
    truncate_dim: int | None,
    device: str | None,
    torch_module,
) -> tuple[dict[str, object], str | None]:
    model_kwargs: dict[str, object] = {"torch_dtype": torch_module.bfloat16}
    attn_implementation = None
    if profile in {"swerank-large", "hf-instruct"}:
        attn_implementation = "sdpa"
        model_kwargs["attn_implementation"] = attn_implementation
    sentence_transformer_kwargs = {
        # BGE-Code's remote tokenizer is still transformers-5-incompatible after
        # aliasing the removed qwen2 fast module; repair the stock tokenizer below.
        "trust_remote_code": not is_bge_code_hf_instruct_profile(profile, family),
        "model_kwargs": model_kwargs,
        "truncate_dim": truncate_dim,
    }
    if device is not None:
        sentence_transformer_kwargs["device"] = device
    return sentence_transformer_kwargs, attn_implementation


def _build_profiled_model_with_constructor(
    sentence_transformer_cls,
    torch_module,
    model_path: str,
    profile: str,
    family: str | None,
    max_seq_length: int,
    device: str | None,
    truncate_dim: int | None,
):
    sentence_transformer_kwargs, attn_implementation = _model_load_kwargs(
        profile, family, truncate_dim, device, torch_module
    )
    model = sentence_transformer_cls(model_path, **sentence_transformer_kwargs)
    model.max_seq_length = max_seq_length
    if profile == "swerank-large" and model.tokenizer.padding_side != "left":
        raise ValueError(
            "SweRank-large requires the official tokenizer's left-padding contract, "
            f"got {model.tokenizer.padding_side!r}"
        )
    query_prompt, document_prompt = configure_model_profile(
        model, profile, family, attn_implementation
    )
    return model, query_prompt, document_prompt


def build_profiled_model(
    model_path: str,
    profile: str,
    family: str | None,
    max_seq_length: int,
    device: str | None,
    truncate_dim: int | None,
):
    import torch
    from sentence_transformers import SentenceTransformer

    return _build_profiled_model_with_constructor(
        SentenceTransformer,
        torch,
        model_path,
        profile,
        family,
        max_seq_length,
        device,
        truncate_dim,
    )


def load_sentence_transformer(args: argparse.Namespace):
    device = "cpu" if args.load_per_worker_pool else None
    return build_profiled_model(
        args.model,
        args.model_profile,
        args.hf_instruct_family,
        args.max_seq_length,
        device,
        args.truncate_dim,
    )


def is_bge_code_hf_instruct_profile(profile: str, family: str | None) -> bool:
    return profile == "hf-instruct" and family == "bge-code"


def is_bge_code_hf_instruct(args: argparse.Namespace) -> bool:
    return is_bge_code_hf_instruct_profile(args.model_profile, args.hf_instruct_family)


def resolved_prompt_text(model, prompt_name: str | None) -> str | None:
    if prompt_name is None:
        return None
    return model.prompts.get(prompt_name)


def bge_code_eos_last_token_id_ok(model) -> bool:
    eos_token_id = getattr(model.tokenizer, "eos_token_id", None)
    if eos_token_id is None:
        return False
    input_ids = model.tokenizer("pool eos probe", add_special_tokens=True)["input_ids"]
    return bool(input_ids) and input_ids[-1] == eos_token_id


def pool_worker_profile_event(
    model,
    device: str,
    query_prompt_name: str | None,
    document_prompt_name: str | None,
    profile: str,
    family: str | None,
) -> dict[str, object]:
    eos_last_token_id_ok = (
        bge_code_eos_last_token_id_ok(model)
        if is_bge_code_hf_instruct_profile(profile, family)
        else None
    )
    return {
        "event": "pool_worker_profile",
        "device": device,
        "query_prompt": resolved_prompt_text(model, query_prompt_name),
        "document_prompt": resolved_prompt_text(model, document_prompt_name),
        "eos_last_token_id_ok": eos_last_token_id_ok,
    }


def validate_pool_worker_profile_event(
    event: dict[str, object],
    *,
    expected_device: str,
    expected_query_prompt: str | None,
    expected_document_prompt: str | None,
) -> None:
    if event.get("event") == "pool_worker_error":
        raise RuntimeError(
            f"model worker {event.get('device')} failed during load: "
            f"{event.get('error_type')}: {event.get('error')}"
        )
    if event.get("event") != "pool_worker_profile":
        raise RuntimeError(f"unexpected model worker readiness event: {event!r}")
    if event.get("device") != expected_device:
        raise RuntimeError(
            f"model worker readiness mismatch: expected {expected_device}, "
            f"got {event.get('device')}"
        )
    if event.get("query_prompt") != expected_query_prompt:
        raise RuntimeError(
            "pool worker query prompt differs from main process: "
            f"expected={expected_query_prompt!r}, actual={event.get('query_prompt')!r}, "
            f"device={expected_device}"
        )
    if event.get("document_prompt") != expected_document_prompt:
        raise RuntimeError(
            "pool worker document prompt differs from main process: "
            f"expected={expected_document_prompt!r}, "
            f"actual={event.get('document_prompt')!r}, device={expected_device}"
        )
    if event.get("eos_last_token_id_ok") is False:
        raise RuntimeError(
            f"pool worker bge-code EOS contract failed on {expected_device}: {event!r}"
        )


def _load_pool_worker_model(
    device: str,
    model_path: str,
    max_seq_length: int,
    model_profile: str,
    hf_instruct_family: str | None,
    truncate_dim: int | None,
    *,
    sentence_transformer_cls=None,
    torch_module=None,
):
    if sentence_transformer_cls is None or torch_module is None:
        import torch
        from sentence_transformers import SentenceTransformer

        if sentence_transformer_cls is None:
            sentence_transformer_cls = SentenceTransformer
        if torch_module is None:
            torch_module = torch
    # Construct on CPU: without an explicit device, SentenceTransformers places the
    # full model on cuda:0 before .to(device) moves it, so every pool worker
    # transiently double-occupies GPU 0 -- fatal once resident + transient copies
    # exceed the card (observed on 32GB: worker 2 OOMs against worker 0's weights).
    model, query_prompt, document_prompt = _build_profiled_model_with_constructor(
        sentence_transformer_cls,
        torch_module,
        model_path,
        model_profile,
        hf_instruct_family,
        max_seq_length,
        "cpu",
        truncate_dim,
    )
    model.to(device)
    event = pool_worker_profile_event(
        model,
        device,
        query_prompt,
        document_prompt,
        model_profile,
        hf_instruct_family,
    )
    return model, event, query_prompt, document_prompt


def encode_smoke(args: argparse.Namespace) -> int:
    model, query_prompt, document_prompt = load_sentence_transformer(args)
    target_device = args.direct_device or args.devices.split(",")[0]
    query_texts = ["Issue: the parser ignores quoted values in config files."]
    document_texts = ["src/config.py\ndef parse_value(raw):\n    return raw.strip()"]
    pool = None
    if args.load_per_worker_pool:
        import torch

        model.to("cpu")
        torch.cuda.empty_cache()
        pool = start_model_loading_pool(
            args.model,
            args.max_seq_length,
            args.devices.split(","),
            args.model_profile,
            args.hf_instruct_family,
            args.truncate_dim,
            resolved_prompt_text(model, query_prompt),
            resolved_prompt_text(model, document_prompt),
        )
        try:
            query_vector = bucketed_encode(model, pool, query_texts, query_prompt)
            document_vector = bucketed_encode(model, pool, document_texts, document_prompt)
        finally:
            model.stop_multi_process_pool(pool)
    else:
        model.to(target_device)
        query_vector = model.encode(
            query_texts,
            prompt_name=query_prompt,
            batch_size=1,
            normalize_embeddings=True,
            show_progress_bar=False,
        )
        document_vector = model.encode(
            document_texts,
            prompt_name=document_prompt,
            batch_size=1,
            normalize_embeddings=True,
            show_progress_bar=False,
        )
    print(
        json.dumps(
            {
                "event": "encode_smoke_complete",
                "device": target_device,
                "query_prompt_name": query_prompt,
                "document_prompt_name": document_prompt,
                "query_shape": list(query_vector.shape),
                "document_shape": list(document_vector.shape),
                "query_norm": float(np.linalg.norm(query_vector[0])),
                "document_norm": float(np.linalg.norm(document_vector[0])),
            }
        ),
        flush=True,
    )
    return 0


def collect_swerank_components(
    work: list[QueryWork], db_dir: Path
) -> tuple[list[str], dict[tuple[str, str], int], list, dict]:
    revisions_by_repo: dict[str, set[str]] = defaultdict(set)
    for item in work:
        revisions_by_repo[item.repo].add(item.revision)
    texts: dict[str, int] = {}
    unique_texts: list[str] = []
    text_index: dict[tuple[str, str], int] = {}
    composes: list[tuple[str, str, str, str]] = []
    methods = 0
    top_level = 0
    for repo, revisions in sorted(revisions_by_repo.items()):
        connection = sqlite3.connect(db_dir / repo / "embeddings.db")
        try:
            placeholders = ",".join("?" for _ in revisions)
            rows = connection.execute(
                f"""SELECT vector_key, path, codeunit_name, text, parent_text
                    FROM chunks WHERE revision IN ({placeholders})""",
                sorted(revisions),
            )
            seen: set[str] = set()
            for vector_key, path, codeunit_name, source_text, parent_text in rows:
                vector_key = str(vector_key)
                if vector_key in seen:
                    continue
                seen.add(vector_key)
                if str(codeunit_name) == "__chunkless_file_summary__":
                    continue
                document, is_method = swerank_document_text(
                    str(path), str(codeunit_name), str(source_text), str(parent_text)
                )
                if is_method:
                    methods += 1
                else:
                    top_level += 1
                document_key = "swerank-v1:" + hashlib.sha256(
                    document.encode("utf-8")
                ).hexdigest()
                row = texts.get(document)
                if row is None:
                    row = len(unique_texts)
                    texts[document] = row
                    unique_texts.append(document)
                text_index[(repo, document_key)] = row
                composes.append((repo, vector_key, document_key, document_key))
        finally:
            connection.close()
    audit = {
        "format": "swerank-find_py_or_non_dict_with_path",
        "unique_texts": len(unique_texts),
        "vectors": len(composes),
        "class_methods": methods,
        "top_level_functions": top_level,
    }
    print(json.dumps({"event": "swerank_documents_collected", **audit}), flush=True)
    return unique_texts, text_index, composes, audit


def save_cache(path: Path, doc_vectors: np.ndarray, text_index: dict, query_vectors: np.ndarray, work: list[QueryWork]) -> None:
    temporary = path.with_name(path.name + ".tmp")
    if temporary.exists():
        shutil.rmtree(temporary)
    temporary.mkdir(parents=True)
    np.save(temporary / "documents.npy", doc_vectors)
    np.save(temporary / "queries.npy", query_vectors)
    (temporary / "document-keys.json").write_text(
        json.dumps([[repo, key, row] for (repo, key), row in text_index.items()]), encoding="utf-8"
    )
    (temporary / "query-keys.json").write_text(
        json.dumps([[item.repo, item.query_id] for item in work]), encoding="utf-8"
    )
    if path.exists():
        shutil.rmtree(path)
    temporary.rename(path)


def load_cache(
    path: Path, composes: list, work: list[QueryWork]
) -> tuple[DocumentVectors, dict, np.ndarray] | None:
    files = [path / "documents.npy", path / "queries.npy", path / "document-keys.json", path / "query-keys.json"]
    if not all(file.is_file() for file in files):
        overlay_files = [
            path / "overlay-documents.npy",
            path / "base-cache.json",
            path / "queries.npy",
            path / "document-keys.json",
            path / "query-keys.json",
        ]
        if not all(file.is_file() for file in overlay_files):
            return None
        base_manifest = json.loads((path / "base-cache.json").read_text(encoding="utf-8"))
        base_path = Path(str(base_manifest["path"]))
        base_documents_path = base_path / "documents.npy"
        if not base_documents_path.is_file():
            return None
        base_documents = np.load(base_documents_path, mmap_mode="r")
        overlay_documents = np.load(path / "overlay-documents.npy", mmap_mode="r")
        if (
            list(base_documents.shape) != base_manifest["shape"]
            or int(base_documents.shape[1]) != int(overlay_documents.shape[1])
        ):
            return None
        documents = DocumentVectors(base_documents, overlay_documents)
    else:
        documents = DocumentVectors(np.load(path / "documents.npy", mmap_mode="r"))
    query_keys = json.loads((path / "query-keys.json").read_text(encoding="utf-8"))
    if query_keys != [[item.repo, item.query_id] for item in work]:
        return None
    text_index = {
        (str(repo), str(key)): int(row)
        for repo, key, row in json.loads((path / "document-keys.json").read_text(encoding="utf-8"))
    }
    if any((repo, child) not in text_index or (repo, parent) not in text_index for repo, _vector, child, parent in composes):
        return None
    return (
        documents,
        text_index,
        np.load(path / "queries.npy", mmap_mode="r"),
    )


def reused_document_layout(
    reuse_path: Path,
    component_texts: list[str],
    text_index: dict[tuple[str, str], int],
    *,
    reuse_below_tokens: int | None = None,
    tokenizer=None,
    tokenization_batch_size: int = 1024,
) -> tuple[DocumentVectors, dict[tuple[str, str], int], list[str], dict]:
    base_documents_path = reuse_path / "documents.npy"
    base_keys_path = reuse_path / "document-keys.json"
    if not base_documents_path.is_file() or not base_keys_path.is_file():
        raise ValueError(f"reuse cache is incomplete: {reuse_path}")
    base_documents = np.load(base_documents_path, mmap_mode="r")
    base_index = {
        (str(repo), str(key)): int(row)
        for repo, key, row in json.loads(base_keys_path.read_text(encoding="utf-8"))
    }
    excluded_rows: set[int] = set()
    length_audit: dict[str, object] = {}
    if reuse_below_tokens is not None:
        if tokenizer is None:
            raise ValueError("reuse_below_tokens requires a tokenizer")
        if reuse_below_tokens < 0:
            raise ValueError("reuse_below_tokens must be non-negative")
        length_start = time.monotonic()
        tokenization_candidates = [
            (row, text)
            for row, text in enumerate(component_texts)
            if len(text) > reuse_below_tokens
        ]
        for start in range(0, len(tokenization_candidates), tokenization_batch_size):
            batch = tokenization_candidates[start : start + tokenization_batch_size]
            encoded = tokenizer(
                [text for _row, text in batch],
                add_special_tokens=True,
                padding=False,
                truncation=False,
                return_length=True,
            )
            lengths = encoded.get("length")
            if lengths is None:
                lengths = [len(ids) for ids in encoded["input_ids"]]
            for (row, _text), length in zip(batch, lengths, strict=True):
                if int(length) > reuse_below_tokens:
                    excluded_rows.add(row)
        length_audit = {
            "reuse_below_tokens": reuse_below_tokens,
            "char_safe_current_rows": len(component_texts)
            - len(tokenization_candidates),
            "char_prefilter_candidate_rows": len(tokenization_candidates),
            "token_excluded_current_rows": len(excluded_rows),
            "length_classification_seconds": time.monotonic() - length_start,
            "tokenization_batch_size": tokenization_batch_size,
        }
    current_to_base: dict[int, int] = {}
    for key, current_row in text_index.items():
        if current_row in excluded_rows:
            continue
        base_row = base_index.get(key)
        if base_row is not None:
            current_to_base.setdefault(current_row, base_row)
    missing_rows = [
        row for row in range(len(component_texts)) if row not in current_to_base
    ]
    missing_position = {row: position for position, row in enumerate(missing_rows)}
    base_rows = int(base_documents.shape[0])
    remapped = {
        key: (
            current_to_base[current_row]
            if current_row in current_to_base
            else base_rows + missing_position[current_row]
        )
        for key, current_row in text_index.items()
    }
    audit = {
        "base_cache": str(reuse_path.resolve()),
        "base_rows": base_rows,
        "reused_current_rows": len(component_texts) - len(missing_rows),
        "missing_current_rows": len(missing_rows),
    }
    audit.update(length_audit)
    return (
        DocumentVectors(base_documents),
        remapped,
        [component_texts[row] for row in missing_rows],
        audit,
    )


def save_overlay_cache(
    path: Path,
    base_path: Path,
    base_documents: np.ndarray,
    overlay_documents: np.ndarray,
    text_index: dict,
    query_vectors: np.ndarray,
    work: list[QueryWork],
) -> None:
    temporary = path.with_name(path.name + ".tmp")
    if temporary.exists():
        shutil.rmtree(temporary)
    temporary.mkdir(parents=True)
    np.save(temporary / "overlay-documents.npy", overlay_documents)
    np.save(temporary / "queries.npy", query_vectors)
    (temporary / "base-cache.json").write_text(
        json.dumps(
            {"path": str(base_path.resolve()), "shape": list(base_documents.shape)},
            sort_keys=True,
        ),
        encoding="utf-8",
    )
    (temporary / "document-keys.json").write_text(
        json.dumps([[repo, key, row] for (repo, key), row in text_index.items()]),
        encoding="utf-8",
    )
    (temporary / "query-keys.json").write_text(
        json.dumps([[item.repo, item.query_id] for item in work]), encoding="utf-8"
    )
    if path.exists():
        shutil.rmtree(path)
    temporary.rename(path)


def update_document_store(
    path: Path,
    documents: DocumentVectors,
    text_index: dict[tuple[str, str], int],
) -> None:
    current_items = list(text_index.items())
    if not current_items:
        return
    existing_documents_path = path / "documents.npy"
    existing_keys_path = path / "document-keys.json"
    existing_documents = None
    existing_entries: list[tuple[str, str, int]] = []
    if existing_documents_path.is_file() and existing_keys_path.is_file():
        existing_documents = np.load(existing_documents_path, mmap_mode="r")
        existing_entries = [
            (str(repo), str(key), int(row))
            for repo, key, row in json.loads(
                existing_keys_path.read_text(encoding="utf-8")
            )
        ]
        if int(existing_documents.shape[1]) != documents.shape[1]:
            raise ValueError(
                f"docstore dimension mismatch: existing={existing_documents.shape[1]}, "
                f"current={documents.shape[1]}"
            )

    rows: list[tuple[str, str, int]] = []
    seen: set[tuple[str, str]] = set()
    existing_sources: list[int] = []
    for repo, key, source_row in sorted(existing_entries, key=lambda item: item[2]):
        cache_key = (repo, key)
        if cache_key in seen:
            continue
        if existing_documents is None or not 0 <= source_row < int(
            existing_documents.shape[0]
        ):
            raise ValueError(
                f"docstore key row out of bounds: {(repo, key, source_row)!r}"
            )
        seen.add(cache_key)
        existing_sources.append(source_row)
        rows.append((repo, key, len(rows)))

    current_sources: list[int] = []
    for (repo, key), source_row in current_items:
        cache_key = (str(repo), str(key))
        if cache_key in seen:
            continue
        seen.add(cache_key)
        current_sources.append(int(source_row))
        rows.append((cache_key[0], cache_key[1], len(rows)))

    temporary = path.with_name(f"{path.name}.tmp-{os.getpid()}-{time.time_ns()}")
    if temporary.exists():
        shutil.rmtree(temporary)
    temporary.parent.mkdir(parents=True, exist_ok=True)
    temporary.mkdir()
    try:
        dtype = (
            existing_documents.dtype
            if existing_documents is not None
            else documents.base.dtype
        )
        output = np.lib.format.open_memmap(
            temporary / "documents.npy",
            mode="w+",
            dtype=dtype,
            shape=(len(rows), documents.shape[1]),
        )
        cursor = 0
        if existing_documents is not None and existing_sources:
            existing_rows = np.asarray(existing_sources, dtype=np.int64)
            output[cursor : cursor + len(existing_sources)] = existing_documents[
                existing_rows
            ]
            cursor += len(existing_sources)
        if current_sources:
            current_rows = np.asarray(current_sources, dtype=np.int64)
            output[cursor : cursor + len(current_sources)] = documents.take(
                current_rows
            )
        output.flush()
        (temporary / "document-keys.json").write_text(
            json.dumps([[repo, key, row] for repo, key, row in rows]),
            encoding="utf-8",
        )
        old_path: Path | None = None
        if path.exists():
            old_path = path.with_name(
                f"{path.name}.old-{os.getpid()}-{time.time_ns()}"
            )
            if old_path.exists():
                shutil.rmtree(old_path)
            path.rename(old_path)
        try:
            temporary.rename(path)
        except Exception:
            if old_path is not None and old_path.exists() and not path.exists():
                old_path.rename(path)
            raise
        else:
            if old_path is not None:
                shutil.rmtree(old_path)
    except Exception:
        if temporary.exists():
            shutil.rmtree(temporary)
        raise


def materialize_current_document_layout(
    documents: DocumentVectors,
    text_index: dict[tuple[str, str], int],
) -> tuple[np.ndarray, dict[tuple[str, str], int]]:
    source_rows = sorted(set(text_index.values()))
    row_remap = {source_row: row for row, source_row in enumerate(source_rows)}
    materialized = documents.take(np.asarray(source_rows, dtype=np.int64))
    remapped = {key: row_remap[source_row] for key, source_row in text_index.items()}
    return materialized, remapped


def derive_truncated_cache(
    source_path: Path,
    target_path: Path,
    composes: list,
    work: list[QueryWork],
    truncate_dim: int,
    *,
    block_size: int = 8192,
) -> None:
    source = load_cache(source_path, composes, work)
    if source is None:
        raise ValueError(
            "truncation source must be a complete cache with identical document/query keys"
        )
    documents, text_index, queries = source
    if documents.overlay is not None:
        raise ValueError("truncation source cannot be an overlay cache")
    if not 0 < truncate_dim < documents.shape[1]:
        raise ValueError(
            f"truncate_dim must be below source dimension {documents.shape[1]}"
        )
    temporary = target_path.with_name(target_path.name + ".tmp")
    if temporary.exists():
        shutil.rmtree(temporary)
    temporary.mkdir(parents=True)

    def truncate(source_vectors: np.ndarray, output_path: Path) -> None:
        output = np.lib.format.open_memmap(
            output_path,
            mode="w+",
            dtype=np.float32,
            shape=(int(source_vectors.shape[0]), truncate_dim),
        )
        for start in range(0, len(source_vectors), block_size):
            stop = min(start + block_size, len(source_vectors))
            block = np.array(
                source_vectors[start:stop, :truncate_dim],
                dtype=np.float32,
                copy=True,
            )
            norms = np.linalg.norm(block, axis=1)
            nonzero = norms > 0
            block[nonzero] /= norms[nonzero, None]
            output[start:stop] = block
        output.flush()

    truncate(documents.base, temporary / "documents.npy")
    truncate(queries, temporary / "queries.npy")
    (temporary / "document-keys.json").write_text(
        json.dumps([[repo, key, row] for (repo, key), row in text_index.items()]),
        encoding="utf-8",
    )
    (temporary / "query-keys.json").write_text(
        json.dumps([[item.repo, item.query_id] for item in work]), encoding="utf-8"
    )
    if target_path.exists():
        shutil.rmtree(target_path)
    temporary.rename(target_path)


def compose_document_matrix(
    documents: DocumentVectors,
    text_index: dict[tuple[str, str], int],
    composes: list[tuple[str, str, str, str]],
    alpha: float,
    *,
    workers: int,
    block_size: int = 1024,
) -> tuple[np.ndarray, dict[tuple[str, str], int]]:
    if documents.overlay is None:
        return compose_parent_matrix(
            documents.base, text_index, composes, alpha, workers=workers
        )
    child_rows = np.fromiter(
        (
            text_index[(repo, child_key)]
            for repo, _vector_key, child_key, _parent_key in composes
        ),
        dtype=np.int64,
        count=len(composes),
    )
    parent_rows = np.fromiter(
        (
            text_index[(repo, parent_key)]
            for repo, _vector_key, _child_key, parent_key in composes
        ),
        dtype=np.int64,
        count=len(composes),
    )
    output = np.empty((len(composes), documents.shape[1]), dtype=np.float32)
    row_by_key = {
        (repo, vector_key): row
        for row, (repo, vector_key, _child, _parent) in enumerate(composes)
    }
    ranges = [
        (start, min(start + block_size, len(composes)))
        for start in range(0, len(composes), block_size)
    ]

    def compose_block(bounds: tuple[int, int]) -> None:
        start, stop = bounds
        target = output[start:stop]
        np.multiply(documents.take(child_rows[start:stop]), alpha, out=target)
        target += documents.take(parent_rows[start:stop]) * (1.0 - alpha)
        norms = np.linalg.norm(target, axis=1)
        nonzero = norms > 0
        target[nonzero] /= norms[nonzero, None]

    from concurrent.futures import ThreadPoolExecutor

    with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
        list(pool.map(compose_block, ranges))
    return output, row_by_key


def reciprocal_rank(ranked: list[int], gold: frozenset[int]) -> float:
    return next((1.0 / rank for rank, chunk_id in enumerate(ranked, 1) if chunk_id in gold), 0.0)


def mean_dict(rows: Iterable[dict[str, float]], keys: list[str]) -> dict[str, float]:
    materialized = list(rows)
    return {key: sum(row[key] for row in materialized) / len(materialized) for key in keys}


def nested_macro(query_rows: list[dict], keys: list[str]) -> tuple[dict, dict]:
    by_task: dict[tuple[str, str], list[dict]] = defaultdict(list)
    for row in query_rows:
        by_task[(row["repo"], row["task_id"])].append(row)
    task_rows = [
        {"repo": rows[0]["repo"], "language": rows[0]["language"], **mean_dict(rows, keys)}
        for rows in by_task.values()
    ]
    by_repo: dict[str, list[dict]] = defaultdict(list)
    for row in task_rows:
        by_repo[row["repo"]].append(row)
    repo_rows = [
        {"repo": repo, "language": rows[0]["language"], **mean_dict(rows, keys)}
        for repo, rows in sorted(by_repo.items())
    ]
    by_language: dict[str, list[dict]] = defaultdict(list)
    for row in repo_rows:
        by_language[row["language"]].append(row)
    language_rows = {
        language: mean_dict(rows, keys) for language, rows in sorted(by_language.items())
    }
    return mean_dict(language_rows.values(), keys), {"languages": language_rows, "repositories": repo_rows}


def build_evaluation_row(
    item: QueryWork,
    ranked_chunks: list[int],
    ranked_files: list[str],
    ks: tuple[int, ...],
) -> dict:
    row: dict[str, object] = {
        "repo": item.repo,
        "revision": item.revision,
        "language": item.language,
        "task_id": item.task_id,
        "query_id": item.query_id,
        "gold_chunks": sorted(item.gold_chunks),
        "gold_files": sorted(item.gold_files),
        "mrr": reciprocal_rank(ranked_chunks, item.gold_chunks),
        "file_mrr": next(
            (
                1.0 / rank
                for rank, path in enumerate(ranked_files, 1)
                if path in item.gold_files
            ),
            0.0,
        ),
        "ranked_chunks_top50": ranked_chunks[:50],
        "ranked_files_top50": ranked_files[:50],
    }
    for k in ks:
        top_chunks = set(ranked_chunks[:k])
        top_files = set(ranked_files[:k])
        row[f"acc@{k}"] = float(bool(top_chunks & item.gold_chunks))
        row[f"recall@{k}"] = len(top_chunks & item.gold_chunks) / len(item.gold_chunks)
        row[f"file_acc@{k}"] = float(bool(top_files & item.gold_files))
        row[f"file_recall@{k}"] = len(top_files & item.gold_files) / len(item.gold_files)
    return row


def score(
    work: list[QueryWork],
    db_dir: Path,
    composed: np.ndarray,
    composed_rows: dict[tuple[str, str], int],
    query_vectors: np.ndarray,
    ks: tuple[int, ...],
    workers: int,
    *,
    include_chunkless: bool,
) -> list[dict]:
    from concurrent.futures import ThreadPoolExecutor

    work_by_revision: dict[tuple[str, str], list[tuple[int, QueryWork]]] = defaultdict(list)
    for index, item in enumerate(work):
        work_by_revision[(item.repo, item.revision)].append((index, item))

    # Loading one revision at a time causes thousands of SQLite opens and small
    # indexed queries. Read every requested revision in one pass per repository.
    revisions_by_repo: dict[str, set[str]] = defaultdict(set)
    for repo, revision in work_by_revision:
        revisions_by_repo[repo].add(revision)
    layouts: dict[tuple[str, str], tuple[np.ndarray, list[str], list[str]]] = {}
    layout_start = time.monotonic()
    for repo, revisions in sorted(revisions_by_repo.items()):
        ordered_revisions = sorted(revisions)
        placeholders = ",".join("?" for _ in ordered_revisions)
        connection = sqlite3.connect(db_dir / repo / "embeddings.db")
        try:
            chunkless_clause = (
                "" if include_chunkless else "AND codeunit_name != '__chunkless_file_summary__'"
            )
            rows = connection.execute(
                f"""SELECT revision, chunk_id, vector_key, path FROM chunks
                    WHERE revision IN ({placeholders})
                    {chunkless_clause}
                    ORDER BY revision, path, codeunit_name, chunk_id""",
                ordered_revisions,
            )
            grouped: dict[str, list[tuple[int, str, str]]] = defaultdict(list)
            for revision, chunk_id, vector_key, path in rows:
                grouped[str(revision)].append((int(chunk_id), str(vector_key), str(path)))
        finally:
            connection.close()
        for revision in ordered_revisions:
            entries = grouped.get(revision)
            if not entries:
                raise ValueError(f"no corpus chunks for {repo}@{revision}")
            layouts[(repo, revision)] = (
                np.asarray([row[0] for row in entries], dtype=np.int64),
                [row[1] for row in entries],
                [row[2] for row in entries],
            )
    print(
        json.dumps(
            {
                "event": "scoring_layouts_loaded",
                "repositories": len(revisions_by_repo),
                "revisions": len(layouts),
                "seconds": time.monotonic() - layout_start,
            }
        ),
        flush=True,
    )

    def score_revision(group: tuple[tuple[str, str], list[tuple[int, QueryWork]]]) -> list[dict]:
        (repo, revision), items = group
        chunk_ids, vector_keys, paths = layouts[(repo, revision)]
        matrix = composed[[composed_rows[(repo, vector_key)] for vector_key in vector_keys]]
        results: list[dict] = []
        for query_index, item in items:
            order = np.argsort(matrix @ query_vectors[query_index])[::-1]
            ranked_chunks = [int(chunk_ids[index]) for index in order]
            ranked_files: list[str] = []
            seen_files: set[str] = set()
            for index in order:
                path = paths[int(index)]
                if path not in seen_files:
                    seen_files.add(path)
                    ranked_files.append(path)
            results.append(build_evaluation_row(item, ranked_chunks, ranked_files, ks))
        return results

    try:
        from threadpoolctl import threadpool_limits

        blas_context = threadpool_limits(limits=1, user_api="blas")
    except ImportError:
        blas_context = nullcontext()
    with blas_context:
        with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
            groups = pool.map(score_revision, sorted(work_by_revision.items()))
            return [row for group in groups for row in group]


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    here = Path(__file__).resolve().parent
    parser.add_argument("--model", required=True)
    parser.add_argument(
        "--model-profile",
        choices=(
            "voyage",
            "swerank-small",
            "swerank-large",
            "granite",
            "hf-instruct",
            "nemotron-embed",
        ),
        required=True,
    )
    parser.add_argument("--hf-instruct-family", choices=("qwen3", "bge-code"))
    parser.add_argument("--model-tag", required=True)
    parser.add_argument("--final-dir", type=Path, default=here / "final")
    parser.add_argument("--db-dir", type=Path, default=here / "production-db")
    parser.add_argument("--output-dir", type=Path, default=here / "eval")
    parser.add_argument("--vector-cache", type=Path, default=here / "eval-vector-cache")
    parser.add_argument(
        "--derive-truncated-cache",
        type=Path,
        help="Derive this run's vectors by truncating and renormalizing an identical wider cache",
    )
    parser.add_argument(
        "--document-shape",
        choices=("parent-composed", "swerank"),
        default="swerank",
    )
    parser.add_argument("--devices", default="cuda:0")
    parser.add_argument("--expected-gpu-uuid")
    parser.add_argument(
        "--direct-device",
        help="Encode in the main process on this device instead of using a multiprocessing pool",
    )
    parser.add_argument(
        "--load-per-worker-pool",
        action="store_true",
        help="Have each legacy SentenceTransformers worker load the model instead of sharing it",
    )
    parser.add_argument("--max-seq-length", type=int, default=8192)
    parser.add_argument("--truncate-dim", type=int)
    parser.add_argument(
        "--checkpoint-dispatch-texts",
        type=int,
        default=20_000,
        help="Texts per atomic embedding checkpoint inside each length bucket",
    )
    parser.add_argument("--checkpoint-shard-index", type=int, default=0)
    parser.add_argument("--checkpoint-shard-count", type=int, default=1)
    parser.add_argument(
        "--documents-shard-only",
        action="store_true",
        help="Encode this document checkpoint shard and exit before queries/finalization",
    )
    parser.add_argument(
        "--documents-shard-stop-after-batch-size",
        type=int,
        help="Stop a documents-only shard after processing this logical length bucket",
    )
    parser.add_argument("--alpha", type=float, default=1.0)
    parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 1) // 2))
    parser.add_argument("--preflight-only", action="store_true")
    parser.add_argument(
        "--encode-smoke-only",
        action="store_true",
        help="Load the selected embedding model, resolve prompts, encode one query/document, and exit",
    )
    parser.add_argument(
        "--documents-preflight-only",
        action="store_true",
        help="Resolve gold and collect document texts without loading an embedding model",
    )
    parser.add_argument(
        "--function-retrievable-only",
        action="store_true",
        help="Drop chunkless-only queries and remove chunkless gold from mixed queries",
    )
    args = parser.parse_args()
    if not 0.0 <= args.alpha <= 1.0:
        parser.error("--alpha must be between zero and one")
    if args.document_shape == "swerank" and args.alpha != 1.0:
        parser.error("--document-shape swerank requires --alpha 1.0")
    if args.model_profile == "hf-instruct":
        if args.hf_instruct_family is None:
            parser.error("--model-profile hf-instruct requires --hf-instruct-family")
        if args.truncate_dim is not None:
            parser.error("--model-profile hf-instruct leaves truncate_dim native; omit --truncate-dim")
    elif args.hf_instruct_family is not None:
        parser.error("--hf-instruct-family is only valid with --model-profile hf-instruct")
    if args.derive_truncated_cache is not None and args.truncate_dim is None:
        parser.error("--derive-truncated-cache requires --truncate-dim")
    if args.checkpoint_shard_count < 1:
        parser.error("--checkpoint-shard-count must be positive")
    if not 0 <= args.checkpoint_shard_index < args.checkpoint_shard_count:
        parser.error(
            "--checkpoint-shard-index must be between zero and --checkpoint-shard-count"
        )
    if args.checkpoint_shard_count > 1 and not args.documents_shard_only:
        parser.error("--checkpoint sharding requires --documents-shard-only")
    if (
        args.documents_shard_stop_after_batch_size is not None
        and not args.documents_shard_only
    ):
        parser.error(
            "--documents-shard-stop-after-batch-size requires --documents-shard-only"
        )
    validate_cuda_runtime(args.devices.split(","), args.expected_gpu_uuid)
    if args.encode_smoke_only:
        if args.direct_device and args.load_per_worker_pool:
            parser.error("--direct-device and --load-per-worker-pool are mutually exclusive")
        return encode_smoke(args)

    task_rows = read_jsonl(args.final_dir / "tasks.jsonl")
    query_rows = read_jsonl(args.final_dir / "queries.jsonl")
    gold_rows = read_jsonl(args.final_dir / "gold-preimage.jsonl")
    work, gold_audit = resolve_gold_chunks(args.db_dir, query_rows, gold_rows, task_rows)
    print(json.dumps({"event": "gold_resolved", **gold_audit}), flush=True)
    slice_audit = None
    if args.function_retrievable_only:
        work, slice_audit = retain_function_retrievable_queries(work, args.db_dir)
    if args.preflight_only:
        return 0

    document_shape_audit = None
    if args.document_shape == "swerank":
        component_texts, text_index, composes, document_shape_audit = (
            collect_swerank_components(work, args.db_dir)
        )
    else:
        component_texts, text_index, composes = collect_components(work, args.db_dir)
    if args.documents_preflight_only:
        print(
            json.dumps(
                {
                    "event": "documents_preflight_complete",
                    "document_shape": args.document_shape,
                    "unique_texts": len(component_texts),
                    "document_keys": len(text_index),
                    "vectors": len(composes),
                    "document_shape_audit": document_shape_audit,
                }
            ),
            flush=True,
        )
        return 0
    digest = cache_digest(args, work)
    cache_path = args.vector_cache / digest
    docstore_identity = document_cache_identity(args)
    docstore_path = args.vector_cache / "docstore" / docstore_identity
    cached = load_cache(cache_path, composes, work)
    if cached is None and args.derive_truncated_cache is not None:
        derive_truncated_cache(
            args.derive_truncated_cache,
            cache_path,
            composes,
            work,
            args.truncate_dim,
        )
        print(
            json.dumps(
                {
                    "event": "vector_cache_derived",
                    "source": str(args.derive_truncated_cache),
                    "path": str(cache_path),
                    "truncate_dim": args.truncate_dim,
                }
            ),
            flush=True,
        )
        cached = load_cache(cache_path, composes, work)
        if cached is None:
            raise RuntimeError("derived vector cache failed its completeness check")
    if cached is None:
        import torch

        reused_documents = None
        reused_text_index = None
        missing_component_texts = component_texts
        if (
            (docstore_path / "documents.npy").is_file()
            and (docstore_path / "document-keys.json").is_file()
        ):
            (
                reused_documents,
                reused_text_index,
                missing_component_texts,
                docstore_audit,
            ) = reused_document_layout(
                docstore_path,
                component_texts,
                text_index,
                reuse_below_tokens=None,
            )
        else:
            docstore_audit = {
                "base_cache": str(docstore_path.resolve()),
                "base_rows": 0,
                "reused_current_rows": 0,
                "missing_current_rows": len(component_texts),
            }
        print(
            json.dumps(
                {
                    "event": "docstore_reuse",
                    "identity": docstore_identity,
                    "reused": docstore_audit["reused_current_rows"],
                    "missing": docstore_audit["missing_current_rows"],
                    "base_rows": docstore_audit["base_rows"],
                }
            ),
            flush=True,
        )
        print(
            json.dumps(
                {
                    "event": "model_load",
                    "model": args.model,
                    "devices": args.devices.split(","),
                }
            ),
            flush=True,
        )
        model, query_prompt, document_prompt = load_sentence_transformer(args)

        pool = None
        if args.direct_device and args.load_per_worker_pool:
            parser.error("--direct-device and --load-per-worker-pool are mutually exclusive")
        if args.direct_device:
            model.to(args.direct_device)
        elif args.load_per_worker_pool:
            model.to("cpu")
            torch.cuda.empty_cache()
            pool = start_model_loading_pool(
                args.model,
                args.max_seq_length,
                args.devices.split(","),
                args.model_profile,
                args.hf_instruct_family,
                args.truncate_dim,
                resolved_prompt_text(model, query_prompt),
                resolved_prompt_text(model, document_prompt),
            )
        else:
            pool = model.start_multi_process_pool(target_devices=args.devices.split(","))
        try:
            encoded_documents = bucketed_encode(
                model,
                pool,
                missing_component_texts,
                document_prompt,
                cache_path / "partial-documents",
                checkpoint_dispatch_texts=args.checkpoint_dispatch_texts,
                checkpoint_shard_index=args.checkpoint_shard_index,
                checkpoint_shard_count=args.checkpoint_shard_count,
                checkpoint_stop_after_batch_size=(
                    args.documents_shard_stop_after_batch_size
                ),
            )
            if not args.documents_shard_only:
                queries = bucketed_encode(
                    model,
                    pool,
                    [item.query for item in work],
                    query_prompt,
                    cache_path / "partial-queries",
                    checkpoint_dispatch_texts=args.checkpoint_dispatch_texts,
                )
        finally:
            if pool is not None:
                model.stop_multi_process_pool(pool)
        if args.documents_shard_only:
            print(
                json.dumps(
                    {
                        "event": "document_shard_complete",
                        "shard_index": args.checkpoint_shard_index,
                        "shard_count": args.checkpoint_shard_count,
                    }
                ),
                flush=True,
            )
            return 0
        del model
        gc.collect()
        if reused_documents is None:
            documents = DocumentVectors(encoded_documents)
        else:
            documents = DocumentVectors(reused_documents.base, encoded_documents)
            text_index = reused_text_index
        encoded_documents, text_index = materialize_current_document_layout(
            documents, text_index
        )
        documents = DocumentVectors(encoded_documents)
        save_cache(cache_path, encoded_documents, text_index, queries, work)
        update_document_store(docstore_path, documents, text_index)
        print(
            json.dumps({"event": "vector_cache_write", "path": str(cache_path)}),
            flush=True,
        )
    else:
        documents, text_index, queries = cached
        print(json.dumps({"event": "vector_cache_hit", "path": str(cache_path)}), flush=True)

    compose_start = time.monotonic()
    composed, composed_rows = compose_document_matrix(
        documents, text_index, composes, args.alpha, workers=args.workers
    )
    print(
        json.dumps(
            {
                "event": "composition_complete",
                "alpha": args.alpha,
                "vectors": len(composes),
                "seconds": time.monotonic() - compose_start,
                "workers": args.workers,
            }
        ),
        flush=True,
    )
    ks = (1, 3, 5, 10, 15, 20, 30, 50)
    scoring_start = time.monotonic()
    evaluations = score(
        work,
        args.db_dir,
        composed,
        composed_rows,
        queries,
        ks,
        args.workers,
        include_chunkless=args.document_shape == "parent-composed",
    )
    metric_keys = ["mrr", "file_mrr"] + [
        f"{prefix}@{k}"
        for k in ks
        for prefix in ("acc", "recall", "file_acc", "file_recall")
    ]
    metrics, breakdown = nested_macro(evaluations, metric_keys)
    output = {
        "benchmark": "PatchPoint",
        "model": args.model,
        "model_profile": args.model_profile,
        "model_tag": args.model_tag,
        "document_shape": args.document_shape,
        "alpha": args.alpha,
        "max_seq_length": args.max_seq_length,
        "embedding_dimension": int(documents.shape[1]),
        "truncate_dim": args.truncate_dim,
        "aggregation": "macro query-within-task, task-within-repository, repository-within-language, language",
        "counts": {
            "queries": len(evaluations),
            "tasks": len({(row["repo"], row["task_id"]) for row in evaluations}),
            "repositories": len({row["repo"] for row in evaluations}),
            "languages": len({row["language"] for row in evaluations}),
        },
        "gold_resolution": gold_audit,
        "evaluation_slice": slice_audit,
        "document_shape_audit": document_shape_audit,
        "metrics": metrics,
        "breakdown": breakdown,
        "queries": evaluations,
    }
    args.output_dir.mkdir(parents=True, exist_ok=True)
    alpha_tag = f"{args.alpha:g}".replace(".", "")
    output_path = args.output_dir / f"{args.model_tag}-alpha{alpha_tag}.json"
    output_path.write_text(json.dumps(output, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(
        json.dumps(
            {
                "event": "evaluation_complete",
                "output": str(output_path),
                "seconds": time.monotonic() - scoring_start,
                "metrics": metrics,
            }
        ),
        flush=True,
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())