deq-runtime 0.8.0-rc1

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
//! Pauli Frame Tracker
//!
//! Tracking how the logical readout changes on the gadget correction, and
//! propagate the changes accordingly
//!
//! When using this Pauli frame tracker in a committed decoding (e.g. window decoding)
//! where the decoded result of each gadget is never changed once it's committed,
//! this tracker ensures that it will return the `PauliFrameUpdate` only once (but not
//! necessarily in the function call to that gadget, because it's history gadget may
//! not have been committed yet)
//!
//! When the decoder may sometimes update the committed result, it's still permitted
//! but the function will only return the updated logical readouts and ignore those
//! unchanged ones
//!
//! Note that this is a preliminary implementation, where it might have to visit
//! the same gadget multiple times in a single update; a more mature implementation
//! should sort the gadgets so that visiting each gadget once should work. However
//! that would require building more complicated data structures.
//!

use crate::misc::bit_matrix::{apply_modifier, optional_sparse_to_dense};
use crate::misc::bit_vector::get_bit;
use crate::{bin, util};
use binar::{BitMatrix, BitVec, BitwisePairMut};
use hashbrown::{HashMap, HashSet};
use std::sync::Arc;

pub struct PauliFrameTracker {
    pub gadgets: HashMap<u64, PauliFrameGadget>,
    retained_readouts: HashMap<u64, RetainedReadout>,
}

struct RetainedReadout {
    /// Keeps logical readouts available while positive; this entry is removed at zero.
    remaining: u64,
    /// Packed logical readout bits retained after the source gadget is collected.
    value: util::BitVector,
}

pub struct PauliFrameGadget {
    /// Marks a final frame whose raw measurements and decoded correction have been released.
    finalized: bool,
    /// Positive values retain logical readouts after collection; underdeclared hints saturate at zero.
    expected_remote_references: u64,
    /// Cached remote bits in committing mode; inner None entries await their source frames.
    remote_readout_values: Option<Vec<Option<bool>>>,
    /// the current error corrected readout and residual
    frame: Option<PauliFrame>,

    /// the raw value of the readouts before error correction; the values
    /// are loaded only after the measurements are ready for the gadget
    raw_readouts: Option<BitVec>,
    /// the raw measurement outcomes for this gadget; needed for physical_correction
    raw_measurements: Option<BitVec>,
    /// the correction from the decoder; the values are loaded only
    /// after the decoder has committed the errors; note that we still allow
    /// user to update this field, which will trigger an update of the error
    /// corrected readouts of this gadget and/or future gadgets
    decoded: Option<PauliFrame>,

    /// input observable to output observable
    pub(crate) correction_propagation: BitMatrix,
    /// input observable to readouts
    pub(crate) readout_propagation: BitMatrix,
    /// readouts to output observables
    pub(crate) logical_correction: BitMatrix,
    /// measurements to output observables
    physical_correction: BitMatrix,
    /// remote readouts to output observables
    /// (remote_readouts, correction_matrix)
    pub(crate) remote_conditional_correction: Option<(Vec<bin::remote_conditional_correction::RemoteReadout>, BitMatrix)>,

    /// the input connections
    pub(crate) inputs: Vec<bin::gadget::Connector>,
    /// the output peers
    outputs: Vec<Option<bin::gadget::Connector>>,
    /// gadgets that depend on this gadget's readout via remote_conditional_correction
    remote_dependents: Vec<u64>,
    /// the output bias for each port
    pub(crate) output_bias: Vec<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PauliFrame {
    /// the value of readouts
    readouts: BitVec,
    /// the value of output observables
    residual: BitVec,
}

impl PauliFrameGadget {
    #[must_use]
    pub fn num_readouts(&self) -> usize {
        self.logical_correction.column_count()
    }

    #[must_use]
    pub fn num_measurements(&self) -> usize {
        self.physical_correction.column_count()
    }

    #[must_use]
    pub fn num_input_observables(&self) -> usize {
        self.correction_propagation.column_count() - 1
    }

    #[must_use]
    pub fn num_output_observables(&self) -> usize {
        self.correction_propagation.row_count()
    }

    pub fn get_residual_slice(&self, residual: &BitVec, port: u64) -> Vec<bool> {
        let start = self.output_bias[port as usize];
        let end = if (port as usize) < self.output_bias.len() - 1 {
            self.output_bias[(port as usize) + 1]
        } else {
            self.num_output_observables()
        };
        use binar::Bitwise;
        (start..end).map(|i| residual.index(i)).collect()
    }
}

impl PauliFrameTracker {
    pub fn new() -> Self {
        Self {
            gadgets: Default::default(),
            retained_readouts: HashMap::new(),
        }
    }

    pub fn reset(&mut self) {
        self.gadgets.clear();
        self.retained_readouts.clear();
    }

    pub(crate) fn validate_remote_readouts(&self, modifier: Option<&bin::GadgetModifier>) -> Result<(), String> {
        if let Some(remote) = modifier.and_then(|modifier| modifier.remote_conditional_correction.as_ref()) {
            for readout in &remote.remote_readouts {
                let count = if let Some(gadget) = self.gadgets.get(&readout.gid) {
                    gadget.num_readouts() as u64
                } else if let Some(retained) = self.retained_readouts.get(&readout.gid) {
                    retained.value.size
                } else {
                    return Err(format!(
                        "logical readout source gid={} is unknown or already collected",
                        readout.gid
                    ));
                };
                if readout.readout_index >= count {
                    return Err(format!(
                        "readout index {} is out of range for gid={}",
                        readout.readout_index, readout.gid
                    ));
                }
            }
        }
        Ok(())
    }

    pub(crate) fn add_committing_gadget(
        &mut self,
        gadget: &bin::Gadget,
        gadget_type: &bin::GadgetType,
        port_types: &HashMap<u64, Arc<bin::PortType>>,
    ) -> Result<(), String> {
        self.validate_remote_readouts(gadget.modifier.as_ref())?;
        let references = gadget
            .modifier
            .as_ref()
            .and_then(|modifier| modifier.remote_conditional_correction.as_ref())
            .map(|remote| remote.remote_readouts.as_slice())
            .unwrap_or_default();
        let values = references
            .iter()
            .map(|readout| {
                if let Some(source) = self.gadgets.get(&readout.gid) {
                    source.frame.as_ref().map(|frame| {
                        use binar::Bitwise;
                        frame.readouts.index(usize::try_from(readout.readout_index).unwrap())
                    })
                } else {
                    Some(get_bit(&self.retained_readouts[&readout.gid].value, readout.readout_index))
                }
            })
            .collect();
        let sources: HashSet<_> = references.iter().map(|readout| readout.gid).collect();
        self.add_gadget_inner(
            gadget.gid,
            gadget_type,
            gadget.modifier.as_ref(),
            port_types,
            &gadget.connectors,
            gadget.expected_remote_references,
            Some(values),
        );
        for gid in sources {
            if let Some(source) = self.gadgets.get_mut(&gid) {
                source.expected_remote_references = source.expected_remote_references.saturating_sub(1);
            } else {
                let source = self.retained_readouts.get_mut(&gid).unwrap();
                source.remaining = source.remaining.saturating_sub(1);
                if source.remaining == 0 {
                    self.retained_readouts.remove(&gid);
                }
            }
        }
        Ok(())
    }

    pub(crate) fn collect_gadget(&mut self, gid: u64) {
        let gadget = self.gadgets.remove(&gid).expect("collected frame must exist");
        let frame = gadget.frame.expect("cannot collect an unfinished frame");
        if gadget.expected_remote_references > 0 && !frame.readouts.is_empty() {
            self.retained_readouts.insert(
                gid,
                RetainedReadout {
                    remaining: gadget.expected_remote_references,
                    value: crate::misc::bit_vector::binar_bitvec_to_bit_vector(&frame.readouts, frame.readouts.len()),
                },
            );
        }
    }

    pub(crate) fn retained_readout_count(&self) -> usize {
        self.retained_readouts.len()
    }

    pub(crate) fn retained_readout_bytes(&self) -> usize {
        self.retained_readouts.values().map(|readout| readout.value.data.len()).sum()
    }

    /// Discard raw measurements and corrections once a gadget's frame is final.
    /// Retain its frame and port layout for future children and remote readouts.
    ///
    /// # Panics
    /// Panics if the gadget does not exist or its frame is not yet available.
    pub fn finalize(&mut self, gid: u64) {
        let gadget = self.gadgets.get_mut(&gid).expect("unknown finalized gadget");
        assert!(gadget.frame.is_some(), "cannot finalize a pending frame");
        gadget.finalized = true;
        gadget.raw_readouts = None;
        gadget.raw_measurements = None;
        gadget.decoded = None;
    }

    pub fn add_gadget(
        &mut self,
        gid: u64,
        gadget_type: &bin::GadgetType,
        gadget_modifier: Option<&bin::GadgetModifier>,
        port_types: &HashMap<u64, Arc<bin::PortType>>,
        connectors: &[bin::gadget::Connector],
    ) {
        self.add_gadget_inner(gid, gadget_type, gadget_modifier, port_types, connectors, 0, None);
    }

    #[allow(clippy::too_many_arguments)]
    fn add_gadget_inner(
        &mut self,
        gid: u64,
        gadget_type: &bin::GadgetType,
        gadget_modifier: Option<&bin::GadgetModifier>,
        port_types: &HashMap<u64, Arc<bin::PortType>>,
        connectors: &[bin::gadget::Connector],
        expected_remote_references: u64,
        remote_readout_values: Option<Vec<Option<bool>>>,
    ) {
        debug_assert!(!self.gadgets.contains_key(&gid));
        debug_assert!(gadget_type.inputs.len() == connectors.len());
        // get the port biases
        let mut output_observable_count = 0;
        let mut output_bias = Vec::with_capacity(gadget_type.outputs.len());
        for port in gadget_type.outputs.iter() {
            let port_type = port_types.get(&port.ptype).unwrap();
            output_bias.push(output_observable_count);
            output_observable_count += port_type.observables.len();
        }
        // get matrices and apply modifier if present
        let mut correction_propagation = optional_sparse_to_dense(&gadget_type.correction_propagation);
        let mut readout_propagation = optional_sparse_to_dense(&gadget_type.readout_propagation);
        let mut logical_correction = optional_sparse_to_dense(&gadget_type.logical_correction);
        let mut physical_correction = optional_sparse_to_dense(&gadget_type.physical_correction);
        let mut remote_conditional_correction = None;
        if let Some(modifier) = gadget_modifier {
            if let Some(mod_) = &modifier.correction_propagation_mod {
                correction_propagation = apply_modifier(correction_propagation, mod_);
            }
            if let Some(mod_) = &modifier.readout_propagation_mod {
                readout_propagation = apply_modifier(readout_propagation, mod_);
            }
            if let Some(mod_) = &modifier.logical_correction_mod {
                logical_correction = apply_modifier(logical_correction, mod_);
            }
            if let Some(mod_) = &modifier.physical_correction_mod {
                physical_correction = apply_modifier(physical_correction, mod_);
            }
            if let Some(remote_cc) = &modifier.remote_conditional_correction {
                let matrix = optional_sparse_to_dense(&remote_cc.correction);
                remote_conditional_correction = Some((remote_cc.remote_readouts.clone(), matrix));
            }
        }
        // create the gadget
        let gadget = PauliFrameGadget {
            finalized: false,
            expected_remote_references,
            remote_readout_values,
            frame: None,
            raw_readouts: None,
            raw_measurements: None,
            decoded: None,
            correction_propagation,
            readout_propagation,
            logical_correction,
            physical_correction,
            remote_conditional_correction: remote_conditional_correction.clone(),
            inputs: connectors.to_vec(),
            outputs: vec![None; gadget_type.outputs.len()],
            remote_dependents: vec![],
            output_bias,
        };
        debug_assert!(output_observable_count == gadget.num_output_observables());
        debug_assert!(gadget.logical_correction.row_count() == gadget.num_output_observables());
        debug_assert_eq!(gadget_type.readouts.len(), gadget.num_readouts());
        debug_assert!(gadget_type.measurements.len() == gadget.num_measurements());
        debug_assert!(gadget.readout_propagation.row_count() == gadget.num_readouts());
        debug_assert!(gadget.readout_propagation.column_count() == gadget.num_input_observables() + 1);
        self.gadgets.insert(gid, gadget);
        for (port, connector) in connectors.iter().enumerate() {
            self.gadgets.get_mut(&connector.gid).unwrap().outputs[connector.port as usize]
                .replace(bin::gadget::Connector { gid, port: port as u64 });
        }
        // register remote dependencies so that remote gadgets can trigger propagation
        if let Some((remote_refs, _)) = remote_conditional_correction {
            let snapshots = self.gadgets[&gid].remote_readout_values.is_some();
            let mut registered = HashSet::new();
            for remote_ref in remote_refs {
                if !registered.insert(remote_ref.gid) {
                    continue;
                }
                if let Some(source) = self.gadgets.get_mut(&remote_ref.gid)
                    && (!snapshots || source.frame.is_none())
                {
                    source.remote_dependents.push(gid);
                }
            }
        }
    }

    pub fn load_raw(&mut self, gid: u64, raw_readouts: &[bool], raw_measurements: &util::BitVector) {
        let gadget = self.gadgets.get_mut(&gid).unwrap();
        debug_assert!(gadget.raw_readouts.is_none());
        debug_assert!(gadget.raw_measurements.is_none());
        debug_assert!(gadget.num_readouts() == raw_readouts.len());
        debug_assert_eq!(gadget.num_measurements() as u64, raw_measurements.size);
        gadget.raw_readouts.replace(raw_readouts.iter().cloned().collect());
        gadget
            .raw_measurements
            .replace((0..raw_measurements.size).map(|i| get_bit(raw_measurements, i)).collect());
    }

    pub fn load_correction(&mut self, gid: u64, residual: BitVec, readout_flips: BitVec) -> HashMap<u64, util::BitVector> {
        let gadget = self.gadgets.get_mut(&gid).unwrap();
        assert!(!gadget.finalized, "cannot correct a finalized frame");
        debug_assert!(
            gadget.raw_readouts.is_some(),
            "raw readouts must be loaded first for gid={gid}"
        );
        gadget.decoded.replace(PauliFrame {
            residual,
            readouts: readout_flips,
        });
        let mut updates = HashMap::new();
        self.propagate_from(gid, &mut updates);
        updates
    }

    fn propagate_from(&mut self, gid: u64, updates: &mut HashMap<u64, util::BitVector>) {
        // first check if all the input peers have done their work; if not, return nothing
        let gadget = self.gadgets.get(&gid).unwrap();
        if gadget.decoded.is_none() {
            return;
        }
        let mut input_observables: Vec<bool> = vec![];
        for peer in gadget.inputs.iter() {
            let peer_gadget = self.gadgets.get(&peer.gid).unwrap();
            if let Some(frame) = peer_gadget.frame.as_ref() {
                input_observables.append(&mut peer_gadget.get_residual_slice(&frame.residual, peer.port));
            } else {
                return;
            }
        }
        // gather remote readouts for remote conditional correction if present
        let remote_readouts_vec: Option<BitVec> = if let Some(values) = &gadget.remote_readout_values {
            let Some(values) = values.iter().copied().collect::<Option<Vec<_>>>() else {
                return;
            };
            Some(values.into_iter().collect())
        } else if let Some((remote_refs, _)) = &gadget.remote_conditional_correction {
            let mut values = Vec::with_capacity(remote_refs.len());
            for remote_ref in remote_refs {
                let remote_gadget = self.gadgets.get(&remote_ref.gid).unwrap();
                if let Some(frame) = remote_gadget.frame.as_ref() {
                    use binar::Bitwise;
                    values.push(frame.readouts.index(remote_ref.readout_index as usize));
                } else {
                    return;
                }
            }
            Some(values.into_iter().collect())
        } else {
            None
        };
        // if input peers are all ready, let's calculate my pauli frame
        let input_observables: BitVec = input_observables.into_iter().chain([true]).collect();
        use std::ops::Mul;
        let mut residual = gadget.correction_propagation.mul(&input_observables.as_view());
        // apply physical_correction * measurements
        let raw_measurements = gadget.raw_measurements.as_ref().unwrap();
        residual.bitxor_assign(&gadget.physical_correction.mul(&raw_measurements.as_view()));
        let mut readouts = gadget.raw_readouts.clone().unwrap();
        let decoded = gadget.decoded.as_ref().unwrap();
        readouts.bitxor_assign(&decoded.readouts);
        readouts.bitxor_assign(&gadget.readout_propagation.mul(&input_observables.as_view()));
        residual.bitxor_assign(&gadget.logical_correction.mul(&readouts.as_view()));
        // apply remote conditional correction if present
        if let Some((_, correction_matrix)) = &gadget.remote_conditional_correction {
            residual.bitxor_assign(&correction_matrix.mul(&remote_readouts_vec.unwrap().as_view()));
        }
        residual.bitxor_assign(&decoded.residual);
        // check if the value has changed; if the value is unchanged, no need to propagate further
        let frame = PauliFrame { residual, readouts };
        if gadget.frame.as_ref() == Some(&frame) {
            return;
        }
        let readouts = crate::misc::bit_vector::binar_bitvec_to_bit_vector(&frame.readouts, gadget.num_readouts());
        updates.insert(gid, readouts);
        let gadget = self.gadgets.get_mut(&gid).unwrap();
        gadget.frame = Some(frame);
        let outputs = gadget.outputs.clone();
        let remote_dependents = gadget.remote_dependents.clone();
        let readout_snapshot = gadget.frame.as_ref().unwrap().readouts.clone();
        for &dependent in &remote_dependents {
            let Some(consumer) = self.gadgets.get_mut(&dependent) else {
                continue;
            };
            if let (Some(values), Some((references, _))) =
                (&mut consumer.remote_readout_values, &consumer.remote_conditional_correction)
            {
                use binar::Bitwise;
                for (value, reference) in values.iter_mut().zip(references) {
                    if reference.gid == gid {
                        *value = Some(readout_snapshot.index(usize::try_from(reference.readout_index).unwrap()));
                    }
                }
            }
        }
        for peer in outputs.iter().flatten() {
            self.propagate_from(peer.gid, updates);
        }
        // also propagate to gadgets that depend on this gadget's readout via remote_conditional_correction
        for dependent_gid in remote_dependents {
            self.propagate_from(dependent_gid, updates);
        }
    }
}

impl Default for PauliFrameTracker {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::misc::bit_matrix::{append_bit, zeros};
    use binar::BitwiseMut;
    use util::BitVector;

    // the ptype=1 port type has 2 observables
    fn build_port_types() -> HashMap<u64, Arc<bin::PortType>> {
        [(
            1,
            Arc::new(bin::PortType {
                ptype: 1,
                name: "surface code".to_string(),
                description: "".to_string(),
                observables: vec![
                    bin::port_type::Observable {
                        tag: "X".to_string(),
                        ..Default::default()
                    },
                    bin::port_type::Observable {
                        tag: "Z".to_string(),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }),
        )]
        .into_iter()
        .collect()
    }

    fn build_gadget_type(num_inputs: usize, num_outputs: usize, num_readouts: usize) -> bin::GadgetType {
        bin::GadgetType {
            gtype: 0, // invalid but nobody checks
            name: "".to_string(),
            description: "".to_string(),
            measurements: vec![], // don't care
            inputs: vec![
                bin::gadget_type::Port {
                    ptype: 1,
                    tag: "".to_string(),
                    ..Default::default()
                };
                num_inputs
            ],
            outputs: vec![
                bin::gadget_type::Port {
                    ptype: 1,
                    tag: "".to_string(),
                    ..Default::default()
                };
                num_outputs
            ],
            correction_propagation: Some(zeros(num_outputs * 2, num_inputs * 2 + 1)),
            readouts: vec![
                bin::gadget_type::Readout {
                    tag: "".to_string(),
                    measurement_indices: vec![],
                    ..Default::default()
                };
                num_readouts
            ],
            readout_propagation: Some(zeros(num_readouts, num_inputs * 2 + 1)),
            logical_correction: Some(zeros(num_outputs * 2, num_readouts)),
            physical_correction: Some(zeros(num_outputs * 2, 0)),
            ..Default::default()
        }
    }

    fn load_correction_to(
        tracker: &mut PauliFrameTracker,
        gid: u64,
        residual_ones: &[usize],
        readout_flips_ones: &[usize],
    ) -> HashMap<u64, BitVector> {
        let gadget = tracker.gadgets.get(&gid).unwrap();
        let mut residual: BitVec = BitVec::zeros(gadget.num_output_observables());
        let mut readout_flips: BitVec = BitVec::zeros(gadget.num_readouts());
        for &index in residual_ones {
            residual.assign_index(index, true);
        }
        for &index in readout_flips_ones {
            readout_flips.assign_index(index, true);
        }
        tracker.load_correction(gid, residual, readout_flips)
    }

    /*
    G1 -->  G2
    a flip in G1 should result in flipped logical readout in G2
     */
    #[test]
    fn pauli_frame_tracker_1() {
        // cargo test pauli_frame_tracker_1 -- --nocapture
        fn prepare_tracker() -> PauliFrameTracker {
            let mut tracker = PauliFrameTracker::new();
            let port_types = build_port_types();
            let gadget_type_1 = build_gadget_type(0, 1, 0);
            tracker.add_gadget(1, &gadget_type_1, None, &port_types, &[]);
            tracker.load_raw(1, &[], &crate::misc::bit_vector::from_sparse_indices(0, &[]));
            let mut gadget_type_2 = build_gadget_type(1, 0, 1);
            append_bit(gadget_type_2.readout_propagation.as_mut().unwrap(), 0, 0);
            tracker.add_gadget(
                2,
                &gadget_type_2,
                None,
                &port_types,
                &[bin::gadget::Connector { gid: 1, port: 0 }],
            );
            tracker.load_raw(2, &[false], &crate::misc::bit_vector::from_sparse_indices(0, &[]));
            tracker
        }

        // 1: sequentially load the decoded results
        let mut tracker = prepare_tracker();
        assert_eq!(
            load_correction_to(&mut tracker, 1, &[], &[]),
            [(1, BitVector { size: 0, data: vec![] })].into()
        );
        assert_eq!(
            load_correction_to(&mut tracker, 2, &[], &[]),
            [(2, BitVector { size: 1, data: vec![0] })].into()
        );

        // 2. try to load a wrong decode result on gid=1 and expect to see flip on gid=2
        let mut tracker = prepare_tracker();
        assert_eq!(
            load_correction_to(&mut tracker, 1, &[0], &[]),
            [(1, BitVector { size: 0, data: vec![] })].into()
        );
        assert_eq!(
            load_correction_to(&mut tracker, 2, &[], &[]),
            [(
                2,
                BitVector {
                    size: 1,
                    data: vec![1 << 7]
                }
            )]
            .into()
        );

        // 3 load gadget 2's decoded result, which should depend on 1's and does nothing
        let mut tracker = prepare_tracker();
        assert_eq!(load_correction_to(&mut tracker, 2, &[], &[]), [].into());
        assert_eq!(
            load_correction_to(&mut tracker, 1, &[0], &[]),
            [
                (1, BitVector { size: 0, data: vec![] }),
                (
                    2,
                    BitVector {
                        size: 1,
                        data: vec![1 << 7]
                    }
                ),
            ]
            .into()
        );
    }

    /*
    Test race condition fix for remote_conditional_correction:

    G_A (source) -- no connection to G_C via port, only via remote_conditional_correction
    G_B (source) --> G_C (has remote_conditional_correction referencing G_A's readout)

    If corrections are loaded in order: B, C, A
    Without the fix, C would never get its frame computed because A's frame is not ready
    when C is processed, and A doesn't trigger C's propagation.

    With the fix, A's propagate_from triggers C's propagate_from via remote_dependents.
    */
    #[test]
    fn pauli_frame_tracker_remote_conditional_correction_race() {
        fn prepare_tracker() -> PauliFrameTracker {
            let mut tracker = PauliFrameTracker::new();
            let port_types = build_port_types();

            // G_A: source gadget with 1 output, 1 readout
            let gadget_type_a = build_gadget_type(0, 1, 1);
            tracker.add_gadget(1, &gadget_type_a, None, &port_types, &[]);
            tracker.load_raw(1, &[true], &crate::misc::bit_vector::from_sparse_indices(0, &[]));

            // G_B: source gadget with 1 output, 0 readouts
            let gadget_type_b = build_gadget_type(0, 1, 0);
            tracker.add_gadget(2, &gadget_type_b, None, &port_types, &[]);
            tracker.load_raw(2, &[], &crate::misc::bit_vector::from_sparse_indices(0, &[]));

            // G_C: takes input from G_B, has remote_conditional_correction from G_A
            // readout_propagation XORs with input observable[0]
            let gadget_type_c = build_gadget_type(1, 0, 1);

            // Build remote_conditional_correction modifier
            // G_C has 0 output observables (no output ports), so correction matrix is 0x1
            let remote_cc = bin::RemoteConditionalCorrection {
                remote_readouts: vec![bin::remote_conditional_correction::RemoteReadout {
                    gid: 1,           // references G_A
                    readout_index: 0, // G_A's readout[0]
                }],
                correction: Some(zeros(0, 1)), // 0 rows (output obs), 1 col (remote readouts)
            };
            let modifier = bin::GadgetModifier {
                remote_conditional_correction: Some(remote_cc),
                ..Default::default()
            };

            tracker.add_gadget(
                3,
                &gadget_type_c,
                Some(&modifier),
                &port_types,
                &[bin::gadget::Connector { gid: 2, port: 0 }],
            );
            tracker.load_raw(3, &[false], &crate::misc::bit_vector::from_sparse_indices(0, &[]));
            tracker
        }

        // Test the race condition scenario: load in order B, C, A
        let mut tracker = prepare_tracker();

        // Load B first - should compute B's frame
        let updates_b = load_correction_to(&mut tracker, 2, &[], &[]);
        assert_eq!(updates_b.len(), 1);
        assert!(updates_b.contains_key(&2), "B should have its frame computed");

        // Load C - should NOT compute C's frame yet (A is not ready)
        let updates_c = load_correction_to(&mut tracker, 3, &[], &[]);
        assert!(updates_c.is_empty(), "C should not have frame yet (A not ready)");

        // Load A - should compute A's frame AND trigger C's frame computation
        let updates_a = load_correction_to(&mut tracker, 1, &[], &[]);
        assert!(updates_a.contains_key(&1), "A should have its frame computed");
        assert!(
            updates_a.contains_key(&3),
            "C should also have its frame computed via remote_dependents"
        );
    }

    #[test]
    fn readout_hints_saturate_and_preserve_the_unsigned_range() {
        let ports = build_port_types();
        let source_type = build_gadget_type(0, 0, 1);
        let consumer_type = build_gadget_type(0, 0, 0);
        let consumer = |gid| bin::Gadget {
            gid,
            modifier: Some(bin::GadgetModifier {
                remote_conditional_correction: Some(bin::RemoteConditionalCorrection {
                    remote_readouts: vec![bin::remote_conditional_correction::RemoteReadout {
                        gid: 1,
                        readout_index: 0,
                    }],
                    correction: Some(zeros(0, 1)),
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        for hint in [0, 1, 1 << 63, u64::MAX] {
            let mut tracker = PauliFrameTracker::new();
            tracker
                .add_committing_gadget(
                    &bin::Gadget {
                        gid: 1,
                        expected_remote_references: hint,
                        ..Default::default()
                    },
                    &source_type,
                    &ports,
                )
                .unwrap();
            tracker.load_raw(1, &[true], &BitVector::default());
            load_correction_to(&mut tracker, 1, &[], &[]);
            for gid in [2, 3] {
                tracker.add_committing_gadget(&consumer(gid), &consumer_type, &ports).unwrap();
            }
            assert_eq!(tracker.gadgets[&1].expected_remote_references, hint.saturating_sub(2));
            tracker.finalize(1);
            tracker.collect_gadget(1);
            if hint > 2 {
                assert_eq!(tracker.retained_readouts[&1].remaining, hint - 2);
                assert!(get_bit(&tracker.retained_readouts[&1].value, 0));
                tracker.add_committing_gadget(&consumer(4), &consumer_type, &ports).unwrap();
                assert_eq!(tracker.retained_readouts[&1].remaining, hint - 3);
            } else {
                assert!(tracker.retained_readouts.is_empty());
            }
        }
    }

    #[test]
    fn finalized_frames_release_payloads_but_support_late_children_and_remote_readouts() {
        let mut tracker = PauliFrameTracker::new();
        let ports = build_port_types();
        let source = build_gadget_type(0, 1, 1);
        tracker.add_gadget(1, &source, None, &ports, &[]);
        tracker.load_raw(1, &[true], &BitVector::default());
        load_correction_to(&mut tracker, 1, &[0], &[]);
        let expected = tracker.gadgets[&1].frame.clone();
        tracker.finalize(1);
        tracker.finalize(1);
        let source = &tracker.gadgets[&1];
        assert_eq!(source.frame, expected);
        assert!(source.decoded.is_none());
        assert!(source.raw_measurements.is_none());
        assert!(source.raw_readouts.is_none());
        assert!(source.finalized);
        assert_eq!(source.num_output_observables(), 2);
        assert_eq!(source.num_readouts(), 1);

        let mut child = build_gadget_type(1, 1, 1);
        append_bit(child.readout_propagation.as_mut().unwrap(), 0, 0);
        let mut remote = zeros(2, 1);
        append_bit(&mut remote, 1, 0);
        let modifier = bin::GadgetModifier {
            remote_conditional_correction: Some(bin::RemoteConditionalCorrection {
                remote_readouts: vec![bin::remote_conditional_correction::RemoteReadout {
                    gid: 1,
                    readout_index: 0,
                }],
                correction: Some(remote),
            }),
            ..Default::default()
        };
        tracker.add_gadget(
            2,
            &child,
            Some(&modifier),
            &ports,
            &[bin::gadget::Connector { gid: 1, port: 0 }],
        );
        tracker.load_raw(2, &[false], &BitVector::default());
        let updates = load_correction_to(&mut tracker, 2, &[], &[]);
        assert!(get_bit(&updates[&2], 0));
        assert_eq!(
            tracker.gadgets[&2].get_residual_slice(&tracker.gadgets[&2].frame.as_ref().unwrap().residual, 0),
            vec![false, true],
        );
    }
}