deq-runtime 0.3.0

deq: Real-time Quantum Error Correction Decoding System
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
//! Tests for MonolithicCoordinator using MockDecoder

use deq_runtime::bin::{self, instruction};
use deq_runtime::coordinator::coordinator_server::Coordinator;
use deq_runtime::coordinator::monolithic_coordinator::MonolithicCoordinator;
use deq_runtime::decoder::{BlackBoxDecoderClient, MockDecoder};
use deq_runtime::util::{BitMatrix, BitVector};
use std::sync::Arc;
use tonic::Request;

fn make_mock_decoder() -> Arc<MockDecoder> {
    Arc::new(MockDecoder::new())
}

fn make_decoder_client(mock: Arc<MockDecoder>) -> BlackBoxDecoderClient {
    BlackBoxDecoderClient::from_mock(mock)
}

fn make_coordinator(mock: Arc<MockDecoder>) -> MonolithicCoordinator {
    let config = serde_json::json!({
        "persistent_decoder": false,
        "merge_hyperedges": false
    });
    MonolithicCoordinator::new(config, make_decoder_client(mock))
}

fn make_gadget(gid: u64, gtype: u64, connectors: Vec<(u64, u64)>) -> bin::Gadget {
    bin::Gadget {
        gid,
        gtype,
        connectors: connectors
            .into_iter()
            .map(|(gid, port)| bin::gadget::Connector { gid, port })
            .collect(),
        ..Default::default()
    }
}

fn make_check_model(cid: u64, ctype: u64, gid: u64) -> bin::CheckModel {
    bin::CheckModel {
        cid,
        ctype,
        gid,
        ..Default::default()
    }
}

fn make_error_model(eid: u64, etype: u64, cid: u64) -> bin::ErrorModel {
    bin::ErrorModel {
        eid,
        etype,
        cid,
        ..Default::default()
    }
}

/// Creates a canonical-style library similar to the Python test's default_library_canonical.
/// This uses a port type with NO observables, which simplifies the pauli frame tracker.
///
/// Matrix dimensions for gadget type with:
/// - 0 input observables (no input ports)
/// - 0 output observables (port type has no observables)
/// - 1 readout
///
/// correction_propagation: rows=0 (output obs), cols=1 (input obs + 1)
/// readout_propagation: rows=1 (readouts), cols=1 (input obs + 1)
/// logical_correction: rows=0 (output obs), cols=1 (readouts)
fn make_canonical_library() -> bin::Library {
    // Port type with NO observables - this is key for simplifying tests
    let port_type = bin::PortType {
        ptype: 1,
        observables: vec![], // No observables!
        ..Default::default()
    };

    // Gadget type similar to the canonical form
    let gadget_type = bin::GadgetType {
        gtype: 1,
        inputs: vec![],
        outputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        measurements: vec![bin::gadget_type::Measurement::default()],
        readouts: vec![bin::gadget_type::Readout {
            measurement_indices: vec![0],
            ..Default::default()
        }],
        // rows=0 (output obs), cols=1 (input obs + 1)
        correction_propagation: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        // rows=1 (readouts), cols=1 (input obs + 1)
        readout_propagation: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        // rows=0 (output obs), cols=1 (readouts)
        logical_correction: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        ..Default::default()
    };

    // Check model type with one check
    let check_model_type = bin::CheckModelType {
        ctype: 1,
        gtype: 1,
        checks: vec![bin::check_model_type::Check {
            measurements: vec![bin::check_model_type::RemoteMeasurement {
                measurement_index: 0,
                remote_gadget: None,
            }],
            naturally_flipped: false,
            ..Default::default()
        }],
        remote_gadgets: vec![],
        ..Default::default()
    };

    // Error model type with one error
    let error_model_type = bin::ErrorModelType {
        etype: 1,
        ctype: 1,
        errors: vec![bin::error_model_type::Error {
            probability: 0.1,
            checks: vec![bin::error_model_type::RemoteCheck {
                check_index: 0,
                remote_check_model: None,
            }],
            residual: vec![],
            readout_flips: vec![],
            ..Default::default()
        }],
        remote_check_models: vec![],
        ..Default::default()
    };

    bin::Library {
        port_types: vec![port_type],
        gadget_types: vec![gadget_type],
        check_model_types: vec![check_model_type],
        error_model_types: vec![error_model_type],
        ..Default::default()
    }
}

#[tokio::test]
async fn test_monolithic_coordinator_load_library() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // Verify types were loaded
    let gadget_types = coordinator.gadget_types.read().await;
    assert!(gadget_types.contains_key(&1));

    let check_model_types = coordinator.check_model_types.read().await;
    assert!(check_model_types.contains_key(&1));

    let error_model_types = coordinator.error_model_types.read().await;
    assert!(error_model_types.contains_key(&1));
}

#[tokio::test]
async fn test_monolithic_coordinator_reset() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // Reset with library
    Coordinator::reset(
        &coordinator,
        Request::new(deq_runtime::coordinator::ResetRequest {
            reset_library: true,
            reset_decoder_service: true,
            ..Default::default()
        }),
    )
    .await
    .unwrap();

    // Verify library was cleared
    let gadget_types = coordinator.gadget_types.read().await;
    assert!(gadget_types.is_empty());

    // Verify ID counters were reset
    let next_gid = *coordinator.next_gid.lock().await;
    assert_eq!(next_gid, 1);

    // Verify decoder was reset
    let state = mock.state.read().await;
    assert_eq!(state.reset_count, 1);
}

#[tokio::test]
async fn test_monolithic_coordinator_auto_assigned_gid() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // Auto-assign (gid=0)
    let gadget = make_gadget(0, 1, vec![]);
    let response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(gadget)),
        }),
    )
    .await
    .unwrap();

    let gid = response.into_inner().id;
    assert_eq!(gid, 1);

    // Verify gadget exists
    let gadgets = coordinator.gadgets.read().await;
    assert!(gadgets.contains_key(&1));
}

#[tokio::test]
async fn test_monolithic_coordinator_user_provided_gid() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // User provides gid=100
    let gadget = make_gadget(100, 1, vec![]);
    let response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(gadget)),
        }),
    )
    .await
    .unwrap();

    assert_eq!(response.into_inner().id, 100);

    // Verify gadget exists with correct id
    let gadgets = coordinator.gadgets.read().await;
    assert!(gadgets.contains_key(&100));
}

#[tokio::test]
async fn test_monolithic_coordinator_mixed_gid_assignment() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // User provides gid=1 (would conflict with first auto-assignment)
    let gadget1 = make_gadget(1, 1, vec![]);
    let response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(gadget1)),
        }),
    )
    .await
    .unwrap();
    assert_eq!(response.into_inner().id, 1);

    // Auto-assign should skip 1 and use 2
    let gadget2 = make_gadget(0, 1, vec![]);
    let response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(gadget2)),
        }),
    )
    .await
    .unwrap();
    assert_eq!(response.into_inner().id, 2);

    // Verify both gadgets exist
    let gadgets = coordinator.gadgets.read().await;
    assert!(gadgets.contains_key(&1));
    assert!(gadgets.contains_key(&2));
}

#[tokio::test]
async fn test_monolithic_coordinator_cid_assignment() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // Create gadget first
    let gadget = make_gadget(0, 1, vec![]);
    let gid_response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(gadget)),
        }),
    )
    .await
    .unwrap();
    let gid = gid_response.into_inner().id;

    // User provides cid=50
    let check_model = make_check_model(50, 1, gid);
    let response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(check_model)),
        }),
    )
    .await
    .unwrap();

    assert_eq!(response.into_inner().id, 50);

    // Verify check model exists
    let check_models = coordinator.check_models.read().await;
    assert!(check_models.contains_key(&50));
}

#[tokio::test]
async fn test_monolithic_coordinator_eid_assignment() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_canonical_library()))
        .await
        .unwrap();

    // Create gadget
    let gadget = make_gadget(0, 1, vec![]);
    let gid = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(gadget)),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;

    // Create check model
    let check_model = make_check_model(0, 1, gid);
    let cid = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(check_model)),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;

    // User provides eid=99
    let error_model = make_error_model(99, 1, cid);
    let response = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(error_model)),
        }),
    )
    .await
    .unwrap();

    assert_eq!(response.into_inner().id, 99);

    // Verify error model exists
    let error_models = coordinator.error_models.read().await;
    assert!(error_models.contains_key(&99));
}

/// Creates the default_library from the Python test suite (library_validator_test.py).
/// This is a complete library with:
/// - 2 port types (rep-code with 1 observable, surface-code with 2 observables)
/// - 3 gadget types (initialize, cnot, measure)
/// - 2 check model types
/// - 2 error model types
fn make_default_library() -> bin::Library {
    // Port types
    let port_type_rep = bin::PortType {
        ptype: 1,
        name: "rep-code".to_string(),
        observables: vec![bin::port_type::Observable {
            tag: "logical_z".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };

    let port_type_surface = bin::PortType {
        ptype: 2,
        name: "surface-code".to_string(),
        observables: vec![
            bin::port_type::Observable {
                tag: "logical_x".to_string(),
                ..Default::default()
            },
            bin::port_type::Observable {
                tag: "logical_z".to_string(),
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    // Gadget type 1: initialize (no inputs, 1 output of ptype=1)
    // correction_propagation: rows=1 (output obs), cols=1 (0 input obs + 1)
    let gadget_type_initialize = bin::GadgetType {
        gtype: 1,
        name: "initialize".to_string(),
        inputs: vec![],
        outputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        measurements: vec![
            bin::gadget_type::Measurement {
                tag: "m1".to_string(),
                ..Default::default()
            },
            bin::gadget_type::Measurement {
                tag: "m2".to_string(),
                ..Default::default()
            },
        ],
        // correction_propagation: rows=1 (output obs), cols=1 (0 input obs + 1)
        correction_propagation: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        // logical_correction: rows=1 (output obs), cols=0 (0 readouts)
        logical_correction: Some(BitMatrix {
            rows: 1,
            cols: 0,
            ..Default::default()
        }),
        // readout_propagation: rows=0 (0 readouts), cols=1 (0 input obs + 1)
        readout_propagation: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 1,
            cols: 2,
            ..Default::default()
        }),
        ..Default::default()
    };

    // Gadget type 2: cnot (1 input of ptype=1, 1 output of ptype=2)
    // input has 1 observable, output has 2 observables
    // 2 measurements, 0 readouts
    let gadget_type_cnot = bin::GadgetType {
        gtype: 2,
        name: "cnot".to_string(),
        inputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        outputs: vec![bin::gadget_type::Port {
            ptype: 2,
            ..Default::default()
        }],
        measurements: vec![
            bin::gadget_type::Measurement {
                tag: "m3".to_string(),
                ..Default::default()
            },
            bin::gadget_type::Measurement {
                tag: "m4".to_string(),
                ..Default::default()
            },
        ],
        // correction_propagation: rows=2 (output obs), cols=2 (1 input obs + 1)
        // bits set at (0,0) and (0,1)
        correction_propagation: Some(BitMatrix {
            rows: 2,
            cols: 2,
            i: vec![0, 0],
            j: vec![0, 1],
        }),
        // logical_correction: rows=2 (output obs), cols=0 (0 readouts)
        logical_correction: Some(BitMatrix {
            rows: 2,
            cols: 0,
            ..Default::default()
        }),
        // readout_propagation: rows=0 (0 readouts), cols=2 (1 input obs + 1)
        readout_propagation: Some(BitMatrix {
            rows: 0,
            cols: 2,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 2,
            cols: 2,
            ..Default::default()
        }),
        ..Default::default()
    };

    // Gadget type 3: measure (1 input of ptype=2, no outputs)
    // input has 2 observables
    // readout_propagation: rows=1 (readouts), cols=3 (2 input obs + 1)
    let gadget_type_measure = bin::GadgetType {
        gtype: 3,
        name: "measure".to_string(),
        inputs: vec![bin::gadget_type::Port {
            ptype: 2,
            ..Default::default()
        }],
        outputs: vec![],
        measurements: vec![
            bin::gadget_type::Measurement {
                tag: "m5".to_string(),
                ..Default::default()
            },
            bin::gadget_type::Measurement {
                tag: "m6".to_string(),
                ..Default::default()
            },
            bin::gadget_type::Measurement {
                tag: "m7".to_string(),
                ..Default::default()
            },
        ],
        readouts: vec![bin::gadget_type::Readout {
            tag: "r1".to_string(),
            measurement_indices: vec![0, 2],
            ..Default::default()
        }],
        // rows=1, cols=3, bits set at (0,0) and (0,2)
        readout_propagation: Some(BitMatrix {
            rows: 1,
            cols: 3,
            i: vec![0, 0],
            j: vec![0, 2],
        }),
        // correction_propagation: rows=0, cols=3 (no outputs)
        correction_propagation: Some(BitMatrix {
            rows: 0,
            cols: 3,
            ..Default::default()
        }),
        // logical_correction: rows=0, cols=1
        logical_correction: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 0,
            cols: 3,
            ..Default::default()
        }),
        ..Default::default()
    };

    // Check model type 1: attached to gtype=2
    let check_model_type_1 = bin::CheckModelType {
        ctype: 1,
        gtype: 2,
        remote_gadgets: vec![
            bin::check_model_type::RemoteGadget {
                port: Some(bin::check_model_type::remote_gadget::Port::Input(0)),
                expecting_gtype: 1,
                measurement_bias: 1,
                ..Default::default()
            },
            bin::check_model_type::RemoteGadget {
                port: Some(bin::check_model_type::remote_gadget::Port::Output(0)),
                previous_remote_gadget: Some(0),
                expecting_gtype: 2,
                ..Default::default()
            },
            bin::check_model_type::RemoteGadget {
                port: Some(bin::check_model_type::remote_gadget::Port::Output(0)),
                previous_remote_gadget: None,
                expecting_gtype: 3,
                ..Default::default()
            },
        ],
        checks: vec![
            bin::check_model_type::Check {
                tag: "c1".to_string(),
                measurements: vec![
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 1,
                        remote_gadget: None,
                    },
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 0,
                        remote_gadget: Some(0),
                    },
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 0,
                        remote_gadget: Some(1),
                    },
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 1,
                        remote_gadget: Some(2),
                    },
                ],
                ..Default::default()
            },
            bin::check_model_type::Check {
                tag: "c2".to_string(),
                ..Default::default()
            },
            bin::check_model_type::Check {
                tag: "c3".to_string(),
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    // Check model type 2: attached to gtype=3
    let check_model_type_2 = bin::CheckModelType {
        ctype: 2,
        gtype: 3,
        remote_gadgets: vec![bin::check_model_type::RemoteGadget {
            port: Some(bin::check_model_type::remote_gadget::Port::Input(0)),
            expecting_gtype: 2,
            ..Default::default()
        }],
        checks: vec![
            bin::check_model_type::Check {
                tag: "c4".to_string(),
                measurements: vec![
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 0,
                        remote_gadget: None,
                    },
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 1,
                        remote_gadget: None,
                    },
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 2,
                        remote_gadget: None,
                    },
                    bin::check_model_type::RemoteMeasurement {
                        measurement_index: 0,
                        remote_gadget: Some(0),
                    },
                ],
                ..Default::default()
            },
            bin::check_model_type::Check {
                tag: "c5".to_string(),
                ..Default::default()
            },
            bin::check_model_type::Check {
                tag: "c6".to_string(),
                ..Default::default()
            },
        ],
        ..Default::default()
    };

    // Error model type 1: attached to ctype=1
    let error_model_type_1 = bin::ErrorModelType {
        etype: 1,
        ctype: 1,
        remote_check_models: vec![
            bin::error_model_type::RemoteCheckModel {
                port: Some(bin::error_model_type::remote_check_model::Port::Output(0)),
                expecting_ctype: 2,
                ..Default::default()
            },
            bin::error_model_type::RemoteCheckModel {
                port: Some(bin::error_model_type::remote_check_model::Port::Input(0)),
                previous_remote_check_model: Some(0),
                expecting_ctype: 1,
                ..Default::default()
            },
            bin::error_model_type::RemoteCheckModel {
                port: Some(bin::error_model_type::remote_check_model::Port::Output(0)),
                expecting_ctype: 2,
                ..Default::default()
            },
        ],
        errors: vec![bin::error_model_type::Error {
            probability: 0.1,
            residual: vec![0],
            checks: vec![
                bin::error_model_type::RemoteCheck {
                    check_index: 0,
                    remote_check_model: None,
                },
                bin::error_model_type::RemoteCheck {
                    check_index: 1,
                    remote_check_model: Some(1),
                },
                bin::error_model_type::RemoteCheck {
                    check_index: 1,
                    remote_check_model: Some(2),
                },
            ],
            ..Default::default()
        }],
        ..Default::default()
    };

    // Error model type 2: attached to ctype=2
    let error_model_type_2 = bin::ErrorModelType {
        etype: 2,
        ctype: 2,
        remote_check_models: vec![bin::error_model_type::RemoteCheckModel {
            port: Some(bin::error_model_type::remote_check_model::Port::Input(0)),
            expecting_ctype: 1,
            ..Default::default()
        }],
        errors: vec![bin::error_model_type::Error {
            probability: 0.1,
            readout_flips: vec![0],
            ..Default::default()
        }],
        ..Default::default()
    };

    bin::Library {
        port_types: vec![port_type_rep, port_type_surface],
        gadget_types: vec![gadget_type_initialize, gadget_type_cnot, gadget_type_measure],
        check_model_types: vec![check_model_type_1, check_model_type_2],
        error_model_types: vec![error_model_type_1, error_model_type_2],
        ..Default::default()
    }
}

/// Test that executing the default_library program produces the correct internal state.
/// This mirrors the structure from Python test library_validator_test.py.
///
/// The program creates:
/// - 3 gadgets (initialize, cnot, measure)
/// - 2 check models (ctype=1 attached to gid=2, ctype=2 attached to gid=3)
/// - 2 error models (etype=1 attached to cid=1, etype=2 attached to cid=2)
///
/// The check model types have:
/// - ctype=1: 3 checks (c1, c2, c3)
/// - ctype=2: 3 checks (c4, c5, c6)
/// Total: 6 checks
///
/// The error model types have:
/// - etype=1: 1 error touching 3 checks
/// - etype=2: 1 error with readout flip
/// Total: 2 errors
#[tokio::test]
async fn test_hypergraph_construction_with_default_library() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    // Load the library
    Coordinator::load_library(&coordinator, Request::new(make_default_library()))
        .await
        .unwrap();

    // Execute the program as in default_library:
    // 1. gadget(gtype=1, tag="initialize")
    let gid1 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 1,
                tag: "initialize".to_string(),
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(gid1, 1);

    // 2. gadget(gtype=2, tag="idle", connector to gid=1 port=0)
    let gid2 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 2,
                tag: "idle".to_string(),
                connectors: vec![bin::gadget::Connector { gid: 1, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(gid2, 2);

    // 3. check_model(ctype=1, gid=2)
    let cid1 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 0,
                ctype: 1,
                gid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(cid1, 1);

    // 4. error_model(etype=1, cid=1)
    let eid1 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 0,
                etype: 1,
                cid: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(eid1, 1);

    // 5. gadget(gtype=3, tag="measure", connector to gid=2 port=0)
    let gid3 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 3,
                tag: "measure".to_string(),
                connectors: vec![bin::gadget::Connector { gid: 2, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(gid3, 3);

    // 6. check_model(ctype=2, gid=3)
    let cid2 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 0,
                ctype: 2,
                gid: 3,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(cid2, 2);

    // 7. error_model(etype=2, cid=2)
    let eid2 = Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 0,
                etype: 2,
                cid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap()
    .into_inner()
    .id;
    assert_eq!(eid2, 2);

    // Verify the internal state was correctly constructed
    // 3 gadgets
    let gadgets = coordinator.gadgets.read().await;
    assert_eq!(gadgets.len(), 3, "Expected 3 gadgets");
    assert!(gadgets.contains_key(&1), "gid=1 should exist");
    assert!(gadgets.contains_key(&2), "gid=2 should exist");
    assert!(gadgets.contains_key(&3), "gid=3 should exist");

    // Verify gadget types
    assert_eq!(gadgets.get(&1).unwrap().instance.gtype, 1);
    assert_eq!(gadgets.get(&2).unwrap().instance.gtype, 2);
    assert_eq!(gadgets.get(&3).unwrap().instance.gtype, 3);

    // Verify connectors
    assert!(gadgets.get(&1).unwrap().instance.connectors.is_empty());
    assert_eq!(gadgets.get(&2).unwrap().instance.connectors.len(), 1);
    assert_eq!(gadgets.get(&2).unwrap().instance.connectors[0].gid, 1);
    assert_eq!(gadgets.get(&3).unwrap().instance.connectors.len(), 1);
    assert_eq!(gadgets.get(&3).unwrap().instance.connectors[0].gid, 2);
    drop(gadgets);

    // 2 check models
    let check_models = coordinator.check_models.read().await;
    assert_eq!(check_models.len(), 2, "Expected 2 check models");
    assert!(check_models.contains_key(&1), "cid=1 should exist");
    assert!(check_models.contains_key(&2), "cid=2 should exist");

    // Verify check model bindings
    assert_eq!(check_models.get(&1).unwrap().instance.gid, 2);
    assert_eq!(check_models.get(&1).unwrap().instance.ctype, 1);
    assert_eq!(check_models.get(&2).unwrap().instance.gid, 3);
    assert_eq!(check_models.get(&2).unwrap().instance.ctype, 2);
    drop(check_models);

    // 2 error models
    let error_models = coordinator.error_models.read().await;
    assert_eq!(error_models.len(), 2, "Expected 2 error models");
    assert!(error_models.contains_key(&1), "eid=1 should exist");
    assert!(error_models.contains_key(&2), "eid=2 should exist");

    // Verify error model bindings
    assert_eq!(error_models.get(&1).unwrap().instance.cid, 1);
    assert_eq!(error_models.get(&1).unwrap().instance.etype, 1);
    assert_eq!(error_models.get(&2).unwrap().instance.cid, 2);
    assert_eq!(error_models.get(&2).unwrap().instance.etype, 2);
    drop(error_models);

    // Verify the check model types have the expected number of checks
    let check_model_types = coordinator.check_model_types.read().await;
    let cmt1 = check_model_types.get(&1).unwrap();
    let cmt2 = check_model_types.get(&2).unwrap();
    assert_eq!(cmt1.checks.len(), 3, "ctype=1 should have 3 checks");
    assert_eq!(cmt2.checks.len(), 3, "ctype=2 should have 3 checks");
    drop(check_model_types);

    // Verify the error model types have the expected number of errors
    let error_model_types = coordinator.error_model_types.read().await;
    let emt1 = error_model_types.get(&1).unwrap();
    let emt2 = error_model_types.get(&2).unwrap();
    assert_eq!(emt1.errors.len(), 1, "etype=1 should have 1 error");
    assert_eq!(emt2.errors.len(), 1, "etype=2 should have 1 error");

    // Verify error details
    assert!(
        (emt1.errors[0].probability - 0.1).abs() < 1e-9,
        "etype=1 error probability should be 0.1"
    );
    assert!(
        (emt2.errors[0].probability - 0.1).abs() < 1e-9,
        "etype=2 error probability should be 0.1"
    );

    // etype=1 error should touch 3 checks
    assert_eq!(emt1.errors[0].checks.len(), 3, "etype=1 error should reference 3 checks");

    // etype=2 error should have 1 readout flip
    assert_eq!(
        emt2.errors[0].readout_flips.len(),
        1,
        "etype=2 error should have 1 readout flip"
    );
}

/// Test that invoking decode triggers hypergraph construction and sends it to the decoder.
/// Uses the default_library and provides measurement outcomes to trigger the decode flow.
#[tokio::test]
async fn test_decode_triggers_hypergraph_construction() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    // Load the library
    Coordinator::load_library(&coordinator, Request::new(make_default_library()))
        .await
        .unwrap();

    // Execute the full program
    // 1. gadget(gtype=1)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // 2. gadget(gtype=2, connector to gid=1)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 2,
                connectors: vec![bin::gadget::Connector { gid: 1, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // 3. check_model(ctype=1, gid=2)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 0,
                ctype: 1,
                gid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // 4. error_model(etype=1, cid=1)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 0,
                etype: 1,
                cid: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // 5. gadget(gtype=3, connector to gid=2)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 3,
                connectors: vec![bin::gadget::Connector { gid: 2, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // 6. check_model(ctype=2, gid=3)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 0,
                ctype: 2,
                gid: 3,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // 7. error_model(etype=2, cid=2)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 0,
                etype: 2,
                cid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // Now load outcomes for all gadgets to trigger decode
    // gid=1 has 2 measurements, gid=2 has 2 measurements, gid=3 has 3 measurements
    // Note: decode() awaits until the final gadget completes decoding.
    // We must call all decodes concurrently, otherwise non-final gadgets block forever.

    let coordinator_clone1 = &coordinator;
    let coordinator_clone2 = &coordinator;
    let coordinator_clone3 = &coordinator;

    // Spawn all decode calls concurrently using tokio::join!
    let (result1, result2, result3) = tokio::join!(
        async {
            Coordinator::decode(
                coordinator_clone1,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 1,
                    outcomes: Some(BitVector { data: vec![0], size: 2 }),
                    ..Default::default()
                }),
            )
            .await
        },
        async {
            Coordinator::decode(
                coordinator_clone2,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 2,
                    outcomes: Some(BitVector { data: vec![0], size: 2 }),
                    ..Default::default()
                }),
            )
            .await
        },
        async {
            Coordinator::decode(
                coordinator_clone3,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 3,
                    outcomes: Some(BitVector { data: vec![0], size: 3 }),
                    ..Default::default()
                }),
            )
            .await
        }
    );

    result1.unwrap();
    result2.unwrap();
    result3.unwrap();

    // Verify the hypergraph was sent to the decoder
    let state = mock.state.read().await;

    // With persistent_decoder=false, decode_calls should have been made
    // (not load_hypergraph + decode_loaded)
    assert!(
        !state.decode_calls.is_empty() || !state.loaded_hypergraphs.is_empty(),
        "Expected either decode_calls or loaded_hypergraphs"
    );

    // Check the hypergraph structure
    if !state.decode_calls.is_empty() {
        let hypergraph = &state.decode_calls[0].hypergraph;

        // The canonical form has 6 checks (vertices)
        assert_eq!(hypergraph.vertex_num, 6, "Expected 6 vertices (checks) in the hypergraph");

        // Only errors with non-trivial syndrome (checks) are included in hypergraph.
        // etype=2 only has readout_flips and no checks, so it's not included.
        // Thus we expect 1 hyperedge (from etype=1).
        assert_eq!(
            hypergraph.hyperedges.len(),
            1,
            "Expected 1 hyperedge (error with checks) in the hypergraph"
        );

        // Verify error probability
        let first_error = &hypergraph.hyperedges[0];
        assert!(
            (first_error.probability - 0.1).abs() < 1e-9,
            "Expected probability 0.1, got {}",
            first_error.probability
        );

        // First error should touch 3 checks (c1, c2, c5 = indices 0, 1, 4)
        assert_eq!(first_error.vertices.len(), 3, "First error should touch 3 checks");
        assert!(first_error.vertices.contains(&0), "Error should touch check 0");
        assert!(first_error.vertices.contains(&1), "Error should touch check 1");
        assert!(first_error.vertices.contains(&4), "Error should touch check 4");
    }
}

/// Test remote_conditional_correction with a chain of gadgets where the correction actually affects
/// the output observable.
///
/// Setup:
/// - Three gadgets: gid=1 -> gid=2 -> gid=3
/// - Gadget 2 has remote_conditional_correction referencing gadget 1's readout
/// - This tests that the remote correction is correctly applied across multiple gadgets
#[tokio::test]
async fn test_remote_conditional_correction_affects_residual() {
    let mock = make_mock_decoder();
    let coordinator = make_coordinator(mock.clone());

    // Port type with 1 observable
    let port_type = bin::PortType {
        ptype: 1,
        observables: vec![bin::port_type::Observable {
            tag: "Z".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };

    // Gadget type 1: source gadget with 1 output, 1 readout
    let gadget_type_1 = bin::GadgetType {
        gtype: 1,
        inputs: vec![],
        outputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        measurements: vec![bin::gadget_type::Measurement::default()],
        readouts: vec![bin::gadget_type::Readout {
            measurement_indices: vec![0],
            ..Default::default()
        }],
        correction_propagation: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        readout_propagation: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        logical_correction: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        ..Default::default()
    };

    // Gadget type 2: middle gadget with 1 input, 1 output, 1 readout
    let gadget_type_2 = bin::GadgetType {
        gtype: 2,
        inputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        outputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        measurements: vec![bin::gadget_type::Measurement::default()],
        readouts: vec![bin::gadget_type::Readout {
            measurement_indices: vec![0],
            ..Default::default()
        }],
        // correction_propagation: pass through the input observable
        // rows=1 (output obs), cols=2 (1 input obs + 1)
        // Set bit at (0, 0) for output[0] = input[0]
        correction_propagation: Some(BitMatrix {
            rows: 1,
            cols: 2,
            i: vec![0],
            j: vec![0],
        }),
        readout_propagation: Some(BitMatrix {
            rows: 1,
            cols: 2,
            ..Default::default()
        }),
        logical_correction: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 1,
            cols: 1,
            ..Default::default()
        }),
        ..Default::default()
    };

    // Gadget type 3: sink gadget with 1 input, no outputs, 1 readout
    let gadget_type_3 = bin::GadgetType {
        gtype: 3,
        inputs: vec![bin::gadget_type::Port {
            ptype: 1,
            ..Default::default()
        }],
        outputs: vec![],
        measurements: vec![bin::gadget_type::Measurement::default()],
        readouts: vec![bin::gadget_type::Readout {
            measurement_indices: vec![0],
            ..Default::default()
        }],
        correction_propagation: Some(BitMatrix {
            rows: 0,
            cols: 2,
            ..Default::default()
        }),
        // Readout XORs with input observable
        // Set bit at (0, 0) for readout[0] XOR= input_observable[0]
        readout_propagation: Some(BitMatrix {
            rows: 1,
            cols: 2,
            i: vec![0],
            j: vec![0],
        }),
        logical_correction: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        physical_correction: Some(BitMatrix {
            rows: 0,
            cols: 1,
            ..Default::default()
        }),
        ..Default::default()
    };

    let check_model_type = bin::CheckModelType {
        ctype: 1,
        gtype: 0, // WILDCARD
        checks: vec![],
        ..Default::default()
    };

    let error_model_type = bin::ErrorModelType {
        etype: 1,
        ctype: 0, // WILDCARD
        errors: vec![],
        ..Default::default()
    };

    let library = bin::Library {
        port_types: vec![port_type],
        gadget_types: vec![gadget_type_1, gadget_type_2, gadget_type_3],
        check_model_types: vec![check_model_type],
        error_model_types: vec![error_model_type],
        ..Default::default()
    };

    Coordinator::load_library(&coordinator, Request::new(library)).await.unwrap();

    // Create gadget 1
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 1,
                gtype: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // Check model and error model for gadget 1
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 1,
                ctype: 1,
                gid: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 1,
                etype: 1,
                cid: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // Create gadget 2 (middle, with remote_conditional_correction from gadget 1)
    // The remote_conditional_correction XORs gadget 1's readout[0] into gadget 2's output observable
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 2,
                gtype: 2,
                connectors: vec![bin::gadget::Connector { gid: 1, port: 0 }],
                modifier: Some(bin::GadgetModifier {
                    remote_conditional_correction: Some(bin::RemoteConditionalCorrection {
                        remote_readouts: vec![bin::remote_conditional_correction::RemoteReadout {
                            gid: 1,
                            readout_index: 0,
                        }],
                        // Correction matrix: 1 row (1 output observable), 1 col (1 remote readout)
                        // output[0] XOR= remote_readout[0]
                        // Set bit at (0, 0)
                        correction: Some(BitMatrix {
                            rows: 1,
                            cols: 1,
                            i: vec![0],
                            j: vec![0],
                        }),
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 2,
                ctype: 1,
                gid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 2,
                etype: 1,
                cid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // Create gadget 3 (sink)
    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 3,
                gtype: 3,
                connectors: vec![bin::gadget::Connector { gid: 2, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 3,
                ctype: 1,
                gid: 3,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        &coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 3,
                etype: 1,
                cid: 3,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // Test case 1: gadget 1 readout = 1
    // Expected flow:
    // - Gadget 1: measurement=1, readout=1, residual=0 (no logical_correction effect)
    // - Gadget 2: has remote_conditional_correction that XORs gadget 1's readout (=1) into output observable
    //   So gadget 2's residual (output observable) = 1 XOR 0 = 1
    // - Gadget 3: readout XORs with input observable (from gadget 2 = 1)
    //   So gadget 3's readout = measurement[0] XOR input_observable[0] = 0 XOR 1 = 1
    //
    // Note: BitVector uses MSB-first encoding: bit 0 is at position 7 in the first byte.
    // So to set bit 0 = 1, use 0x80 (0b10000000), not 0x01.
    let (result1, result2, result3) = tokio::join!(
        async {
            Coordinator::decode(
                &coordinator,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 1,
                    outcomes: Some(BitVector {
                        data: vec![0x80], // measurement 0 = 1 (MSB-first: bit 0 at position 7)
                        size: 1,
                    }),
                    ..Default::default()
                }),
            )
            .await
        },
        async {
            Coordinator::decode(
                &coordinator,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 2,
                    outcomes: Some(BitVector {
                        data: vec![0x00], // measurement 0 = 0
                        size: 1,
                    }),
                    ..Default::default()
                }),
            )
            .await
        },
        async {
            Coordinator::decode(
                &coordinator,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 3,
                    outcomes: Some(BitVector {
                        data: vec![0x00], // measurement 0 = 0
                        size: 1,
                    }),
                    ..Default::default()
                }),
            )
            .await
        }
    );

    let readouts1 = result1.unwrap().into_inner().readouts.unwrap();
    let readouts2 = result2.unwrap().into_inner().readouts.unwrap();
    let readouts3 = result3.unwrap().into_inner().readouts.unwrap();

    // Verify decode completes successfully with expected sizes
    assert_eq!(readouts1.size, 1, "Gadget 1 should have 1 readout");
    assert_eq!(readouts2.size, 1, "Gadget 2 should have 1 readout");
    assert_eq!(readouts3.size, 1, "Gadget 3 should have 1 readout");

    // The remote_conditional_correction XORs gadget 1's readout into gadget 2's output observable.
    // This affects gadget 3's readout via readout_propagation (which XORs with input observable).
    //
    // Trace through the computation:
    // - Gadget 1: measurement=1, readout = raw XOR readout_propagation(input) = 1 XOR 0 = 1
    // - Gadget 2: residual = correction_propagation(input) XOR remote_cc(gadget1.readout)
    //             = 0 XOR 1 = 1 (the remote_conditional_correction applies gadget 1's readout)
    // - Gadget 3: readout = raw XOR readout_propagation(input) = 0 XOR gadget2.residual[0] = 0 XOR 1 = 1
    //
    // Note: Readout BitVector uses MSB-first: bit 0 is at position 7 in the first byte (0x80).
    // Verify actual readout values:
    assert_eq!(
        readouts1.data[0] & 0x80,
        0x80,
        "Gadget 1 readout should be 1 (from measurement)"
    );
    assert_eq!(
        readouts2.data[0] & 0x80,
        0,
        "Gadget 2 readout should be 0 (measurement=0, no readout_propagation)"
    );
    assert_eq!(
        readouts3.data[0] & 0x80,
        0x80,
        "Gadget 3 readout should be 1 (0 XOR input_observable from gadget 2's residual)"
    );
}

// ─── persistent_decoder cache-key regression tests ──────────────────────────
//
// These tests exercise the `MonolithicCoordinator::loaded_decoders` cache
// with `persistent_decoder: true`.  The cache is keyed by `DecoderCacheKey`,
// which (after the `fix/window-coordinator-cache-key` fix) must distinguish
// shots that share a `RelativeProgram` but differ in their resolved
// error-model state.  Under the previous key (which keyed only on
// `RelativeProgram`), the second shot below would incorrectly reuse the
// first shot's loaded hypergraph despite using a different probability
// modifier.

fn make_persistent_coordinator(mock: Arc<MockDecoder>) -> MonolithicCoordinator {
    let config = serde_json::json!({
        "persistent_decoder": true,
        "merge_hyperedges": false
    });
    MonolithicCoordinator::new(config, make_decoder_client(mock))
}

/// Build the canonical three-gadget program (initialize → cnot → measure) and
/// attach error models with the supplied probability modifiers, then trigger
/// the decode pipeline by submitting outcomes concurrently for all gadgets.
async fn run_canonical_shot(
    coordinator: &MonolithicCoordinator,
    modifier_for_etype_1: Option<bin::ProbabilityModifier>,
    modifier_for_etype_2: Option<bin::ProbabilityModifier>,
) {
    let wrap_modifier = |pm: Option<bin::ProbabilityModifier>| {
        pm.map(|p| bin::error_model::ErrorModelModifier {
            probability_modifier: Some(p),
            reroute_remote_check_models: vec![],
        })
    };

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 1,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 2,
                connectors: vec![bin::gadget::Connector { gid: 1, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 0,
                ctype: 1,
                gid: 2,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 0,
                etype: 1,
                cid: 1,
                modifier: wrap_modifier(modifier_for_etype_1),
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::Gadget(bin::Gadget {
                gid: 0,
                gtype: 3,
                connectors: vec![bin::gadget::Connector { gid: 2, port: 0 }],
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::CheckModel(bin::CheckModel {
                cid: 0,
                ctype: 2,
                gid: 3,
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    Coordinator::execute(
        coordinator,
        Request::new(bin::Instruction {
            create: Some(instruction::Create::ErrorModel(bin::ErrorModel {
                eid: 0,
                etype: 2,
                cid: 2,
                modifier: wrap_modifier(modifier_for_etype_2),
                ..Default::default()
            })),
        }),
    )
    .await
    .unwrap();

    // All three decode calls must be submitted concurrently — see the note
    // in `test_decode_triggers_hypergraph_construction`.
    let (r1, r2, r3) = tokio::join!(
        async {
            Coordinator::decode(
                coordinator,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 1,
                    outcomes: Some(BitVector { data: vec![0], size: 2 }),
                    ..Default::default()
                }),
            )
            .await
        },
        async {
            Coordinator::decode(
                coordinator,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 2,
                    outcomes: Some(BitVector { data: vec![0], size: 2 }),
                    ..Default::default()
                }),
            )
            .await
        },
        async {
            Coordinator::decode(
                coordinator,
                Request::new(deq_runtime::coordinator::Outcomes {
                    gid: 3,
                    outcomes: Some(BitVector { data: vec![0], size: 3 }),
                    ..Default::default()
                }),
            )
            .await
        }
    );
    r1.unwrap();
    r2.unwrap();
    r3.unwrap();
}

/// Reset between shots, keeping the library and the persisted decoder cache.
async fn reset_keeping_library_and_decoder(coordinator: &MonolithicCoordinator) {
    Coordinator::reset(
        coordinator,
        Request::new(deq_runtime::coordinator::ResetRequest {
            reset_library: false,
            reset_decoder_service: false,
            ..Default::default()
        }),
    )
    .await
    .unwrap();
}

/// Regression test for `loaded_decoders` cache-key correctness.
///
/// Drives two shots with identical `RelativeProgram` but with the
/// probability modifier on `etype=1` switched from `0.1` to `0.2` in the
/// second shot.  Under the new `DecoderCacheKey` the
/// `ErrorModelFingerprint` for that slot must differ, forcing a second
/// `load_hypergraph` call.  Under the old key (which keyed only on
/// `RelativeProgram`) the second shot would incorrectly reuse the cached
/// hypergraph built with the `0.1` probability.
#[tokio::test]
async fn test_persistent_decoder_distinguishes_probability_modifier_across_shots() {
    let mock = make_mock_decoder();
    let coordinator = make_persistent_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_default_library()))
        .await
        .unwrap();

    // Shot 1: probability modifier p = 0.1 on etype=1.
    run_canonical_shot(
        &coordinator,
        Some(bin::ProbabilityModifier {
            probabilities: vec![0.1],
            ..Default::default()
        }),
        None,
    )
    .await;

    reset_keeping_library_and_decoder(&coordinator).await;

    // Shot 2: same program shape, but probability modifier p = 0.2 on
    // etype=1.  Different `DecoderCacheKey` → new `load_hypergraph` call.
    run_canonical_shot(
        &coordinator,
        Some(bin::ProbabilityModifier {
            probabilities: vec![0.2],
            ..Default::default()
        }),
        None,
    )
    .await;

    let mock_state = mock.state.read().await;
    assert_eq!(
        mock_state.loaded_hypergraphs.len(),
        2,
        "Expected 2 distinct loaded hypergraphs (one per modifier), got {}; old cache key \
         would reuse the first one and report 1",
        mock_state.loaded_hypergraphs.len(),
    );
    let loaded_decoders = coordinator.loaded_decoders.read().await;
    assert_eq!(
        loaded_decoders.len(),
        2,
        "Expected 2 distinct DecoderCacheKey entries (one per modifier), got {}",
        loaded_decoders.len(),
    );
}

/// Positive control: two shots with *identical* error-model modifier must
/// reuse the cached hypergraph (cache hit on the second shot), so exactly
/// one `load_hypergraph` call is observed and a `decode_loaded` call is
/// served from the cache.  This guards the other direction — the new key
/// must not be over-strict.
#[tokio::test]
async fn test_persistent_decoder_reuses_cache_when_modifier_unchanged() {
    let mock = make_mock_decoder();
    let coordinator = make_persistent_coordinator(mock.clone());

    Coordinator::load_library(&coordinator, Request::new(make_default_library()))
        .await
        .unwrap();

    let modifier = bin::ProbabilityModifier {
        probabilities: vec![0.1],
        ..Default::default()
    };

    run_canonical_shot(&coordinator, Some(modifier.clone()), None).await;
    reset_keeping_library_and_decoder(&coordinator).await;
    run_canonical_shot(&coordinator, Some(modifier), None).await;

    let mock_state = mock.state.read().await;
    assert_eq!(
        mock_state.loaded_hypergraphs.len(),
        1,
        "Expected 1 cached hypergraph reused across both shots, got {}",
        mock_state.loaded_hypergraphs.len(),
    );
    assert!(
        !mock_state.decode_loaded_calls.is_empty(),
        "Expected the second shot to hit the cache and call decode_loaded",
    );
    let loaded_decoders = coordinator.loaded_decoders.read().await;
    assert_eq!(loaded_decoders.len(), 1, "Expected a single cache entry");
}