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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
"""Durable, append-only collection API for crowdsourced research events.

The module intentionally exposes only write endpoints plus aggregate health/stats.
Raw records may contain user-provided text and stay quarantined in SQLite until a
separate moderation/export process makes an explicit release decision.
"""

from __future__ import annotations

from src.raw_audio_schema import SCHEMA_SQL as RAW_AUDIO_SCHEMA_SQL, erase_participant_audio

import hashlib
import hmac
import json
import math
import os
import re
import sqlite3
import tempfile
import threading
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Annotated, Any, Literal

from fastapi import APIRouter, Body, Header, HTTPException, Response, status
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator

from src.consent_lineage import (
    IEDID_DATASET_LOCK,
    VERIFIED_CONSENT_PROVENANCE,
    VERIFIED_CONSENT_STATUS,
    canonical_json_list,
    consent_lineage_is_verified,
)
from src.consent_policy import (
    get_current_consent_policy,
    validate_consent_policy_payload,
)


SCHEMA_VERSION = 3
# Existing append-only SQLite tables use storage schema 2 constraints. New
# records keep that physical row version while recording/exporting receipt
# schema 3 explicitly, avoiding an unsafe rewrite of historical event tables.
STORAGE_SCHEMA_VERSION = 2
DB_PATH_ENV = "COLLECTION_DB_PATH"
COMPAT_DB_PATH_ENVS = ("COLLECTION_V2_DB_PATH", "PUREPOLYGLOT_COLLECTION_DB")
ALLOW_EPHEMERAL_DB_ENV = "ALLOW_EPHEMERAL_COLLECTION"
SQLITE_JOURNAL_MODE_ENV = "COLLECTION_SQLITE_JOURNAL_MODE"
SUPPORTED_SQLITE_JOURNAL_MODES = frozenset({"WAL", "DELETE"})
IDEMPOTENCY_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$"
PARTICIPANT_PATTERN = re.compile(r"^participant_[0-9a-f]{32}$")
WALLET_PATTERN = re.compile(r"^0x[0-9a-fA-F]{40,64}$")
PARTICIPANT_TOKEN_PATTERN = r"^[A-Za-z0-9_-]{43,128}$"
SUBMISSION_METADATA_KEYS = frozenset(
    {
        "tone",
        "context",
        "pragmatics",
        "source_tag",
        "edit_ratios",
        "transcript_edit_ratio",
        "meaning_edit_ratio",
        "audio_sanitation",
        "voice_privacy_mode",
        "room_type",
        "title",
        "mission_subtext",
        "chat_mode",
        "output_semantics",
        "mode",
        "clarification_source",
    }
)
SENSITIVE_METADATA_VALUE_PATTERNS = (
    re.compile(r"0x[0-9a-fA-F]{40,64}"),
    re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"),
    re.compile(r"(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)"),
    re.compile(r"(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43,128}(?![A-Za-z0-9_-])"),
)

router = APIRouter(prefix="/api/v2", tags=["crowdsourcing-v2"])

# Shared with backend/api.py so old and v2 writers cannot race during the
# transition period while Pending Audit still consumes pending_approvals.csv.
PENDING_QUEUE_LOCK = threading.Lock()

# Withdrawal CSVs retain only random server locators and the minimum receipt/
# propagation evidence needed to prove that a release was revoked. Every other
# column is contribution or provenance data and is scrubbed fail-closed, which
# also protects future columns that are not yet known to this module.
_TOMBSTONE_AUDIT_COLUMNS = frozenset(
    {
        "Queue_ID",
        "Submission_ID",
        "Consent_ID",
        "Schema_Version",
        "Consent_Status",
        "Consent_Provenance",
        "Consent_Recorded_At",
        "Consent_Text_SHA256",
        "Consent_Record_SHA256",
        "Consent_Schema_Version",
        "Submission_Status",
        "Review_Status",
        "Release_Eligible",
        "Ethics_Review_Status",
        "Withdrawal_Request_ID",
        "Withdrawal_Requested_At",
        "Deletion_Propagation_Status",
        "Audio_Deletion_Status",
    }
)
_TOMBSTONE_TEXT_COLUMNS = frozenset(
    {
        "Utterance",
        "Clarification",
        "Tone",
        "Tone_Category",
        "Context",
        "Linguistic_Context",
        "Pragmatic_Analysis",
        "Syntax_Pattern",
        "Acoustic_Profile",
        "Prompt_Text",
        "Preceding_Context",
        "Source_Text",
        "Machine_Transcript_Initial",
        "User_Transcript_Final",
        "Machine_Translation_Initial",
        "Machine_Output_Initial",
        "User_Translation_Final",
        "User_Output_Final",
        "Metadata_JSON",
    }
)


def _scrub_tombstoned_csv_rows(frame: Any, mask: Any, marker: str) -> None:
    """Scrub every non-audit column for selected contribution rows."""
    for column in frame.columns:
        if column in _TOMBSTONE_AUDIT_COLUMNS:
            continue
        frame.loc[mask, column] = (
            marker if column in _TOMBSTONE_TEXT_COLUMNS else ""
        )

IdempotencyKey = Annotated[
    str,
    Header(
        alias="Idempotency-Key",
        min_length=8,
        max_length=128,
        pattern=IDEMPOTENCY_PATTERN,
        description="Stable client-generated key for safe retries.",
    ),
]

ParticipantToken = Annotated[
    str,
    Header(
        alias="X-Participant-Token",
        min_length=43,
        max_length=128,
        pattern=PARTICIPANT_TOKEN_PATTERN,
        description="Client-held secret that authenticates a pseudonymous participant.",
    ),
]


def _utc_now() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace(
        "+00:00", "Z"
    )


def _new_id(prefix: str) -> str:
    return f"{prefix}_{uuid.uuid4().hex}"


def _canonical_json(value: Any) -> str:
    return json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    )


def _request_hash(value: Any) -> str:
    return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest()


def _validate_participant_id(value: str) -> str:
    value = value.strip()
    if not PARTICIPANT_PATTERN.fullmatch(value):
        raise ValueError(
            "participant_id must be participant_ followed by 32 lowercase hex characters"
        )
    if WALLET_PATTERN.fullmatch(value) or "@" in value:
        raise ValueError(
            "participant_id must be a revocable pseudonym, not a wallet or email"
        )
    return value


class StrictModel(BaseModel):
    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)


class ConsentCreate(StrictModel):
    participant_id: str = Field(min_length=8, max_length=128)
    withdrawal_token_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    app_id: str = Field(min_length=2, max_length=64)
    app_version: str = Field(min_length=1, max_length=64)
    consent_version: str = Field(min_length=1, max_length=128)
    privacy_notice_version: str = Field(min_length=1, max_length=128)
    dataset_license: str = Field(min_length=1, max_length=128)
    permitted_modalities: list[
        Literal["text", "speech", "image", "multimodal", "judgment", "telemetry"]
    ] = Field(min_length=1, max_length=6)
    consent_surface: str = Field(min_length=2, max_length=128)
    consent_locale: str = Field(
        min_length=2,
        max_length=35,
        pattern=r"^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$",
    )
    consent_text_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    research_purposes: list[str] = Field(min_length=1, max_length=12)
    retention_policy_version: str = Field(min_length=1, max_length=128)
    withdrawal_policy_version: str = Field(min_length=1, max_length=128)
    eligibility_confirmed: Literal[True]
    public_release_confirmed: Literal[True]
    commercial_ai_reuse_confirmed: Literal[True]
    privacy_risks_acknowledged: Literal[True]
    operational_processing_acknowledged: Literal[True]
    voluntary_participation_confirmed: Literal[True]
    contribution_rights_confirmed: Literal[True]
    raw_audio_consent: bool = False
    data_controller_name: str = Field(min_length=2, max_length=200)
    data_controller_contact: str = Field(min_length=3, max_length=256)
    data_recipient_categories: list[str] = Field(min_length=1, max_length=12)
    consent_granted: Literal[True]

    _participant_is_pseudonymous = field_validator("participant_id")(
        _validate_participant_id
    )

    @field_validator("permitted_modalities")
    @classmethod
    def normalize_modalities(cls, value: list[str]) -> list[str]:
        return sorted(set(value))

    @field_validator("research_purposes", "data_recipient_categories")
    @classmethod
    def normalize_policy_lists(cls, value: list[str]) -> list[str]:
        normalized = sorted({item.strip() for item in value if item.strip()})
        if not normalized:
            raise ValueError("policy list must contain at least one non-empty value")
        if any(len(item) > 128 for item in normalized):
            raise ValueError("policy list values must not exceed 128 characters")
        return normalized

    @model_validator(mode="after")
    def policy_is_registered(self) -> "ConsentCreate":
        validate_consent_policy_payload(self.model_dump(mode="json"))
        return self


class SubmissionCreate(StrictModel):
    participant_id: str = Field(min_length=8, max_length=128)
    consent_id: str = Field(pattern=r"^cns_[0-9a-f]{32}$")
    app_id: str = Field(min_length=2, max_length=64)
    app_version: str = Field(min_length=1, max_length=64)
    game_id: str = Field(min_length=2, max_length=64)
    task_id: str = Field(min_length=1, max_length=128)
    prompt_text: str | None = Field(default=None, max_length=20_000)
    topic_id: str | None = Field(default=None, max_length=128)
    image_asset_id: str | None = Field(default=None, max_length=256)
    conversation_id: str | None = Field(default=None, max_length=128)
    turn_id: str | None = Field(default=None, max_length=128)
    preceding_context: str | None = Field(default=None, max_length=40_000)
    source_text: str | None = Field(default=None, max_length=20_000)
    source_language: str = Field(min_length=1, max_length=128)
    source_dialect: str = Field(min_length=1, max_length=256)
    target_language: str = Field(min_length=1, max_length=128)
    target_dialect: str = Field(min_length=1, max_length=256)
    input_modality: Literal["text", "speech", "image", "multimodal"]
    machine_transcript_initial: str | None = Field(default=None, max_length=20_000)
    user_transcript_final: str | None = Field(default=None, max_length=20_000)
    machine_output_initial: str | None = Field(default=None, max_length=20_000)
    user_output_final: str | None = Field(default=None, max_length=20_000)
    model_name: str | None = Field(default=None, max_length=128)
    model_version: str | None = Field(default=None, max_length=128)
    asr_model: str | None = Field(default=None, max_length=128)
    translation_route: str | None = Field(default=None, max_length=128)
    metadata: dict[str, Any] = Field(default_factory=dict)
    started_at: datetime | None = None
    duration_ms: int | None = Field(default=None, ge=0, le=86_400_000)

    _participant_is_pseudonymous = field_validator("participant_id")(
        _validate_participant_id
    )

    @field_validator("metadata")
    @classmethod
    def metadata_is_minimized(cls, value: dict[str, Any]) -> dict[str, Any]:
        unknown = sorted(set(value) - SUBMISSION_METADATA_KEYS)
        if unknown:
            raise ValueError(
                "metadata contains non-allowlisted keys: " + ", ".join(unknown)
            )
        normalized: dict[str, Any] = {}
        for key, item in value.items():
            if item is None or isinstance(item, bool):
                normalized[key] = item
                continue
            if isinstance(item, (int, float)) and not isinstance(item, bool):
                if not math.isfinite(float(item)):
                    raise ValueError(f"metadata.{key} must be finite")
                normalized[key] = item
                continue
            if not isinstance(item, str):
                raise ValueError(f"metadata.{key} must be a bounded scalar")
            if len(item) > 2048:
                raise ValueError(f"metadata.{key} exceeds 2048 characters")
            if any(pattern.search(item) for pattern in SENSITIVE_METADATA_VALUE_PATTERNS):
                raise ValueError(
                    f"metadata.{key} appears to contain a private identifier or token"
                )
            normalized[key] = item
        return normalized

    @field_validator("started_at")
    @classmethod
    def started_at_has_timezone(cls, value: datetime | None) -> datetime | None:
        if value is not None and value.tzinfo is None:
            raise ValueError("started_at must include a timezone")
        return value

    @field_validator("metadata")
    @classmethod
    def metadata_is_bounded(cls, value: dict[str, Any]) -> dict[str, Any]:
        try:
            serialized = _canonical_json(value).encode("utf-8")
        except (TypeError, ValueError) as exc:
            raise ValueError("metadata must be JSON serializable") from exc
        if len(serialized) > 16 * 1024:
            raise ValueError("metadata must not exceed 16 KiB when serialized")
        return value

    @model_validator(mode="after")
    def has_human_contribution(self) -> "SubmissionCreate":
        if not any(
            value and value.strip()
            for value in (
                self.source_text,
                self.user_transcript_final,
                self.user_output_final,
            )
        ):
            raise ValueError("at least one human-provided text field is required")
        if self.input_modality == "image" and not self.image_asset_id:
            raise ValueError("image_asset_id is required for image submissions")
        if self.turn_id and not self.conversation_id:
            raise ValueError("conversation_id is required when turn_id is provided")
        return self


class JudgmentCreate(StrictModel):
    participant_id: str = Field(min_length=8, max_length=128)
    consent_id: str = Field(pattern=r"^cns_[0-9a-f]{32}$")
    submission_id: str = Field(pattern=r"^sub_[0-9a-f]{32}$")
    task_id: str = Field(min_length=1, max_length=128)
    choice: Literal[
        "candidate_a",
        "candidate_b",
        "tie",
        "both_good",
        "both_bad",
        "accept",
        "edit",
        "challenge",
        "skip",
    ]
    error_span: str | None = Field(default=None, max_length=4_000)
    error_type: Literal[
        "meaning",
        "omission",
        "fluency",
        "tone",
        "register",
        "dialect",
        "safety",
        "other",
    ] | None = None
    correction: str | None = Field(default=None, max_length=20_000)
    confidence: float | None = Field(default=None, ge=0.0, le=1.0)
    latency_ms: int | None = Field(default=None, ge=0, le=86_400_000)

    _participant_is_pseudonymous = field_validator("participant_id")(
        _validate_participant_id
    )

    @model_validator(mode="after")
    def correction_matches_choice(self) -> "JudgmentCreate":
        if self.choice == "edit" and not self.correction:
            raise ValueError("correction is required when choice is edit")
        return self


class DeletionRequestCreate(StrictModel):
    reason: Literal[
        "participant_request", "consent_withdrawal", "privacy_concern", "other"
    ] = "participant_request"
    scope: Literal["all"] = "all"


class ConsentReceipt(StrictModel):
    consent_id: str
    recorded_at: str
    consent_record_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    consent_text_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    receipt_schema_version: int
    consent_version: str
    permitted_modalities: list[
        Literal["text", "speech", "image", "multimodal", "judgment", "telemetry"]
    ]
    consent_status: Literal["verified_v2"]
    consent_provenance: Literal["collection_v2_server_receipt"]
    idempotent_replay: bool


class SubmissionReceipt(StrictModel):
    submission_id: str
    submitted_at: str
    moderation_status: Literal["pending"]
    review_status: Literal["pending"]
    release_eligible: Literal[False]
    pending_queue_id: str
    pending_audit_status: Literal[
        "mirrored", "retry_pending", "withdrawn_not_mirrored"
    ]
    idempotent_replay: bool


class JudgmentReceipt(StrictModel):
    judgment_id: str
    recorded_at: str
    idempotent_replay: bool


class DeletionReceipt(StrictModel):
    deletion_request_id: str
    requested_at: str
    status: Literal["pending"]
    tombstoned: Literal[True]
    hard_deleted: Literal[False]
    raw_audio_active_payloads: Literal["erased"] = "erased"
    raw_audio_backup_erasure: Literal["not_attested"] = "not_attested"
    local_pending_audit_status: Literal["tombstoned", "retry_pending"]
    local_iedid_status: Literal["tombstoned", "retry_pending"]
    remote_export_status: Literal["propagation_pending"]
    private_pending_mirror_status: Literal["propagation_pending"] = (
        "propagation_pending"
    )
    propagation_pending: Literal[True]
    idempotent_replay: bool


class IdempotencyConflict(Exception):
    pass


class ParticipantTombstoned(Exception):
    pass


class ConsentError(Exception):
    pass


class StorageConfigurationError(Exception):
    pass


class MissingResource(Exception):
    pass


SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS schema_meta (
    schema_version INTEGER PRIMARY KEY,
    installed_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS consents (
    consent_id TEXT PRIMARY KEY,
    schema_version INTEGER NOT NULL CHECK (schema_version = 2),
    receipt_schema_version INTEGER NOT NULL CHECK (receipt_schema_version = 3),
    participant_id TEXT NOT NULL,
    app_id TEXT,
    app_version TEXT,
    consent_version TEXT NOT NULL,
    privacy_notice_version TEXT NOT NULL,
    dataset_license TEXT NOT NULL,
    permitted_modalities_json TEXT NOT NULL,
    consent_surface TEXT NOT NULL,
    consent_locale TEXT NOT NULL,
    consent_text_sha256 TEXT NOT NULL,
    research_purposes_json TEXT NOT NULL,
    retention_policy_version TEXT NOT NULL,
    withdrawal_policy_version TEXT NOT NULL,
    eligibility_confirmed INTEGER NOT NULL CHECK (eligibility_confirmed = 1),
    public_release_confirmed INTEGER NOT NULL CHECK (public_release_confirmed = 1),
    commercial_ai_reuse_confirmed INTEGER NOT NULL CHECK (commercial_ai_reuse_confirmed = 1),
    privacy_risks_acknowledged INTEGER NOT NULL CHECK (privacy_risks_acknowledged = 1),
    operational_processing_acknowledged INTEGER NOT NULL CHECK (operational_processing_acknowledged = 1),
    voluntary_participation_confirmed INTEGER NOT NULL CHECK (voluntary_participation_confirmed = 1),
    contribution_rights_confirmed INTEGER NOT NULL CHECK (contribution_rights_confirmed = 1),
    raw_audio_consent INTEGER NOT NULL CHECK (raw_audio_consent IN (0, 1)),
    data_controller_name TEXT NOT NULL,
    data_controller_contact TEXT NOT NULL,
    data_recipient_categories_json TEXT NOT NULL,
    withdrawal_token_sha256 TEXT NOT NULL,
    consent_status TEXT NOT NULL CHECK (consent_status = 'verified_v2'),
    consent_provenance TEXT NOT NULL CHECK (
        consent_provenance = 'collection_v2_server_receipt'
    ),
    consent_granted INTEGER NOT NULL CHECK (consent_granted = 1),
    recorded_at TEXT NOT NULL,
    request_sha256 TEXT NOT NULL,
    record_sha256 TEXT NOT NULL,
    record_json TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS submissions (
    submission_id TEXT PRIMARY KEY,
    schema_version INTEGER NOT NULL CHECK (schema_version = 2),
    participant_id TEXT NOT NULL,
    consent_id TEXT NOT NULL REFERENCES consents(consent_id),
    app_id TEXT NOT NULL,
    app_version TEXT NOT NULL,
    game_id TEXT NOT NULL,
    task_id TEXT NOT NULL,
    prompt_text TEXT,
    topic_id TEXT,
    image_asset_id TEXT,
    conversation_id TEXT,
    turn_id TEXT,
    preceding_context TEXT,
    source_text TEXT,
    source_language TEXT NOT NULL,
    source_dialect TEXT NOT NULL,
    target_language TEXT NOT NULL,
    target_dialect TEXT NOT NULL,
    input_modality TEXT NOT NULL,
    machine_transcript_initial TEXT,
    user_transcript_final TEXT,
    machine_output_initial TEXT,
    user_output_final TEXT,
    model_name TEXT,
    model_version TEXT,
    asr_model TEXT,
    translation_route TEXT,
    metadata_json TEXT NOT NULL,
    started_at TEXT,
    submitted_at TEXT NOT NULL,
    duration_ms INTEGER,
    moderation_status TEXT NOT NULL CHECK (moderation_status = 'pending'),
    review_status TEXT NOT NULL CHECK (review_status = 'pending'),
    release_eligible INTEGER NOT NULL CHECK (release_eligible = 0),
    request_sha256 TEXT NOT NULL,
    record_json TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS judgments (
    judgment_id TEXT PRIMARY KEY,
    schema_version INTEGER NOT NULL CHECK (schema_version = 2),
    participant_id TEXT NOT NULL,
    consent_id TEXT NOT NULL REFERENCES consents(consent_id),
    submission_id TEXT NOT NULL REFERENCES submissions(submission_id),
    task_id TEXT NOT NULL,
    choice TEXT NOT NULL,
    error_span TEXT,
    error_type TEXT,
    correction TEXT,
    confidence REAL,
    latency_ms INTEGER,
    gold_item INTEGER NOT NULL DEFAULT 0 CHECK (gold_item = 0),
    gold_result TEXT,
    recorded_at TEXT NOT NULL,
    release_eligible INTEGER NOT NULL CHECK (release_eligible = 0),
    request_sha256 TEXT NOT NULL,
    record_json TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS deletion_requests (
    deletion_request_id TEXT PRIMARY KEY,
    schema_version INTEGER NOT NULL CHECK (schema_version = 2),
    participant_id TEXT NOT NULL,
    reason TEXT NOT NULL,
    scope TEXT NOT NULL CHECK (scope = 'all'),
    requested_at TEXT NOT NULL,
    status TEXT NOT NULL CHECK (status = 'pending'),
    tombstoned INTEGER NOT NULL CHECK (tombstoned = 1),
    hard_deleted INTEGER NOT NULL CHECK (hard_deleted = 0),
    request_sha256 TEXT NOT NULL,
    record_json TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS idempotency_keys (
    operation TEXT NOT NULL,
    idempotency_key TEXT NOT NULL,
    request_sha256 TEXT NOT NULL,
    resource_type TEXT NOT NULL,
    resource_id TEXT NOT NULL,
    response_json TEXT NOT NULL,
    created_at TEXT NOT NULL,
    PRIMARY KEY (operation, idempotency_key)
);

CREATE TABLE IF NOT EXISTS pending_audit_outbox (
    outbox_id TEXT PRIMARY KEY,
    submission_id TEXT NOT NULL UNIQUE REFERENCES submissions(submission_id),
    queue_id TEXT NOT NULL UNIQUE,
    pending_row_json TEXT NOT NULL,
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS pending_audit_attempts (
    attempt_id TEXT PRIMARY KEY,
    outbox_id TEXT NOT NULL REFERENCES pending_audit_outbox(outbox_id),
    attempted_at TEXT NOT NULL,
    succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
    error_code TEXT
);

CREATE TABLE IF NOT EXISTS deletion_propagation_outbox (
    action_id TEXT PRIMARY KEY,
    deletion_request_id TEXT NOT NULL REFERENCES deletion_requests(deletion_request_id),
    participant_id TEXT NOT NULL,
    target TEXT NOT NULL CHECK (target IN ('pending_audit_csv', 'huggingface_export')),
    action TEXT NOT NULL CHECK (action = 'tombstone_participant_records'),
    payload_json TEXT NOT NULL,
    created_at TEXT NOT NULL,
    UNIQUE (deletion_request_id, target)
);

CREATE TABLE IF NOT EXISTS deletion_propagation_attempts (
    attempt_id TEXT PRIMARY KEY,
    action_id TEXT NOT NULL REFERENCES deletion_propagation_outbox(action_id),
    attempted_at TEXT NOT NULL,
    succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
    error_code TEXT
);

CREATE TABLE IF NOT EXISTS iedid_deletion_outbox (
    action_id TEXT PRIMARY KEY,
    deletion_request_id TEXT NOT NULL UNIQUE REFERENCES deletion_requests(deletion_request_id),
    participant_id TEXT NOT NULL,
    consent_ids_json TEXT NOT NULL,
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS iedid_deletion_attempts (
    attempt_id TEXT PRIMARY KEY,
    action_id TEXT NOT NULL REFERENCES iedid_deletion_outbox(action_id),
    attempted_at TEXT NOT NULL,
    succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
    error_code TEXT
);

CREATE INDEX IF NOT EXISTS idx_consents_participant
    ON consents(participant_id, recorded_at);
CREATE INDEX IF NOT EXISTS idx_submissions_participant
    ON submissions(participant_id, submitted_at);
CREATE INDEX IF NOT EXISTS idx_submissions_task
    ON submissions(app_id, game_id, task_id);
CREATE INDEX IF NOT EXISTS idx_judgments_submission
    ON judgments(submission_id, recorded_at);
CREATE INDEX IF NOT EXISTS idx_judgments_participant
    ON judgments(participant_id, recorded_at);
CREATE INDEX IF NOT EXISTS idx_deletions_participant
    ON deletion_requests(participant_id, requested_at);
"""

APPEND_ONLY_TABLES = (
    "consents",
    "submissions",
    "judgments",
    "deletion_requests",
    "idempotency_keys",
    "pending_audit_outbox",
    "pending_audit_attempts",
    "deletion_propagation_outbox",
    "deletion_propagation_attempts",
    "iedid_deletion_outbox",
    "iedid_deletion_attempts",
)

# Existing v2 databases predate the complete ethical-policy receipt. SQLite
# cannot add NOT NULL columns without inventing defaults, so migrations append
# nullable columns. Old receipts consequently remain explicitly unverified;
# only newly inserted receipts populate the complete policy snapshot.
CONSENT_COLUMN_MIGRATIONS = {
    "consent_surface": "TEXT",
    "receipt_schema_version": "INTEGER",
    "consent_locale": "TEXT",
    "consent_text_sha256": "TEXT",
    "research_purposes_json": "TEXT",
    "retention_policy_version": "TEXT",
    "withdrawal_policy_version": "TEXT",
    "eligibility_confirmed": "INTEGER",
    "public_release_confirmed": "INTEGER",
    "commercial_ai_reuse_confirmed": "INTEGER",
    "privacy_risks_acknowledged": "INTEGER",
    "operational_processing_acknowledged": "INTEGER",
    "voluntary_participation_confirmed": "INTEGER",
    "contribution_rights_confirmed": "INTEGER",
    "raw_audio_consent": "INTEGER",
    "data_controller_name": "TEXT",
    "data_controller_contact": "TEXT",
    "data_recipient_categories_json": "TEXT",
    "withdrawal_token_sha256": "TEXT",
    "consent_status": "TEXT",
    "consent_provenance": "TEXT",
    "record_sha256": "TEXT",
}


def _configured_db_path() -> Path | None:
    configured = os.environ.get(DB_PATH_ENV, "").strip()
    if not configured:
        configured = next(
            (
                os.environ.get(name, "").strip()
                for name in COMPAT_DB_PATH_ENVS
                if os.environ.get(name, "").strip()
            ),
            "",
        )
    if configured:
        if configured == ":memory:":
            raise StorageConfigurationError(
                f"{DB_PATH_ENV} must name a durable file, not an in-memory database"
            )
        return Path(configured).expanduser().resolve()
    return None


def _default_db_path() -> Path:
    configured = _configured_db_path()
    if configured is not None:
        return configured

    if os.environ.get(ALLOW_EPHEMERAL_DB_ENV, "").strip().casefold() != "true":
        raise StorageConfigurationError(
            "Crowdsourced collection is unavailable until COLLECTION_DB_PATH "
            "is explicitly configured on persistent storage. Set "
            "ALLOW_EPHEMERAL_COLLECTION=true only for disposable development "
            "or tests."
        )

    return (
        Path(tempfile.gettempdir())
        / "purepolyglot"
        / "collection_v2.sqlite3"
    ).resolve()


def _configured_sqlite_journal_mode() -> str:
    mode = os.environ.get(SQLITE_JOURNAL_MODE_ENV, "WAL").strip().upper() or "WAL"
    if mode not in SUPPORTED_SQLITE_JOURNAL_MODES:
        raise StorageConfigurationError(
            f"{SQLITE_JOURNAL_MODE_ENV} must be WAL for local POSIX storage or "
            "DELETE for a tested single-writer network volume"
        )
    return mode


def _pending_queue_path() -> Path:
    configured = os.environ.get("PENDING_APPROVALS_FILE", "").strip()
    if configured:
        return Path(configured).expanduser().resolve()
    if Path("/app").exists():
        return Path("/app/pending_approvals.csv")
    return Path("pending_approvals.csv").resolve()


def _iedid_dataset_path() -> Path:
    configured = (
        os.environ.get("IEDID_DATASET_DIR", "").strip()
        or os.environ.get("DATASET_DIR", "").strip()
    )
    if configured:
        return Path(configured).expanduser().resolve()
    if Path("/app/IEDID").exists():
        return Path("/app/IEDID")
    return (Path(__file__).resolve().parents[1] / "IEDID").resolve()


def _consent_snapshot(consent: sqlite3.Row) -> dict[str, str]:
    """Build the immutable dataset lineage from an authoritative DB receipt."""
    keys = set(consent.keys())

    def value(column: str) -> Any:
        return consent[column] if column in keys else None

    def json_list(column: str) -> str:
        raw = value(column)
        if not raw:
            return ""
        try:
            parsed = json.loads(raw)
        except (TypeError, ValueError, json.JSONDecodeError):
            return ""
        if not isinstance(parsed, list) or not all(
            isinstance(item, str) and item for item in parsed
        ):
            return ""
        return canonical_json_list(parsed)

    candidate = {
        "Consent_ID": str(value("consent_id") or ""),
        "Consent_Status": str(value("consent_status") or "legacy_unverified"),
        "Consent_Provenance": str(
            value("consent_provenance") or "legacy_incomplete_v2_receipt"
        ),
        "Consent_Confirmed": "true" if value("consent_granted") == 1 else "",
        "Consent_Version": str(value("consent_version") or ""),
        "Consent_Recorded_At": str(value("recorded_at") or ""),
        "Privacy_Notice_Version": str(value("privacy_notice_version") or ""),
        "Dataset_License": str(value("dataset_license") or ""),
        "Permitted_Modalities": json_list("permitted_modalities_json"),
        "Consent_Surface": str(value("consent_surface") or ""),
        "Consent_Locale": str(value("consent_locale") or ""),
        "Consent_Text_SHA256": str(value("consent_text_sha256") or ""),
        "Consent_Record_SHA256": str(value("record_sha256") or ""),
        "Consent_Schema_Version": str(value("receipt_schema_version") or ""),
        "Research_Purposes": json_list("research_purposes_json"),
        "Retention_Policy_Version": str(
            value("retention_policy_version") or ""
        ),
        "Withdrawal_Policy_Version": str(
            value("withdrawal_policy_version") or ""
        ),
        "Eligibility_Confirmed": (
            "true" if value("eligibility_confirmed") == 1 else ""
        ),
        "Public_Release_Confirmed": (
            "true" if value("public_release_confirmed") == 1 else ""
        ),
        "Commercial_AI_Reuse_Confirmed": (
            "true" if value("commercial_ai_reuse_confirmed") == 1 else ""
        ),
        "Privacy_Risks_Acknowledged": (
            "true" if value("privacy_risks_acknowledged") == 1 else ""
        ),
        "Operational_Processing_Acknowledged": (
            "true" if value("operational_processing_acknowledged") == 1 else ""
        ),
        "Voluntary_Participation_Confirmed": (
            "true" if value("voluntary_participation_confirmed") == 1 else ""
        ),
        "Contribution_Rights_Confirmed": (
            "true" if value("contribution_rights_confirmed") == 1 else ""
        ),
        "Raw_Audio_Consent": (
            "true"
            if value("raw_audio_consent") == 1
            else "false"
            if value("raw_audio_consent") == 0
            else ""
        ),
        "Data_Controller_Name": str(value("data_controller_name") or ""),
        "Data_Controller_Contact": str(value("data_controller_contact") or ""),
        "Data_Recipient_Categories": json_list(
            "data_recipient_categories_json"
        ),
    }
    if not consent_lineage_is_verified(candidate):
        candidate["Consent_Status"] = "legacy_unverified"
        if candidate["Consent_Provenance"] == VERIFIED_CONSENT_PROVENANCE:
            candidate["Consent_Provenance"] = "legacy_incomplete_v2_receipt"
    return candidate


def _legacy_pending_row(
    payload: SubmissionCreate,
    submission_id: str,
    queue_id: str,
    submitted_at: str,
    consent_snapshot: dict[str, str],
) -> dict[str, Any]:
    metadata = payload.metadata
    final_utterance = payload.user_transcript_final or payload.source_text or ""
    final_output = payload.user_output_final or payload.machine_output_initial or ""
    context_parts = [
        payload.prompt_text or "",
        payload.preceding_context or "",
    ]
    context = str(metadata.get("context") or " | ".join(
        part for part in context_parts if part
    ))
    return {
        # Fields consumed by the current Pending Audit UI.
        "User": payload.participant_id,
        "Data_Origin": str(metadata.get("source_tag") or f"Game: {payload.game_id}"),
        "Utterance": final_utterance,
        "Dialect": payload.target_dialect,
        "Clarification": final_output,
        "Clarification_Source": "Schema v2 crowdsourcing submission",
        "Tone": str(metadata.get("tone") or ""),
        "Context": context,
        "Pragmatic_Analysis": str(metadata.get("pragmatics") or ""),
        "Audio": "",
        "Timestamp": submitted_at,
        "Chain_ID": "",
        "Approvers": "",
        "Language": payload.target_language,
        # Stable bridge fields make the mirror idempotent and auditable.
        "Queue_ID": queue_id,
        "Participant_ID": payload.participant_id,
        "Submission_ID": submission_id,
        "Interaction_ID": payload.task_id,
        "Schema_Version": str(SCHEMA_VERSION),
        "App_Source": payload.app_id,
        "App_Version": payload.app_version,
        "Game_ID": payload.game_id,
        "Task_ID": payload.task_id,
        "Source_App_ID": payload.app_id,
        "Source_App_Version": payload.app_version,
        "Source_Game_ID": payload.game_id,
        "Collected_At": submitted_at,
        "Submission_Status": "Pending Review",
        **consent_snapshot,
        "Source_Language": payload.source_language,
        "Source_Dialect": payload.source_dialect,
        "Source_Input_Mode": payload.input_modality,
        "Machine_Transcript_Initial": payload.machine_transcript_initial or "",
        "User_Transcript_Final": payload.user_transcript_final or "",
        "Target_Language": payload.target_language,
        "Target_Dialect": payload.target_dialect,
        "Machine_Translation_Initial": payload.machine_output_initial or "",
        "User_Translation_Final": payload.user_output_final or "",
        "AI_Model": payload.model_name or "",
        "AI_Model_Version": payload.model_version or "",
        "ASR_Model": payload.asr_model or "",
        "Translation_Route": payload.translation_route or "",
        "Metadata_JSON": _canonical_json(payload.metadata),
        "Prompt_Text": payload.prompt_text or "",
        "Topic_ID": payload.topic_id or "",
        "Image_Asset_ID": payload.image_asset_id or "",
        "Conversation_ID": payload.conversation_id or "",
        "Turn_ID": payload.turn_id or "",
        "Review_Submitted_At": submitted_at,
        "Release_Eligible": "false",
        "Ethics_Review_Status": "pending_moderation",
        "Withdrawal_Request_ID": "",
        "Withdrawal_Requested_At": "",
        "Deletion_Propagation_Status": "not_requested",
    }


class CollectionStore:
    """Small SQLite event store using one transaction per API mutation."""

    def __init__(self, path: Path):
        self.path = path
        self._initialize_lock = threading.Lock()
        self._initialized = False

    def _connect(self) -> sqlite3.Connection:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        connection = sqlite3.connect(
            str(self.path),
            timeout=30,
            isolation_level=None,
        )
        connection.row_factory = sqlite3.Row
        connection.execute("PRAGMA foreign_keys = ON")
        connection.execute("PRAGMA busy_timeout = 30000")
        requested_journal_mode = _configured_sqlite_journal_mode()
        actual_journal_mode = connection.execute(
            f"PRAGMA journal_mode = {requested_journal_mode}"
        ).fetchone()[0]
        if str(actual_journal_mode).upper() != requested_journal_mode:
            connection.close()
            raise StorageConfigurationError(
                "The configured storage does not support the requested SQLite "
                f"journal mode {requested_journal_mode}"
            )
        connection.execute("PRAGMA synchronous = FULL")
        return connection

    def initialize(self) -> None:
        if self._initialized:
            return
        with self._initialize_lock:
            if self._initialized:
                return
            with self._connect() as connection:
                connection.execute("BEGIN IMMEDIATE")
                try:
                    connection.executescript(SCHEMA_SQL + "\n" + RAW_AUDIO_SCHEMA_SQL)
                    consent_columns = {
                        row["name"]
                        for row in connection.execute(
                            "PRAGMA table_info(consents)"
                        ).fetchall()
                    }
                    for column, sql_type in CONSENT_COLUMN_MIGRATIONS.items():
                        if column not in consent_columns:
                            connection.execute(
                                f"ALTER TABLE consents ADD COLUMN {column} {sql_type}"
                            )
                    connection.execute(
                        "INSERT OR IGNORE INTO schema_meta(schema_version, installed_at) "
                        "VALUES (?, ?)",
                        (SCHEMA_VERSION, _utc_now()),
                    )
                    for table in APPEND_ONLY_TABLES:
                        connection.executescript(
                            f"""
                            CREATE TRIGGER IF NOT EXISTS {table}_prevent_update
                            BEFORE UPDATE ON {table}
                            BEGIN
                                SELECT RAISE(ABORT, '{table} is append-only');
                            END;
                            CREATE TRIGGER IF NOT EXISTS {table}_prevent_delete
                            BEFORE DELETE ON {table}
                            BEGIN
                                SELECT RAISE(ABORT, '{table} is append-only');
                            END;
                            """
                        )
                    connection.commit()
                except Exception:
                    connection.rollback()
                    raise
            self._initialized = True

    @staticmethod
    def _begin(connection: sqlite3.Connection) -> None:
        connection.execute("BEGIN IMMEDIATE")

    @staticmethod
    def _idempotent_replay(
        connection: sqlite3.Connection,
        operation: str,
        idempotency_key: str,
        request_sha256: str,
    ) -> dict[str, Any] | None:
        row = connection.execute(
            "SELECT request_sha256, response_json FROM idempotency_keys "
            "WHERE operation = ? AND idempotency_key = ?",
            (operation, idempotency_key),
        ).fetchone()
        if row is None:
            return None
        if row["request_sha256"] != request_sha256:
            raise IdempotencyConflict(
                "Idempotency-Key was already used with a different request"
            )
        response = json.loads(row["response_json"])
        response["idempotent_replay"] = True
        return response

    @staticmethod
    def _record_idempotency(
        connection: sqlite3.Connection,
        operation: str,
        idempotency_key: str,
        request_sha256: str,
        resource_type: str,
        resource_id: str,
        response_body: dict[str, Any],
        created_at: str,
    ) -> None:
        connection.execute(
            "INSERT INTO idempotency_keys "
            "(operation, idempotency_key, request_sha256, resource_type, "
            "resource_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                operation,
                idempotency_key,
                request_sha256,
                resource_type,
                resource_id,
                _canonical_json(response_body),
                created_at,
            ),
        )

    @staticmethod
    def _ensure_active(connection: sqlite3.Connection, participant_id: str) -> None:
        tombstone = connection.execute(
            "SELECT 1 FROM deletion_requests WHERE participant_id = ? LIMIT 1",
            (participant_id,),
        ).fetchone()
        if tombstone:
            raise ParticipantTombstoned(
                "Participant has requested deletion; new collection is disabled"
            )

    @staticmethod
    def _authenticate_participant(
        connection: sqlite3.Connection,
        participant_id: str,
        participant_token: str,
        *,
        allow_first_binding: bool = False,
        supplied_token_sha256: str | None = None,
    ) -> str:
        token_sha256 = hashlib.sha256(participant_token.encode("utf-8")).hexdigest()
        if supplied_token_sha256 is not None and not hmac.compare_digest(
            token_sha256,
            supplied_token_sha256,
        ):
            raise ConsentError("participant token does not match its supplied SHA-256")
        rows = connection.execute(
            "SELECT withdrawal_token_sha256 FROM consents "
            "WHERE participant_id = ?",
            (participant_id,),
        ).fetchall()
        known_hashes = [
            str(row["withdrawal_token_sha256"] or "")
            for row in rows
            if str(row["withdrawal_token_sha256"] or "")
        ]
        if not rows and allow_first_binding:
            return token_sha256
        matched = False
        for known_hash in known_hashes:
            matched = hmac.compare_digest(token_sha256, known_hash) or matched
        if not matched:
            raise ConsentError("participant token authentication failed")
        return token_sha256

    @staticmethod
    def _require_consent(
        connection: sqlite3.Connection,
        consent_id: str,
        participant_id: str,
        modality: str,
        app_id: str | None = None,
    ) -> sqlite3.Row:
        consent = connection.execute(
            "SELECT * FROM consents WHERE consent_id = ?",
            (consent_id,),
        ).fetchone()
        if consent is None:
            raise ConsentError("consent_id does not exist")
        if consent["participant_id"] != participant_id:
            raise ConsentError("consent_id belongs to a different participant")
        permitted = json.loads(consent["permitted_modalities_json"])
        if modality not in permitted:
            raise ConsentError(f"consent does not permit {modality} contributions")
        receipt_app_id = str(consent["app_id"] or "").strip()
        if app_id and receipt_app_id and receipt_app_id.casefold() != app_id.casefold():
            raise ConsentError("consent_id was issued for a different app")
        return consent

    def get_consent_snapshot(
        self,
        consent_id: str,
        participant_id: str,
        modality: str,
        app_id: str | None = None,
    ) -> dict[str, str]:
        """Validate an active receipt and return its server-authoritative lineage."""
        self.initialize()
        with self._connect() as connection:
            self._ensure_active(connection, participant_id)
            consent = self._require_consent(
                connection,
                consent_id,
                participant_id,
                modality,
                app_id,
            )
            return _consent_snapshot(consent)

    def get_submission_consent_snapshot(
        self,
        submission_id: str,
        participant_id: str,
        consent_id: str,
        task_id: str,
    ) -> dict[str, str]:
        """Bind a release attempt to its canonical v2 submission and receipt."""
        return self.get_submission_release_snapshot(
            submission_id,
            participant_id,
            consent_id,
            task_id,
        )["consent_snapshot"]

    def get_submission_release_snapshot(
        self,
        submission_id: str,
        participant_id: str,
        consent_id: str,
        task_id: str,
    ) -> dict[str, Any]:
        """Return server-owned content/provenance for one active submission.

        The final writer uses this record while holding the shared IEDID lock,
        so a reviewer cannot release edited or CSV-forged content under an
        unrelated participant receipt.
        """
        self.initialize()
        with self._connect() as connection:
            submission = connection.execute(
                "SELECT * FROM submissions WHERE submission_id = ?",
                (submission_id,),
            ).fetchone()
            if submission is None:
                raise MissingResource("submission_id does not exist")
            expected = {
                "participant_id": participant_id,
                "consent_id": consent_id,
                "task_id": task_id,
            }
            if any(
                str(submission[field]) != str(value)
                for field, value in expected.items()
            ):
                raise ConsentError(
                    "submission identifiers do not match the canonical v2 record"
                )
            self._ensure_active(connection, participant_id)
            consent = self._require_consent(
                connection,
                consent_id,
                participant_id,
                submission["input_modality"],
                submission["app_id"],
            )
            try:
                metadata = json.loads(submission["metadata_json"] or "{}")
            except (TypeError, ValueError, json.JSONDecodeError) as exc:
                raise ConsentError(
                    "canonical submission metadata is not valid JSON"
                ) from exc
            if not isinstance(metadata, dict):
                raise ConsentError("canonical submission metadata is not an object")
            canonical_context = str(
                metadata.get("context")
                or " | ".join(
                    part
                    for part in (
                        str(submission["prompt_text"] or ""),
                        str(submission["preceding_context"] or ""),
                    )
                    if part
                )
            )
            return {
                "consent_snapshot": _consent_snapshot(consent),
                "submission_id": str(submission["submission_id"]),
                "participant_id": str(submission["participant_id"]),
                "consent_id": str(submission["consent_id"]),
                "task_id": str(submission["task_id"]),
                "app_id": str(submission["app_id"]),
                "app_version": str(submission["app_version"]),
                "game_id": str(submission["game_id"]),
                "input_modality": str(submission["input_modality"]),
                "utterance": str(
                    submission["user_transcript_final"]
                    or submission["source_text"]
                    or ""
                ),
                "clarification": str(
                    submission["user_output_final"]
                    or submission["machine_output_initial"]
                    or ""
                ),
                "language": str(submission["target_language"]),
                "dialect": str(submission["target_dialect"]),
                "source_language": str(submission["source_language"]),
                "source_dialect": str(submission["source_dialect"]),
                "tone": str(metadata.get("tone") or ""),
                "context": canonical_context,
                "pragmatics": str(metadata.get("pragmatics") or ""),
                "source_tag": str(
                    metadata.get("source_tag")
                    or f"Game: {submission['game_id']}"
                ),
                "machine_transcript_initial": str(
                    submission["machine_transcript_initial"] or ""
                ),
                "user_transcript_final": str(
                    submission["user_transcript_final"] or ""
                ),
                "machine_output_initial": str(
                    submission["machine_output_initial"] or ""
                ),
                "user_output_final": str(submission["user_output_final"] or ""),
                "model_name": str(submission["model_name"] or ""),
                "model_version": str(submission["model_version"] or ""),
                "asr_model": str(submission["asr_model"] or ""),
                "translation_route": str(submission["translation_route"] or ""),
                "submitted_at": str(submission["submitted_at"]),
            }

    def _record_pending_attempt(
        self,
        outbox_id: str,
        succeeded: bool,
        error_code: str | None = None,
    ) -> None:
        try:
            with self._connect() as connection:
                self._begin(connection)
                connection.execute(
                    "INSERT INTO pending_audit_attempts "
                    "(attempt_id, outbox_id, attempted_at, succeeded, error_code) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (
                        _new_id("pat"),
                        outbox_id,
                        _utc_now(),
                        int(succeeded),
                        error_code,
                    ),
                )
                connection.commit()
        except sqlite3.Error:
            # The canonical submission and immutable outbox entry are already
            # durable. A later replay/drain can reconstruct this attempt.
            pass

    @staticmethod
    def _append_pending_csv(
        row: dict[str, Any],
        tombstone_check: Any = None,
    ) -> None:
        # pandas is imported only on delivery, keeping router imports lightweight.
        import pandas as pd

        pending_file = _pending_queue_path()
        pending_file.parent.mkdir(parents=True, exist_ok=True)
        with PENDING_QUEUE_LOCK:
            if callable(tombstone_check) and tombstone_check():
                raise ParticipantTombstoned(
                    "Participant withdrew before Pending Audit delivery"
                )
            if pending_file.exists():
                frame = pd.read_csv(pending_file, dtype=str).fillna("")
            else:
                frame = pd.DataFrame()

            for column in row:
                if column not in frame.columns:
                    frame[column] = ""

            if "Submission_ID" in frame.columns:
                same_submission = (
                    frame["Submission_ID"].astype(str) == row["Submission_ID"]
                )
                if same_submission.any():
                    return
            if "Queue_ID" in frame.columns:
                same_queue = frame["Queue_ID"].astype(str) == row["Queue_ID"]
                if same_queue.any():
                    return

            if frame.empty and not len(frame.columns):
                frame = pd.DataFrame(columns=list(row))
            frame.loc[len(frame)] = {
                column: row.get(column, "") for column in frame.columns
            }
            temp_file = pending_file.with_name(f"{pending_file.name}.v2.tmp")
            frame.to_csv(temp_file, index=False)
            os.replace(temp_file, pending_file)

    def _participant_has_tombstone(self, participant_id: str) -> bool:
        with self._connect() as connection:
            return connection.execute(
                "SELECT 1 FROM deletion_requests WHERE participant_id = ? LIMIT 1",
                (participant_id,),
            ).fetchone() is not None

    def mirror_submission(self, submission_id: str) -> str:
        """Deliver one immutable outbox item to the legacy Pending Audit CSV."""
        self.initialize()
        with self._connect() as connection:
            outbox = connection.execute(
                """
                SELECT outbox.outbox_id, outbox.pending_row_json,
                    submissions.participant_id,
                    EXISTS(
                        SELECT 1 FROM pending_audit_attempts attempts
                        WHERE attempts.outbox_id = outbox.outbox_id
                          AND attempts.succeeded = 1
                    ) AS delivered,
                    (
                        SELECT attempts.error_code
                        FROM pending_audit_attempts attempts
                        WHERE attempts.outbox_id = outbox.outbox_id
                          AND attempts.succeeded = 1
                        ORDER BY attempts.attempted_at DESC
                        LIMIT 1
                    ) AS delivery_code,
                    EXISTS(
                        SELECT 1 FROM deletion_requests requests
                        WHERE requests.participant_id = submissions.participant_id
                    ) AS participant_tombstoned
                FROM pending_audit_outbox AS outbox
                JOIN submissions
                  ON submissions.submission_id = outbox.submission_id
                WHERE outbox.submission_id = ?
                """,
                (submission_id,),
            ).fetchone()
        if outbox is None:
            return "retry_pending"
        if outbox["delivered"]:
            if outbox["delivery_code"] == "participant_tombstoned_no_delivery":
                return "withdrawn_not_mirrored"
            return "mirrored"
        if outbox["participant_tombstoned"]:
            self._record_pending_attempt(
                outbox["outbox_id"],
                True,
                error_code="participant_tombstoned_no_delivery",
            )
            return "withdrawn_not_mirrored"

        try:
            self._append_pending_csv(
                json.loads(outbox["pending_row_json"]),
                tombstone_check=lambda: self._participant_has_tombstone(
                    outbox["participant_id"]
                ),
            )
        except ParticipantTombstoned:
            self._record_pending_attempt(
                outbox["outbox_id"],
                True,
                error_code="participant_tombstoned_no_delivery",
            )
            return "withdrawn_not_mirrored"
        except Exception as exc:
            self._record_pending_attempt(
                outbox["outbox_id"],
                False,
                error_code=type(exc).__name__[:128],
            )
            return "retry_pending"

        self._record_pending_attempt(outbox["outbox_id"], True)
        return "mirrored"

    def drain_pending_audit(
        self,
        limit: int = 10,
        exclude_submission_id: str | None = None,
    ) -> int:
        """Best-effort retry of prior outbox items; failures remain recorded."""
        self.initialize()
        with self._connect() as connection:
            rows = connection.execute(
                """
                SELECT outbox.submission_id
                FROM pending_audit_outbox AS outbox
                WHERE outbox.submission_id != COALESCE(?, '')
                  AND NOT EXISTS (
                      SELECT 1 FROM pending_audit_attempts AS attempts
                      WHERE attempts.outbox_id = outbox.outbox_id
                        AND attempts.succeeded = 1
                  )
                ORDER BY outbox.created_at
                LIMIT ?
                """,
                (exclude_submission_id, max(1, min(limit, 100))),
            ).fetchall()
        return sum(
            self.mirror_submission(row["submission_id"]) == "mirrored"
            for row in rows
        )

    def _record_deletion_propagation_attempt(
        self,
        action_id: str,
        succeeded: bool,
        error_code: str | None = None,
    ) -> None:
        try:
            with self._connect() as connection:
                self._begin(connection)
                connection.execute(
                    "INSERT INTO deletion_propagation_attempts "
                    "(attempt_id, action_id, attempted_at, succeeded, error_code) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (
                        _new_id("dpa"),
                        action_id,
                        _utc_now(),
                        int(succeeded),
                        error_code,
                    ),
                )
                connection.commit()
        except sqlite3.Error:
            pass

    @staticmethod
    def _tombstone_pending_csv(
        participant_id: str,
        deletion_request_id: str,
        requested_at: str,
        submission_ids: tuple[str, ...] = (),
        consent_ids: tuple[str, ...] = (),
    ) -> None:
        import pandas as pd

        pending_file = _pending_queue_path()
        with PENDING_QUEUE_LOCK:
            if not pending_file.exists():
                return
            frame = pd.read_csv(pending_file, dtype=str).fillna("")
            contribution_mask = pd.Series(False, index=frame.index, dtype=bool)
            if "User" in frame.columns:
                contribution_mask |= frame["User"].astype(str) == participant_id
            if "Participant_ID" in frame.columns:
                contribution_mask |= frame["Participant_ID"].astype(str) == participant_id
            if submission_ids and "Submission_ID" in frame.columns:
                contribution_mask |= frame["Submission_ID"].astype(str).isin(submission_ids)
            if consent_ids and "Consent_ID" in frame.columns:
                contribution_mask |= frame["Consent_ID"].astype(str).isin(consent_ids)
            approvers_changed = False
            if "Approvers" in frame.columns:
                cleaned_approvers = frame["Approvers"].astype(str).map(
                    lambda values: ",".join(
                        entry
                        for entry in values.split(",")
                        if entry and entry != participant_id
                    )
                )
                approvers_changed = not cleaned_approvers.equals(frame["Approvers"])
                frame["Approvers"] = cleaned_approvers

            if not contribution_mask.any() and not approvers_changed:
                return

            if contribution_mask.any():
                _scrub_tombstoned_csv_rows(
                    frame, contribution_mask, "[deleted]"
                )
                frame.loc[contribution_mask, "User"] = "deleted-participant"
                frame.loc[contribution_mask, "Submission_Status"] = (
                    "Deletion Requested"
                )
                if "Review_Status" in frame.columns:
                    frame.loc[contribution_mask, "Review_Status"] = (
                        "Withdrawal Requested"
                    )
                frame.loc[contribution_mask, "Release_Eligible"] = "false"
                if "Consent_Status" in frame.columns:
                    frame.loc[contribution_mask, "Consent_Status"] = "withdrawn"
                if "Consent_Confirmed" in frame.columns:
                    frame.loc[contribution_mask, "Consent_Confirmed"] = ""
                frame.loc[contribution_mask, "Ethics_Review_Status"] = "withdrawn"
                frame.loc[contribution_mask, "Withdrawal_Request_ID"] = deletion_request_id
                frame.loc[contribution_mask, "Withdrawal_Requested_At"] = requested_at
                frame.loc[
                    contribution_mask, "Deletion_Propagation_Status"
                ] = "local_tombstoned_remote_pending"

            temp_file = pending_file.with_name(f"{pending_file.name}.delete.tmp")
            frame.to_csv(temp_file, index=False)
            os.replace(temp_file, pending_file)

    def propagate_deletion_to_pending_audit(
        self,
        deletion_request_id: str,
    ) -> bool:
        """Tombstone a participant's local Pending Audit copies."""
        self.initialize()
        with self._connect() as connection:
            action = connection.execute(
                """
                SELECT outbox.action_id, outbox.participant_id, requests.requested_at,
                    EXISTS(
                        SELECT 1 FROM deletion_propagation_attempts AS attempts
                        WHERE attempts.action_id = outbox.action_id
                          AND attempts.succeeded = 1
                    ) AS delivered
                FROM deletion_propagation_outbox AS outbox
                JOIN deletion_requests AS requests
                  ON requests.deletion_request_id = outbox.deletion_request_id
                WHERE outbox.deletion_request_id = ?
                  AND outbox.target = 'pending_audit_csv'
                """,
                (deletion_request_id,),
            ).fetchone()
            submission_ids: tuple[str, ...] = ()
            consent_ids: tuple[str, ...] = ()
            if action is not None:
                submission_ids = tuple(sorted(
                    str(row["submission_id"])
                    for row in connection.execute(
                        "SELECT submission_id FROM submissions WHERE participant_id = ?",
                        (action["participant_id"],),
                    ).fetchall()
                ))
                consent_ids = tuple(sorted(
                    str(row["consent_id"])
                    for row in connection.execute(
                        "SELECT consent_id FROM consents WHERE participant_id = ?",
                        (action["participant_id"],),
                    ).fetchall()
                ))
        if action is None:
            return False
        if action["delivered"]:
            return True
        try:
            self._tombstone_pending_csv(
                action["participant_id"],
                deletion_request_id,
                action["requested_at"],
                submission_ids,
                consent_ids,
            )
        except Exception as exc:
            self._record_deletion_propagation_attempt(
                action["action_id"],
                False,
                type(exc).__name__[:128],
            )
            return False
        self._record_deletion_propagation_attempt(action["action_id"], True)
        return True

    def _record_iedid_deletion_attempt(
        self,
        action_id: str,
        succeeded: bool,
        error_code: str | None = None,
    ) -> None:
        try:
            with self._connect() as connection:
                self._begin(connection)
                connection.execute(
                    "INSERT INTO iedid_deletion_attempts "
                    "(attempt_id, action_id, attempted_at, succeeded, error_code) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (
                        _new_id("ida"),
                        action_id,
                        _utc_now(),
                        int(succeeded),
                        error_code,
                    ),
                )
                connection.commit()
        except sqlite3.Error:
            pass

    @staticmethod
    def _tombstone_local_iedid(
        participant_id: str,
        consent_ids: list[str],
        deletion_request_id: str,
        requested_at: str,
    ) -> None:
        import pandas as pd

        dataset_root = _iedid_dataset_path()
        ignored = {
            "minted_history.csv",
            "system_feedback.csv",
            "eeqs_events.csv",
        }
        with IEDID_DATASET_LOCK:
            csv_paths = (
                set(dataset_root.rglob("*.csv"))
                if dataset_root.exists()
                else set()
            )
            rejected_audit = dataset_root.parent / "rejected_graveyard.csv"
            if rejected_audit.is_file():
                csv_paths.add(rejected_audit)
            for csv_path in sorted(csv_paths):
                if csv_path.name.casefold() in ignored:
                    continue
                frame = pd.read_csv(csv_path, dtype=str, encoding="utf-8-sig").fillna("")
                mask = pd.Series(False, index=frame.index)
                if "User" in frame.columns:
                    mask |= frame["User"].astype(str) == participant_id
                if "Participant_ID" in frame.columns:
                    mask |= frame["Participant_ID"].astype(str) == participant_id
                if consent_ids and "Consent_ID" in frame.columns:
                    mask |= frame["Consent_ID"].astype(str).isin(consent_ids)
                if not mask.any():
                    continue

                for column in (
                    "Consent_Status",
                    "Consent_Confirmed",
                    "Review_Status",
                    "Release_Eligible",
                    "Ethics_Review_Status",
                    "Withdrawal_Request_ID",
                    "Withdrawal_Requested_At",
                    "Deletion_Propagation_Status",
                    "Audio_Deletion_Status",
                ):
                    if column not in frame.columns:
                        frame[column] = ""
                _scrub_tombstoned_csv_rows(frame, mask, "[withdrawn]")
                if "User" in frame.columns:
                    frame.loc[mask, "User"] = "withdrawn-participant"
                if "Participant_ID" in frame.columns:
                    frame.loc[mask, "Participant_ID"] = ""
                frame.loc[mask, "Consent_Status"] = "withdrawn"
                frame.loc[mask, "Consent_Confirmed"] = ""
                frame.loc[mask, "Review_Status"] = "Withdrawal Requested"
                if "Submission_Status" in frame.columns:
                    frame.loc[mask, "Submission_Status"] = "Deletion Requested"
                frame.loc[mask, "Release_Eligible"] = "false"
                frame.loc[mask, "Ethics_Review_Status"] = "withdrawn"
                frame.loc[mask, "Withdrawal_Request_ID"] = deletion_request_id
                frame.loc[mask, "Withdrawal_Requested_At"] = requested_at
                frame.loc[
                    mask, "Deletion_Propagation_Status"
                ] = "local_tombstoned_remote_pending"
                frame.loc[mask, "Audio_Deletion_Status"] = "pending_propagation"

                temporary_path = csv_path.with_name(
                    f".{csv_path.name}.withdrawal.tmp"
                )
                frame.to_csv(temporary_path, index=False)
                os.replace(temporary_path, csv_path)

    def propagate_deletion_to_local_iedid(
        self,
        deletion_request_id: str,
    ) -> bool:
        """Tombstone controlled local IEDID rows; remote copies remain queued."""
        self.initialize()
        with self._connect() as connection:
            action = connection.execute(
                """
                SELECT outbox.action_id, outbox.participant_id,
                    outbox.consent_ids_json, requests.requested_at,
                    EXISTS(
                        SELECT 1 FROM iedid_deletion_attempts AS attempts
                        WHERE attempts.action_id = outbox.action_id
                          AND attempts.succeeded = 1
                    ) AS delivered
                FROM iedid_deletion_outbox AS outbox
                JOIN deletion_requests AS requests
                  ON requests.deletion_request_id = outbox.deletion_request_id
                WHERE outbox.deletion_request_id = ?
                """,
                (deletion_request_id,),
            ).fetchone()
        if action is None:
            return False
        if action["delivered"]:
            return True
        try:
            self._tombstone_local_iedid(
                action["participant_id"],
                json.loads(action["consent_ids_json"]),
                deletion_request_id,
                action["requested_at"],
            )
        except Exception as exc:
            self._record_iedid_deletion_attempt(
                action["action_id"],
                False,
                type(exc).__name__[:128],
            )
            return False
        self._record_iedid_deletion_attempt(action["action_id"], True)
        return True

    def create_consent(
        self,
        payload: ConsentCreate,
        idempotency_key: str,
        participant_token: str,
    ) -> tuple[dict[str, Any], bool]:
        self.initialize()
        request_data = payload.model_dump(mode="json")
        request_sha256 = _request_hash(request_data)
        receipt_data = dict(request_data)
        receipt_data.pop("withdrawal_token_sha256", None)
        receipt_data.pop("participant_id", None)
        operation = "create_consent"
        with self._connect() as connection:
            self._begin(connection)
            try:
                self._ensure_active(connection, payload.participant_id)
                token_sha256 = self._authenticate_participant(
                    connection,
                    payload.participant_id,
                    participant_token,
                    allow_first_binding=True,
                    supplied_token_sha256=payload.withdrawal_token_sha256,
                )
                replay = self._idempotent_replay(
                    connection, operation, idempotency_key, request_sha256
                )
                if replay is not None:
                    connection.commit()
                    return replay, True
                consent_id = _new_id("cns")
                recorded_at = _utc_now()
                record = {
                    **receipt_data,
                    "consent_id": consent_id,
                    "recorded_at": recorded_at,
                    "schema_version": SCHEMA_VERSION,
                    "consent_status": VERIFIED_CONSENT_STATUS,
                    "consent_provenance": VERIFIED_CONSENT_PROVENANCE,
                }
                record_sha256 = _request_hash(record)
                connection.execute(
                    """
                    INSERT INTO consents (
                        consent_id, schema_version, participant_id, app_id,
                        receipt_schema_version,
                        app_version, consent_version, privacy_notice_version, dataset_license,
                        permitted_modalities_json, consent_surface, consent_locale,
                        consent_text_sha256, research_purposes_json,
                        retention_policy_version, withdrawal_policy_version,
                        eligibility_confirmed, public_release_confirmed,
                        commercial_ai_reuse_confirmed, privacy_risks_acknowledged,
                        operational_processing_acknowledged,
                        voluntary_participation_confirmed,
                        contribution_rights_confirmed, raw_audio_consent,
                        data_controller_name, data_controller_contact,
                        data_recipient_categories_json, withdrawal_token_sha256,
                        consent_status,
                        consent_provenance, consent_granted, recorded_at,
                        request_sha256, record_sha256, record_json
                    ) VALUES (
                        :consent_id, :schema_version, :participant_id, :app_id,
                        :receipt_schema_version,
                        :app_version, :consent_version, :privacy_notice_version,
                        :dataset_license, :permitted_modalities_json,
                        :consent_surface, :consent_locale, :consent_text_sha256,
                        :research_purposes_json, :retention_policy_version,
                        :withdrawal_policy_version, 1, 1, 1, 1, 1, 1, 1,
                        :raw_audio_consent,
                        :data_controller_name, :data_controller_contact,
                        :data_recipient_categories_json, :withdrawal_token_sha256,
                        :consent_status,
                        :consent_provenance, 1, :recorded_at,
                        :request_sha256, :record_sha256, :record_json
                    )
                    """,
                    {
                        "consent_id": consent_id,
                        "schema_version": STORAGE_SCHEMA_VERSION,
                        "receipt_schema_version": SCHEMA_VERSION,
                        "participant_id": payload.participant_id,
                        "app_id": payload.app_id,
                        "app_version": payload.app_version,
                        "consent_version": payload.consent_version,
                        "privacy_notice_version": payload.privacy_notice_version,
                        "dataset_license": payload.dataset_license,
                        "permitted_modalities_json": _canonical_json(
                            payload.permitted_modalities
                        ),
                        "consent_surface": payload.consent_surface,
                        "consent_locale": payload.consent_locale,
                        "consent_text_sha256": payload.consent_text_sha256,
                        "research_purposes_json": _canonical_json(
                            payload.research_purposes
                        ),
                        "retention_policy_version": payload.retention_policy_version,
                        "withdrawal_policy_version": payload.withdrawal_policy_version,
                        "raw_audio_consent": int(payload.raw_audio_consent),
                        "data_controller_name": payload.data_controller_name,
                        "data_controller_contact": payload.data_controller_contact,
                        "data_recipient_categories_json": _canonical_json(
                            payload.data_recipient_categories
                        ),
                        "withdrawal_token_sha256": token_sha256,
                        "consent_status": VERIFIED_CONSENT_STATUS,
                        "consent_provenance": VERIFIED_CONSENT_PROVENANCE,
                        "recorded_at": recorded_at,
                        "request_sha256": request_sha256,
                        "record_sha256": record_sha256,
                        "record_json": _canonical_json(record),
                    },
                )
                response = {
                    "consent_id": consent_id,
                    "recorded_at": recorded_at,
                    "consent_record_sha256": record_sha256,
                    "consent_text_sha256": payload.consent_text_sha256,
                    "receipt_schema_version": SCHEMA_VERSION,
                    "consent_version": payload.consent_version,
                    "permitted_modalities": sorted(payload.permitted_modalities),
                    "consent_status": VERIFIED_CONSENT_STATUS,
                    "consent_provenance": VERIFIED_CONSENT_PROVENANCE,
                    "idempotent_replay": False,
                }
                self._record_idempotency(
                    connection,
                    operation,
                    idempotency_key,
                    request_sha256,
                    "consent",
                    consent_id,
                    response,
                    recorded_at,
                )
                connection.commit()
                return response, False
            except Exception:
                connection.rollback()
                raise

    def create_submission(
        self,
        payload: SubmissionCreate,
        idempotency_key: str,
        participant_token: str,
    ) -> tuple[dict[str, Any], bool]:
        self.initialize()
        request_data = payload.model_dump(mode="json")
        request_sha256 = _request_hash(request_data)
        operation = "create_submission"
        with self._connect() as connection:
            self._begin(connection)
            try:
                self._ensure_active(connection, payload.participant_id)
                self._authenticate_participant(
                    connection,
                    payload.participant_id,
                    participant_token,
                )
                replay = self._idempotent_replay(
                    connection, operation, idempotency_key, request_sha256
                )
                if replay is not None:
                    connection.commit()
                    return replay, True
                consent = self._require_consent(
                    connection,
                    payload.consent_id,
                    payload.participant_id,
                    payload.input_modality,
                    payload.app_id,
                )
                consent_snapshot = _consent_snapshot(consent)
                if not consent_lineage_is_verified(consent_snapshot):
                    raise ConsentError(
                        "consent receipt predates the complete ethical policy; "
                        "record a new consent receipt"
                    )
                submission_id = _new_id("sub")
                outbox_id = _new_id("out")
                pending_queue_id = f"v2-{uuid.uuid4()}"
                submitted_at = _utc_now()
                record = {
                    **request_data,
                    "submission_id": submission_id,
                    "submitted_at": submitted_at,
                    "schema_version": SCHEMA_VERSION,
                    "moderation_status": "pending",
                    "review_status": "pending",
                    "release_eligible": False,
                    "consent_snapshot": consent_snapshot,
                }
                connection.execute(
                    """
                    INSERT INTO submissions (
                        submission_id, schema_version, participant_id, consent_id,
                        app_id, app_version, game_id, task_id, prompt_text, topic_id,
                        image_asset_id, conversation_id, turn_id, preceding_context,
                        source_text, source_language, source_dialect, target_language,
                        target_dialect, input_modality, machine_transcript_initial,
                        user_transcript_final, machine_output_initial, user_output_final,
                        model_name, model_version, asr_model, translation_route,
                        metadata_json, started_at, submitted_at, duration_ms,
                        moderation_status, review_status, release_eligible,
                        request_sha256, record_json
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending', 0, ?, ?
                    )
                    """,
                    (
                        submission_id,
                        STORAGE_SCHEMA_VERSION,
                        payload.participant_id,
                        payload.consent_id,
                        payload.app_id,
                        payload.app_version,
                        payload.game_id,
                        payload.task_id,
                        payload.prompt_text,
                        payload.topic_id,
                        payload.image_asset_id,
                        payload.conversation_id,
                        payload.turn_id,
                        payload.preceding_context,
                        payload.source_text,
                        payload.source_language,
                        payload.source_dialect,
                        payload.target_language,
                        payload.target_dialect,
                        payload.input_modality,
                        payload.machine_transcript_initial,
                        payload.user_transcript_final,
                        payload.machine_output_initial,
                        payload.user_output_final,
                        payload.model_name,
                        payload.model_version,
                        payload.asr_model,
                        payload.translation_route,
                        _canonical_json(payload.metadata),
                        request_data.get("started_at"),
                        submitted_at,
                        payload.duration_ms,
                        request_sha256,
                        _canonical_json(record),
                    ),
                )
                pending_row = _legacy_pending_row(
                    payload,
                    submission_id,
                    pending_queue_id,
                    submitted_at,
                    consent_snapshot,
                )
                connection.execute(
                    "INSERT INTO pending_audit_outbox "
                    "(outbox_id, submission_id, queue_id, pending_row_json, created_at) "
                    "VALUES (?, ?, ?, ?, ?)",
                    (
                        outbox_id,
                        submission_id,
                        pending_queue_id,
                        _canonical_json(pending_row),
                        submitted_at,
                    ),
                )
                response = {
                    "submission_id": submission_id,
                    "submitted_at": submitted_at,
                    "moderation_status": "pending",
                    "review_status": "pending",
                    "release_eligible": False,
                    "pending_queue_id": pending_queue_id,
                    "pending_audit_status": "retry_pending",
                    "idempotent_replay": False,
                }
                self._record_idempotency(
                    connection,
                    operation,
                    idempotency_key,
                    request_sha256,
                    "submission",
                    submission_id,
                    response,
                    submitted_at,
                )
                connection.commit()
                return response, False
            except Exception:
                connection.rollback()
                raise

    def create_judgment(
        self,
        payload: JudgmentCreate,
        idempotency_key: str,
        participant_token: str,
    ) -> tuple[dict[str, Any], bool]:
        self.initialize()
        request_data = payload.model_dump(mode="json")
        request_sha256 = _request_hash(request_data)
        operation = "create_judgment"
        with self._connect() as connection:
            self._begin(connection)
            try:
                self._ensure_active(connection, payload.participant_id)
                self._authenticate_participant(
                    connection,
                    payload.participant_id,
                    participant_token,
                )
                replay = self._idempotent_replay(
                    connection, operation, idempotency_key, request_sha256
                )
                if replay is not None:
                    connection.commit()
                    return replay, True
                submission = connection.execute(
                    "SELECT participant_id, task_id, app_id FROM submissions "
                    "WHERE submission_id = ?",
                    (payload.submission_id,),
                ).fetchone()
                if submission is None:
                    raise MissingResource("submission_id does not exist")
                if str(submission["task_id"]) != payload.task_id:
                    raise ConsentError(
                        "judgment task_id does not match the canonical submission"
                    )
                self._ensure_active(connection, str(submission["participant_id"]))
                consent = self._require_consent(
                    connection,
                    payload.consent_id,
                    payload.participant_id,
                    "judgment",
                    str(submission["app_id"]),
                )
                if not consent_lineage_is_verified(_consent_snapshot(consent)):
                    raise ConsentError(
                        "consent receipt predates the complete ethical policy; "
                        "record a new consent receipt"
                    )
                judgment_id = _new_id("jdg")
                recorded_at = _utc_now()
                record = {
                    **request_data,
                    "judgment_id": judgment_id,
                    "recorded_at": recorded_at,
                    "schema_version": SCHEMA_VERSION,
                    "gold_item": False,
                    "gold_result": None,
                    "release_eligible": False,
                }
                connection.execute(
                    """
                    INSERT INTO judgments (
                        judgment_id, schema_version, participant_id, consent_id,
                        submission_id, task_id, choice, error_span, error_type,
                        correction, confidence, latency_ms, gold_item, gold_result,
                        recorded_at, release_eligible, request_sha256, record_json
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, ?, 0, ?, ?)
                    """,
                    (
                        judgment_id,
                        STORAGE_SCHEMA_VERSION,
                        payload.participant_id,
                        payload.consent_id,
                        payload.submission_id,
                        payload.task_id,
                        payload.choice,
                        payload.error_span,
                        payload.error_type,
                        payload.correction,
                        payload.confidence,
                        payload.latency_ms,
                        recorded_at,
                        request_sha256,
                        _canonical_json(record),
                    ),
                )
                response = {
                    "judgment_id": judgment_id,
                    "recorded_at": recorded_at,
                    "idempotent_replay": False,
                }
                self._record_idempotency(
                    connection,
                    operation,
                    idempotency_key,
                    request_sha256,
                    "judgment",
                    judgment_id,
                    response,
                    recorded_at,
                )
                connection.commit()
                return response, False
            except Exception:
                connection.rollback()
                raise

    def request_deletion(
        self,
        participant_id: str,
        payload: DeletionRequestCreate,
        idempotency_key: str,
        participant_token: str,
    ) -> tuple[dict[str, Any], bool]:
        self.initialize()
        participant_id = _validate_participant_id(participant_id)
        request_data = {
            "participant_id": participant_id,
            **payload.model_dump(mode="json"),
        }
        request_sha256 = _request_hash(request_data)
        operation = "request_deletion"
        # Serialize the canonical tombstone with both release and Pending Audit
        # delivery. Either a writer finishes before withdrawal is recorded and
        # is subsequently tombstoned, or it observes the tombstone and stops.
        with IEDID_DATASET_LOCK, PENDING_QUEUE_LOCK, self._connect() as connection:
            self._begin(connection)
            try:
                self._authenticate_participant(
                    connection,
                    participant_id,
                    participant_token,
                )
                replay = self._idempotent_replay(
                    connection, operation, idempotency_key, request_sha256
                )
                if replay is not None:
                    connection.commit()
                    return replay, True
                deletion_request_id = _new_id("del")
                requested_at = _utc_now()
                connection.execute("PRAGMA secure_delete = ON")
                erase_participant_audio(connection, participant_id, requested_at)
                record = {
                    **request_data,
                    "deletion_request_id": deletion_request_id,
                    "requested_at": requested_at,
                    "schema_version": SCHEMA_VERSION,
                    "status": "pending",
                    "tombstoned": True,
                    "hard_deleted": False,
                }
                connection.execute(
                    """
                    INSERT INTO deletion_requests (
                        deletion_request_id, schema_version, participant_id, reason,
                        scope, requested_at, status, tombstoned, hard_deleted,
                        request_sha256, record_json
                    ) VALUES (?, ?, ?, ?, ?, ?, 'pending', 1, 0, ?, ?)
                    """,
                    (
                        deletion_request_id,
                        STORAGE_SCHEMA_VERSION,
                        participant_id,
                        payload.reason,
                        payload.scope,
                        requested_at,
                        request_sha256,
                        _canonical_json(record),
                    ),
                )
                for target in (
                    "pending_audit_csv",
                    "huggingface_export",
                ):
                    action_id = _new_id("dpo")
                    action_payload = {
                        "deletion_request_id": deletion_request_id,
                        "participant_id": participant_id,
                        "target": target,
                        "action": "tombstone_participant_records",
                    }
                    connection.execute(
                        """
                        INSERT INTO deletion_propagation_outbox (
                            action_id, deletion_request_id, participant_id, target,
                            action, payload_json, created_at
                        ) VALUES (?, ?, ?, ?, 'tombstone_participant_records', ?, ?)
                        """,
                        (
                            action_id,
                            deletion_request_id,
                            participant_id,
                            target,
                            _canonical_json(action_payload),
                            requested_at,
                        ),
                    )
                consent_ids = [
                    row["consent_id"]
                    for row in connection.execute(
                        "SELECT consent_id FROM consents WHERE participant_id = ?",
                        (participant_id,),
                    ).fetchall()
                ]
                connection.execute(
                    "INSERT INTO iedid_deletion_outbox "
                    "(action_id, deletion_request_id, participant_id, "
                    "consent_ids_json, created_at) VALUES (?, ?, ?, ?, ?)",
                    (
                        _new_id("ido"),
                        deletion_request_id,
                        participant_id,
                        _canonical_json(consent_ids),
                        requested_at,
                    ),
                )
                response = {
                    "deletion_request_id": deletion_request_id,
                    "requested_at": requested_at,
                    "status": "pending",
                    "tombstoned": True,
                    "hard_deleted": False,
                    "local_pending_audit_status": "retry_pending",
                    "local_iedid_status": "retry_pending",
                    "remote_export_status": "propagation_pending",
                    "private_pending_mirror_status": "propagation_pending",
                    "propagation_pending": True,
                    "idempotent_replay": False,
                }
                self._record_idempotency(
                    connection,
                    operation,
                    idempotency_key,
                    request_sha256,
                    "deletion_request",
                    deletion_request_id,
                    response,
                    requested_at,
                )
                connection.commit()
                return response, False
            except Exception:
                connection.rollback()
                raise

    def health(self) -> dict[str, Any]:
        self.initialize()
        with self._connect() as connection:
            check = connection.execute("PRAGMA quick_check").fetchone()[0]
            journal_mode = connection.execute("PRAGMA journal_mode").fetchone()[0]
            version = connection.execute(
                "SELECT MAX(schema_version) FROM schema_meta"
            ).fetchone()[0]
        configured_path = _configured_db_path() is not None
        path_ready = self.path.is_file() and check == "ok"
        return {
            "status": "ok" if check == "ok" else "degraded",
            "schema_version": version,
            "journal_mode": journal_mode.lower(),
            "append_only": True,
            "raw_records_exposed": False,
            "storage_mode": (
                "configured_file_path"
                if configured_path
                else "ephemeral_explicit_opt_in"
            ),
            "storage_path_configured": configured_path,
            "storage_path_ready": path_ready,
            # A live request can verify only that this process can open and
            # check the configured file. Persistence across a Space restart
            # must be verified externally and is deliberately not claimed here.
            "persistence_verification": "external_restart_test_required",
        }

    def stats(self) -> dict[str, Any]:
        self.initialize()
        with self._connect() as connection:
            counts = {
                table: connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
                for table in (
                    "consents",
                    "submissions",
                    "judgments",
                    "deletion_requests",
                )
            }
            tombstoned = connection.execute(
                "SELECT COUNT(DISTINCT participant_id) FROM deletion_requests"
            ).fetchone()[0]
            pending_audit = connection.execute(
                """
                SELECT COUNT(*)
                FROM pending_audit_outbox AS outbox
                WHERE NOT EXISTS (
                    SELECT 1 FROM pending_audit_attempts AS attempts
                    WHERE attempts.outbox_id = outbox.outbox_id
                      AND attempts.succeeded = 1
                )
                """
            ).fetchone()[0]
            deletion_propagation = {
                target: count
                for target, count in connection.execute(
                    """
                    SELECT outbox.target, COUNT(*)
                    FROM deletion_propagation_outbox AS outbox
                    WHERE NOT EXISTS (
                        SELECT 1 FROM deletion_propagation_attempts AS attempts
                        WHERE attempts.action_id = outbox.action_id
                          AND attempts.succeeded = 1
                    )
                    GROUP BY outbox.target
                    """
                ).fetchall()
            }
            local_iedid_deletion_pending = connection.execute(
                """
                SELECT COUNT(*)
                FROM iedid_deletion_outbox AS outbox
                WHERE NOT EXISTS (
                    SELECT 1 FROM iedid_deletion_attempts AS attempts
                    WHERE attempts.action_id = outbox.action_id
                      AND attempts.succeeded = 1
                )
                """
            ).fetchone()[0]
        return {
            "schema_version": SCHEMA_VERSION,
            "records": counts,
            "tombstoned_participants": tombstoned,
            "release_eligible_records": 0,
            "pending_audit_retry_count": pending_audit,
            "deletion_propagation_pending": {
                "pending_audit_csv": deletion_propagation.get(
                    "pending_audit_csv", 0
                ),
                "huggingface_export": deletion_propagation.get(
                    "huggingface_export", 0
                ),
                "private_pending_mirror": deletion_propagation.get(
                    "huggingface_export", 0
                ),
                "local_iedid_csv": local_iedid_deletion_pending,
            },
        }


_STORE_REGISTRY: dict[Path, CollectionStore] = {}
_STORE_REGISTRY_LOCK = threading.Lock()


def get_store() -> CollectionStore:
    path = _default_db_path()
    with _STORE_REGISTRY_LOCK:
        store = _STORE_REGISTRY.get(path)
        if store is None:
            store = CollectionStore(path)
            _STORE_REGISTRY[path] = store
        return store


def _raise_api_error(exc: Exception) -> None:
    if isinstance(exc, StorageConfigurationError):
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=str(exc),
        )
    if isinstance(exc, IdempotencyConflict):
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
    if isinstance(exc, ParticipantTombstoned):
        raise HTTPException(status_code=status.HTTP_410_GONE, detail=str(exc))
    if isinstance(exc, ConsentError):
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
    if isinstance(exc, MissingResource):
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
    if isinstance(exc, ValueError):
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)
        )
    if isinstance(exc, sqlite3.Error):
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Collection store is temporarily unavailable",
        )
    raise exc


@router.get("/consent-policies/current")
def current_consent_policy(consent_locale: str = "en") -> dict[str, Any]:
    """Expose the immutable text/hash clients must verify before consenting."""
    try:
        return get_current_consent_policy(consent_locale)
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc


@router.post(
    "/consents",
    response_model=ConsentReceipt,
    status_code=status.HTTP_201_CREATED,
)
def create_consent(
    payload: ConsentCreate,
    response: Response,
    idempotency_key: IdempotencyKey,
    participant_token: ParticipantToken,
) -> dict[str, Any]:
    try:
        result, replayed = get_store().create_consent(
            payload,
            idempotency_key,
            participant_token,
        )
    except Exception as exc:
        _raise_api_error(exc)
    if replayed:
        response.status_code = status.HTTP_200_OK
    return result


@router.post(
    "/submissions",
    response_model=SubmissionReceipt,
    status_code=status.HTTP_201_CREATED,
)
def create_submission(
    payload: SubmissionCreate,
    response: Response,
    idempotency_key: IdempotencyKey,
    participant_token: ParticipantToken,
) -> dict[str, Any]:
    try:
        store = get_store()
        result, replayed = store.create_submission(
            payload,
            idempotency_key,
            participant_token,
        )
        result["pending_audit_status"] = store.mirror_submission(
            result["submission_id"]
        )
        store.drain_pending_audit(
            limit=10,
            exclude_submission_id=result["submission_id"],
        )
    except Exception as exc:
        _raise_api_error(exc)
    if replayed:
        response.status_code = status.HTTP_200_OK
    return result


@router.post(
    "/judgments",
    response_model=JudgmentReceipt,
    status_code=status.HTTP_201_CREATED,
)
def create_judgment(
    payload: JudgmentCreate,
    response: Response,
    idempotency_key: IdempotencyKey,
    participant_token: ParticipantToken,
) -> dict[str, Any]:
    try:
        result, replayed = get_store().create_judgment(
            payload,
            idempotency_key,
            participant_token,
        )
    except Exception as exc:
        _raise_api_error(exc)
    if replayed:
        response.status_code = status.HTTP_200_OK
    return result


@router.delete(
    "/participants/{participant_id}/data",
    response_model=DeletionReceipt,
    status_code=status.HTTP_202_ACCEPTED,
)
def request_participant_deletion(
    participant_id: str,
    response: Response,
    idempotency_key: IdempotencyKey,
    participant_token: ParticipantToken,
    payload: Annotated[DeletionRequestCreate | None, Body()] = None,
) -> dict[str, Any]:
    try:
        store = get_store()
        result, replayed = store.request_deletion(
            participant_id,
            payload or DeletionRequestCreate(),
            idempotency_key,
            participant_token,
        )
        local_tombstoned = store.propagate_deletion_to_pending_audit(
            result["deletion_request_id"]
        )
        result["local_pending_audit_status"] = (
            "tombstoned" if local_tombstoned else "retry_pending"
        )
        local_iedid_tombstoned = store.propagate_deletion_to_local_iedid(
            result["deletion_request_id"]
        )
        result["local_iedid_status"] = (
            "tombstoned" if local_iedid_tombstoned else "retry_pending"
        )
        # Remote publication deletion is an explicit outbox action consumed by
        # the separate HF export job; this API does not overstate completion.
        result["remote_export_status"] = "propagation_pending"
        result["private_pending_mirror_status"] = "propagation_pending"
        result["propagation_pending"] = True
    except Exception as exc:
        _raise_api_error(exc)
    if replayed:
        response.status_code = status.HTTP_200_OK
    return result


@router.get("/health")
def collection_health() -> dict[str, Any]:
    try:
        return get_store().health()
    except Exception as exc:
        _raise_api_error(exc)


@router.get("/stats")
def collection_stats() -> dict[str, Any]:
    try:
        return get_store().stats()
    except Exception as exc:
        _raise_api_error(exc)