Skip to main content

faultscope_core/
compile.rs

1use crate::program::{ExpandedOperation, ExpansionMode};
2use crate::stabilizer::SymbolicStabilizer;
3use crate::{
4    Expr, IndexedNoiseLocation, LocationCatalog, LogicalObservable, NpError, NpResult, Operation,
5    RuntimeCapacities, SamplerObservable, SamplerOperation, SamplerProgram,
6};
7
8#[cfg(test)]
9thread_local! {
10    static SYMBOLIC_OPERATION_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
11}
12
13/// Compile a borrowed operation tree into the canonical compact sampler program.
14pub fn compile_sampler_program_ref(
15    n_qubits: usize,
16    operations: &[Operation],
17    observables: Vec<LogicalObservable>,
18) -> NpResult<SamplerProgram> {
19    crate::model::validate_operations(n_qubits, operations)?;
20    for observable in &observables {
21        observable.validate_for_n_qubits(n_qubits)?;
22    }
23    let expanded = crate::program::expand_operations(operations, ExpansionMode::Sampler)?;
24    compile_expanded_program(n_qubits, expanded, observables)
25}
26
27struct SymbolicCompilation {
28    operations: Vec<ExpandedOperation>,
29    ideals: Vec<Expr>,
30    measurement_keys: Vec<String>,
31    noise_locations: Vec<IndexedNoiseLocation>,
32    location_catalog: LocationCatalog,
33    random_source_count: usize,
34    stored_operation_count: usize,
35    logical_operation_count: usize,
36    loop_kernel_count: usize,
37}
38
39fn compile_expanded_program(
40    n_qubits: usize,
41    expanded: crate::program::ExpandedProgram,
42    observables: Vec<LogicalObservable>,
43) -> NpResult<SamplerProgram> {
44    let crate::program::ExpandedProgram {
45        operations,
46        measurement_keys,
47        noise_locations,
48        location_catalog,
49        stored_operation_count,
50        logical_operation_count,
51        ideal_count,
52        mut loop_ranges,
53        ..
54    } = expanded;
55    let mut symbolic = SymbolicStabilizer::zero(n_qubits);
56    let mut ideals = Vec::with_capacity(ideal_count);
57    loop_ranges.retain(|range| range.iterations.len() >= 2);
58    loop_ranges.sort_by(|left, right| {
59        let left_start = left.iterations[0].start;
60        let right_start = right.iterations[0].start;
61        left_start.cmp(&right_start).then_with(|| {
62            right
63                .iterations
64                .last()
65                .unwrap()
66                .end
67                .cmp(&left.iterations.last().unwrap().end)
68        })
69    });
70
71    let mut cursor = 0usize;
72    let mut loop_kernel_count = 0usize;
73    for loop_range in loop_ranges {
74        let start = loop_range.iterations[0].start;
75        let end = loop_range.iterations.last().unwrap().end;
76        if start < cursor || end > operations.len() {
77            continue;
78        }
79        compile_regular_segment(&mut symbolic, &operations[cursor..start], &mut ideals)?;
80        let used_affine_cycle = compile_affine_loop(
81            &mut symbolic,
82            &operations,
83            &loop_range.iterations,
84            &mut ideals,
85        )?;
86        loop_kernel_count += usize::from(used_affine_cycle);
87        cursor = end;
88    }
89    compile_regular_segment(&mut symbolic, &operations[cursor..], &mut ideals)?;
90    emit_sampler_program(
91        n_qubits,
92        SymbolicCompilation {
93            operations,
94            ideals,
95            measurement_keys,
96            noise_locations,
97            location_catalog,
98            random_source_count: symbolic.random_source_count(),
99            stored_operation_count,
100            logical_operation_count,
101            loop_kernel_count,
102        },
103        observables,
104    )
105}
106
107fn compile_regular_segment(
108    symbolic: &mut SymbolicStabilizer,
109    operations: &[ExpandedOperation],
110    ideals: &mut Vec<Expr>,
111) -> NpResult<()> {
112    if operations.is_empty() {
113        return Ok(());
114    }
115    simulate_symbolic_segment(symbolic, operations, ideals)
116}
117
118fn compile_affine_loop(
119    symbolic: &mut SymbolicStabilizer,
120    operations: &[ExpandedOperation],
121    iterations: &[std::ops::Range<usize>],
122    ideals: &mut Vec<Expr>,
123) -> NpResult<bool> {
124    let iteration_len = iterations[0].end - iterations[0].start;
125    let has_clifford = operations[iterations[0].clone()].iter().any(|operation| {
126        matches!(
127            operation,
128            ExpandedOperation::H(_)
129                | ExpandedOperation::S(_)
130                | ExpandedOperation::SDag(_)
131                | ExpandedOperation::Cx(_, _)
132                | ExpandedOperation::Cz(_, _)
133                | ExpandedOperation::Swap(_, _)
134        )
135    });
136    let minimum_iterations = if has_clifford { 8 } else { 4 };
137    if iterations.len() < minimum_iterations
138        || iteration_len < symbolic.n_qubits().saturating_mul(2)
139        || iterations
140            .iter()
141            .any(|iteration| iteration.end - iteration.start != iteration_len)
142    {
143        for iteration in iterations {
144            compile_regular_segment(symbolic, &operations[iteration.clone()], ideals)?;
145        }
146        return Ok(false);
147    }
148
149    let mut template = symbolic.affine_template();
150    let mut template_ideals = Vec::new();
151    simulate_symbolic_segment(
152        &mut template,
153        &operations[iterations[0].clone()],
154        &mut template_ideals,
155    )?;
156    let mut period = usize::from(symbolic.support_equals(&template));
157    let mut probed_iterations = 1usize;
158    if period == 0 && has_clifford {
159        simulate_symbolic_segment(
160            &mut template,
161            &operations[iterations[1].clone()],
162            &mut template_ideals,
163        )?;
164        probed_iterations = 2;
165        if symbolic.support_equals(&template) {
166            period = 2;
167        }
168    }
169
170    let basis_count = symbolic.signs().len();
171    let local_random_count = template
172        .random_source_count()
173        .checked_sub(basis_count)
174        .ok_or_else(|| NpError::new("invalid affine loop random-source count"))?;
175    let input_signs = symbolic.signs().to_vec();
176    let source_base = symbolic.random_source_count();
177    instantiate_affine_ideals_into(&template_ideals, &input_signs, source_base, ideals);
178    let probed_signs = instantiate_affine_signs(&template, &input_signs, source_base);
179    let probed_random_source_count = source_base
180        .checked_add(local_random_count)
181        .ok_or_else(|| NpError::new("random-source count overflow"))?;
182
183    let reusable_periods = (iterations.len() - probed_iterations)
184        .checked_div(period)
185        .unwrap_or(0);
186    let use_affine_cycle = period != 0
187        && reusable_periods >= 2
188        && affine_template_is_compact(template.signs(), &template_ideals);
189    if !use_affine_cycle {
190        symbolic.replace_with_affine_template(template, probed_signs, probed_random_source_count);
191        let remaining = &iterations[probed_iterations..];
192        for iteration in remaining {
193            compile_regular_segment(symbolic, &operations[iteration.clone()], ideals)?;
194        }
195        return Ok(false);
196    }
197
198    symbolic.replace_affine_state(probed_signs, probed_random_source_count);
199    let mut next_iteration = probed_iterations;
200    while next_iteration + period <= iterations.len() {
201        let input_signs = symbolic.signs().to_vec();
202        let source_base = symbolic.random_source_count();
203        instantiate_affine_ideals_into(&template_ideals, &input_signs, source_base, ideals);
204        let signs = instantiate_affine_signs(&template, &input_signs, source_base);
205        symbolic.replace_affine_state(
206            signs,
207            source_base
208                .checked_add(local_random_count)
209                .ok_or_else(|| NpError::new("random-source count overflow"))?,
210        );
211        next_iteration += period;
212    }
213    for remaining in &iterations[next_iteration..] {
214        compile_regular_segment(symbolic, &operations[remaining.clone()], ideals)?;
215    }
216    Ok(true)
217}
218
219fn affine_template_is_compact(signs: &[Expr], ideals: &[Expr]) -> bool {
220    let expression_count = signs.len() + ideals.len();
221    let expression_term_count = signs
222        .iter()
223        .chain(ideals)
224        .map(|expr| expr.terms().len())
225        .sum::<usize>();
226    expression_term_count <= expression_count.saturating_mul(16)
227}
228
229fn instantiate_affine_ideals_into(
230    template_ideals: &[Expr],
231    input_signs: &[Expr],
232    source_base: usize,
233    ideals: &mut Vec<Expr>,
234) {
235    ideals.extend(
236        template_ideals
237            .iter()
238            .map(|ideal| substitute_affine_expr(ideal, input_signs, source_base)),
239    );
240}
241
242fn instantiate_affine_signs(
243    template: &SymbolicStabilizer,
244    input_signs: &[Expr],
245    source_base: usize,
246) -> Vec<Expr> {
247    template
248        .signs()
249        .iter()
250        .map(|sign| substitute_affine_expr(sign, input_signs, source_base))
251        .collect()
252}
253
254fn substitute_affine_expr(template: &Expr, input_signs: &[Expr], source_base: usize) -> Expr {
255    let mut result = Expr::constant(template.constant_value());
256    let basis_count = input_signs.len();
257    for term in template.terms() {
258        if *term < basis_count {
259            result.xor_assign(&input_signs[*term]);
260        } else {
261            result.toggle_term(source_base + term - basis_count);
262        }
263    }
264    result
265}
266
267fn simulate_symbolic_segment(
268    symbolic: &mut SymbolicStabilizer,
269    operations: &[ExpandedOperation],
270    ideals: &mut Vec<Expr>,
271) -> NpResult<()> {
272    #[cfg(test)]
273    SYMBOLIC_OPERATION_COUNT.with(|count| count.set(count.get() + operations.len()));
274
275    let reset_reuse = find_measure_reset_reuse(operations);
276    let mut reuse_index = 0usize;
277    let mut operation_index = 0usize;
278    while operation_index < operations.len() {
279        if let Some(reuse) = reset_reuse.get(reuse_index) {
280            if reuse.measurement_start == operation_index {
281                let mut cached_ideals = Vec::with_capacity(reuse.count);
282                for operation in
283                    &operations[reuse.measurement_start..reuse.measurement_start + reuse.count]
284                {
285                    let ExpandedOperation::MeasureSingle { qubit, basis, .. } = operation else {
286                        return Err(NpError::new(
287                            "internal error: invalid fused measurement block",
288                        ));
289                    };
290                    let ideal = symbolic.measure_single_pauli_expr(*qubit, basis.as_str())?;
291                    ideals.push(ideal.clone());
292                    cached_ideals.push(ideal);
293                }
294                for (offset, ideal) in cached_ideals.iter().enumerate() {
295                    let reset_index = reuse.measurement_start + reuse.count + offset;
296                    let ExpandedOperation::Reset { qubit, basis, .. } = &operations[reset_index]
297                    else {
298                        return Err(NpError::new("internal error: invalid fused reset block"));
299                    };
300                    symbolic.apply_single_pauli_string_expr(
301                        *qubit,
302                        reset_correction(basis.as_str())?,
303                        ideal,
304                    )?;
305                    ideals.push(Expr::constant(false));
306                }
307                operation_index += reuse.count * 2;
308                reuse_index += 1;
309                continue;
310            }
311        }
312
313        match &operations[operation_index] {
314            ExpandedOperation::H(qubit) => symbolic.apply_h(*qubit),
315            ExpandedOperation::S(qubit) => symbolic.apply_s(*qubit),
316            ExpandedOperation::SDag(qubit) => symbolic.apply_s_dag(*qubit),
317            ExpandedOperation::Cx(control, target) => symbolic.apply_cx(*control, *target),
318            ExpandedOperation::Cz(left, right) => symbolic.apply_cz(*left, *right),
319            ExpandedOperation::Swap(left, right) => symbolic.apply_swap(*left, *right),
320            ExpandedOperation::Pauli { qubits, pauli } => {
321                symbolic.apply_sparse_pauli_string(qubits, pauli)?;
322            }
323            ExpandedOperation::MeasureSingle { qubit, basis, .. } => {
324                ideals.push(symbolic.measure_single_pauli_expr(*qubit, basis.as_str())?);
325            }
326            ExpandedOperation::MeasurePauli { qubits, pauli, .. } => {
327                ideals.push(symbolic.measure_sparse_pauli_expr(qubits, pauli)?);
328            }
329            ExpandedOperation::Reset { qubit, basis, .. } => {
330                let basis = basis.as_str();
331                let ideal = symbolic.measure_single_pauli_expr(*qubit, basis)?;
332                symbolic.apply_single_pauli_string_expr(
333                    *qubit,
334                    reset_correction(basis)?,
335                    &ideal,
336                )?;
337                ideals.push(ideal);
338            }
339            ExpandedOperation::Noise(_)
340            | ExpandedOperation::Detector { .. }
341            | ExpandedOperation::ObservableInclude { .. } => {}
342        }
343        operation_index += 1;
344    }
345    Ok(())
346}
347
348fn emit_sampler_program(
349    n_qubits: usize,
350    compiled: SymbolicCompilation,
351    observables: Vec<LogicalObservable>,
352) -> NpResult<SamplerProgram> {
353    let mut sampler_operations = Vec::with_capacity(compiled.operations.len());
354    let mut ideals = compiled.ideals.into_iter();
355    let mut capacities = RuntimeCapacities {
356        random_sources: compiled.random_source_count,
357        ..RuntimeCapacities::default()
358    };
359    for operation in compiled.operations {
360        match operation {
361            ExpandedOperation::H(qubit) => {
362                sampler_operations.push(SamplerOperation::H(qubit));
363            }
364            ExpandedOperation::S(qubit) => {
365                sampler_operations.push(SamplerOperation::S(qubit));
366            }
367            ExpandedOperation::SDag(qubit) => {
368                sampler_operations.push(SamplerOperation::SDag(qubit));
369            }
370            ExpandedOperation::Cx(control, target) => {
371                sampler_operations.push(SamplerOperation::Cx(control, target));
372            }
373            ExpandedOperation::Cz(left, right) => {
374                sampler_operations.push(SamplerOperation::Cz(left, right));
375            }
376            ExpandedOperation::Swap(left, right) => {
377                sampler_operations.push(SamplerOperation::Swap(left, right));
378            }
379            ExpandedOperation::Pauli { .. } => {}
380            ExpandedOperation::Noise(noise_id) => {
381                sampler_operations.push(SamplerOperation::Noise(noise_id));
382            }
383            ExpandedOperation::MeasureSingle {
384                qubit,
385                basis,
386                measurement_id,
387                noise,
388            } => {
389                sampler_operations.push(SamplerOperation::MeasureSingle {
390                    qubit,
391                    basis,
392                    measurement_id,
393                    ideal: ideals
394                        .next()
395                        .ok_or_else(|| NpError::new("missing compiled measurement expression"))?,
396                    noise,
397                });
398                capacities.measurements += 1;
399            }
400            ExpandedOperation::MeasurePauli {
401                qubits,
402                pauli,
403                measurement_id,
404                noise,
405            } => {
406                sampler_operations.push(SamplerOperation::MeasurePauli {
407                    qubits,
408                    pauli,
409                    measurement_id,
410                    ideal: ideals
411                        .next()
412                        .ok_or_else(|| NpError::new("missing compiled measurement expression"))?,
413                    noise,
414                });
415                capacities.measurements += 1;
416            }
417            ExpandedOperation::Reset {
418                qubit,
419                measurement_id,
420                basis,
421            } => {
422                capacities.measurements += usize::from(measurement_id.is_some());
423                sampler_operations.push(SamplerOperation::Reset {
424                    qubit,
425                    measurement_id,
426                    basis,
427                    ideal: ideals
428                        .next()
429                        .ok_or_else(|| NpError::new("missing compiled reset expression"))?,
430                });
431            }
432            ExpandedOperation::Detector {
433                detector_id,
434                measurement_ids,
435                ..
436            } => {
437                sampler_operations.push(SamplerOperation::Detector {
438                    detector_id,
439                    measurement_ids,
440                });
441                capacities.detectors += 1;
442            }
443            ExpandedOperation::ObservableInclude {
444                observable_id,
445                measurement_ids,
446            } => {
447                sampler_operations.push(SamplerOperation::ObservableInclude {
448                    observable_id,
449                    measurement_ids,
450                });
451                capacities.observables += 1;
452            }
453        }
454    }
455    if ideals.next().is_some() {
456        return Err(NpError::new(
457            "internal error: unused compiled measurement expression",
458        ));
459    }
460
461    let mut measurement_keys = compiled.measurement_keys;
462    let compiled_observables = observables
463        .iter()
464        .map(|observable| SamplerObservable {
465            id: observable.id,
466            measurement_ids: observable
467                .measurement_keys
468                .iter()
469                .map(|key| resolve_declared_measurement_key(key, &mut measurement_keys))
470                .collect(),
471            pauli_qubits: observable.pauli_qubits.clone(),
472            pauli: observable.pauli.clone(),
473        })
474        .collect();
475    Ok(SamplerProgram::from_compiled_parts(
476        n_qubits,
477        sampler_operations,
478        observables,
479        compiled_observables,
480        measurement_keys,
481        compiled.noise_locations,
482        compiled.location_catalog,
483        capacities,
484        compiled.stored_operation_count,
485        compiled.logical_operation_count,
486        compiled.loop_kernel_count,
487    ))
488}
489
490fn resolve_declared_measurement_key(key: &str, measurement_keys: &mut Vec<String>) -> usize {
491    if let Some(measurement_id) = crate::program::automatic_key_ordinal(key) {
492        if measurement_keys.get(measurement_id).map(String::as_str) == Some(key) {
493            return measurement_id;
494        }
495    }
496    if let Some(measurement_id) = measurement_keys
497        .iter()
498        .position(|defined_key| defined_key == key)
499    {
500        return measurement_id;
501    }
502    let measurement_id = measurement_keys.len();
503    measurement_keys.push(key.to_string());
504    measurement_id
505}
506
507struct MeasureResetReuse {
508    measurement_start: usize,
509    count: usize,
510}
511
512fn find_measure_reset_reuse(operations: &[ExpandedOperation]) -> Vec<MeasureResetReuse> {
513    let mut reuse = Vec::new();
514    let mut index = 0;
515    while index < operations.len() {
516        let measurement_start = index;
517        while matches!(
518            operations.get(index),
519            Some(ExpandedOperation::MeasureSingle { .. })
520        ) {
521            index += 1;
522        }
523        if index == measurement_start {
524            index += 1;
525            continue;
526        }
527
528        let reset_start = index;
529        while matches!(
530            operations.get(index),
531            Some(ExpandedOperation::Reset {
532                measurement_id: None,
533                ..
534            })
535        ) {
536            index += 1;
537        }
538        let measurement_count = reset_start - measurement_start;
539        let reset_count = index - reset_start;
540        if measurement_count != reset_count {
541            continue;
542        }
543
544        let matching = (0..measurement_count).all(|offset| {
545            matches!(
546                (
547                    &operations[measurement_start + offset],
548                    &operations[reset_start + offset]
549                ),
550                (
551                    ExpandedOperation::MeasureSingle {
552                        qubit: measurement_qubit,
553                        basis: measurement_basis,
554                        ..
555                    },
556                    ExpandedOperation::Reset {
557                        qubit: reset_qubit,
558                        basis: reset_basis,
559                        measurement_id: None,
560                    }
561                ) if measurement_qubit == reset_qubit && measurement_basis == reset_basis
562            )
563        });
564        if matching {
565            reuse.push(MeasureResetReuse {
566                measurement_start,
567                count: measurement_count,
568            });
569        }
570    }
571    reuse
572}
573
574fn reset_correction(basis: &str) -> NpResult<&'static str> {
575    match basis {
576        "Z" => Ok("X"),
577        "X" => Ok("Z"),
578        "Y" => Ok("X"),
579        _ => Err(NpError::new(format!("unsupported reset basis {basis:?}"))),
580    }
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586    use crate::{NoiseLocation, NoiseModel};
587    use std::collections::HashMap;
588
589    fn compile_sampler(n_qubits: usize, operations: Vec<Operation>) -> NpResult<SamplerProgram> {
590        compile_sampler_program_ref(n_qubits, &operations, Vec::new())
591    }
592
593    #[test]
594    fn compiles_random_measurement_to_sampler_operation() {
595        let compiled = compile_sampler(
596            1,
597            vec![Operation::Measure {
598                qubit: 0,
599                key: Some("m".to_string()),
600                basis: "X".to_string(),
601                noise: None,
602            }],
603        )
604        .unwrap();
605
606        assert_eq!(compiled.capacities().random_sources, 1);
607        assert!(matches!(
608            compiled.operations(),
609            [SamplerOperation::MeasureSingle { .. }]
610        ));
611    }
612
613    #[test]
614    fn public_compile_errors_remain_stable_on_the_canonical_path() {
615        let assert_error = |operations, expected: &str| {
616            let error = compile_sampler(1, operations).unwrap_err();
617            assert_eq!(error.message(), expected);
618        };
619
620        assert_error(
621            vec![Operation::Repeat {
622                count: 0,
623                body: Vec::new(),
624            }],
625            "repeat count must be positive",
626        );
627        assert_error(
628            vec![
629                Operation::Measure {
630                    qubit: 0,
631                    key: None,
632                    basis: "Z".to_string(),
633                    noise: None,
634                },
635                Operation::Measure {
636                    qubit: 0,
637                    key: Some("m0".to_string()),
638                    basis: "Z".to_string(),
639                    noise: None,
640                },
641            ],
642            "duplicate measurement key \"m0\"",
643        );
644        assert_error(
645            vec![Operation::DetectorRec {
646                detector_id: Some(0),
647                lookbacks: vec![1],
648                coords: Vec::new(),
649            }],
650            "measurement record lookback 1 is out of range",
651        );
652        assert_error(
653            vec![
654                Operation::Detector {
655                    detector_id: Some(3),
656                    measurement_keys: Vec::new(),
657                    coords: Vec::new(),
658                },
659                Operation::Detector {
660                    detector_id: Some(3),
661                    measurement_keys: Vec::new(),
662                    coords: Vec::new(),
663                },
664            ],
665            "duplicate detector id 3",
666        );
667        let duplicate_noise = NoiseLocation {
668            id: "duplicate".to_string(),
669            model: NoiseModel::BernoulliPauli("X".to_string()),
670            rate: 0.1,
671            qubits: vec![0],
672            tags: HashMap::new(),
673        };
674        assert_error(
675            vec![
676                Operation::Noise(duplicate_noise.clone()),
677                Operation::Noise(duplicate_noise),
678            ],
679            "native sampler requires unique noise location ids; duplicate \"duplicate\"",
680        );
681        assert_error(
682            vec![Operation::Measure {
683                qubit: 0,
684                key: None,
685                basis: "Q".to_string(),
686                noise: None,
687            }],
688            "unsupported measurement basis \"Q\"",
689        );
690    }
691
692    #[test]
693    fn compiler_rejects_invalid_circuit_and_observable_targets() {
694        for operation in [Operation::H(1), Operation::Cx(0, 0), Operation::Swap(0, 0)] {
695            let err = compile_sampler(1, vec![operation]).unwrap_err();
696            assert!(
697                err.message().contains("targets qubit 1")
698                    || err.message().contains("duplicate qubit 0"),
699                "{err}"
700            );
701        }
702
703        let observable = LogicalObservable {
704            id: 7,
705            measurement_keys: Vec::new(),
706            pauli_qubits: vec![1],
707            pauli: "Z".to_string(),
708        };
709        let err = compile_sampler_program_ref(1, &[], vec![observable]).unwrap_err();
710        assert!(err.message().contains("logical observable 7"));
711        assert!(err.message().contains("targets qubit 1"));
712    }
713
714    #[test]
715    fn repeat_compilation_matches_explicit_expansion_with_same_seed() {
716        let repeated = vec![Operation::Repeat {
717            count: 3,
718            body: vec![
719                Operation::H(0),
720                Operation::MeasureReset {
721                    qubit: 0,
722                    basis: "Z".to_string(),
723                },
724                Operation::DetectorRec {
725                    detector_id: None,
726                    lookbacks: vec![1],
727                    coords: Vec::new(),
728                },
729            ],
730        }];
731        let mut expanded = Vec::new();
732        for index in 0..3 {
733            expanded.push(Operation::H(0));
734            expanded.push(Operation::Reset {
735                qubit: 0,
736                key: Some(format!("m{index}")),
737                basis: "Z".to_string(),
738            });
739            expanded.push(Operation::Detector {
740                detector_id: None,
741                measurement_keys: vec![format!("m{index}")],
742                coords: Vec::new(),
743            });
744        }
745        let repeated = compile_sampler(1, repeated).unwrap();
746        let expanded = compile_sampler(1, expanded).unwrap();
747        assert_eq!(
748            repeated.capacities().random_sources,
749            expanded.capacities().random_sources
750        );
751        let repeated_batch = crate::run_sampler_program(&repeated, 129, Some(123), false).unwrap();
752        let expanded_batch = crate::run_sampler_program(&expanded, 129, Some(123), false).unwrap();
753        assert_eq!(repeated_batch.measurements, expanded_batch.measurements);
754        assert_eq!(repeated_batch.detectors, expanded_batch.detectors);
755    }
756
757    #[test]
758    fn affine_measure_reset_loop_matches_expansion_and_counts_kernel() {
759        let repeated = compile_sampler(
760            1,
761            vec![Operation::Repeat {
762                count: 4,
763                body: vec![
764                    Operation::MeasureReset {
765                        qubit: 0,
766                        basis: "Z".to_string(),
767                    },
768                    Operation::MeasureReset {
769                        qubit: 0,
770                        basis: "Z".to_string(),
771                    },
772                ],
773            }],
774        )
775        .unwrap();
776        let expanded = compile_sampler(
777            1,
778            (0..8)
779                .map(|index| Operation::Reset {
780                    qubit: 0,
781                    key: Some(format!("m{index}")),
782                    basis: "Z".to_string(),
783                })
784                .collect(),
785        )
786        .unwrap();
787
788        assert_eq!(repeated.loop_kernel_count(), 1);
789        assert_eq!(repeated.operations(), expanded.operations());
790    }
791
792    #[test]
793    fn affine_mismatch_commits_first_iteration_without_changing_results() {
794        let body = vec![
795            Operation::Measure {
796                qubit: 0,
797                key: None,
798                basis: "X".to_string(),
799                noise: None,
800            },
801            Operation::Reset {
802                qubit: 0,
803                key: None,
804                basis: "X".to_string(),
805            },
806        ];
807        let repeated = compile_sampler(
808            1,
809            vec![Operation::Repeat {
810                count: 4,
811                body: body.clone(),
812            }],
813        )
814        .unwrap();
815        let expanded = compile_sampler(
816            1,
817            (0..4)
818                .flat_map(|_| body.clone())
819                .collect::<Vec<Operation>>(),
820        )
821        .unwrap();
822        let repeated_batch = crate::run_sampler_program(&repeated, 129, Some(19), false).unwrap();
823        let expanded_batch = crate::run_sampler_program(&expanded, 129, Some(19), false).unwrap();
824
825        assert_eq!(repeated.loop_kernel_count(), 0);
826        assert_eq!(repeated_batch.measurements, expanded_batch.measurements);
827    }
828
829    #[test]
830    fn short_clifford_repeats_skip_affine_probe() {
831        let repeated_h = compile_sampler(
832            1,
833            vec![Operation::Repeat {
834                count: 500,
835                body: vec![Operation::H(0)],
836            }],
837        )
838        .unwrap();
839        let repeated_cx = compile_sampler(
840            2,
841            vec![Operation::Repeat {
842                count: 500,
843                body: vec![Operation::Cx(0, 1)],
844            }],
845        )
846        .unwrap();
847
848        assert_eq!(repeated_h.loop_kernel_count(), 0);
849        assert_eq!(repeated_cx.loop_kernel_count(), 0);
850        assert_eq!(repeated_h.operations().len(), 500);
851        assert_eq!(repeated_cx.operations().len(), 500);
852    }
853
854    #[test]
855    fn clifford_period_one_kernel_uses_one_real_iteration() {
856        SYMBOLIC_OPERATION_COUNT.with(|count| count.set(0));
857        let body = vec![Operation::H(0), Operation::H(0)];
858        let repeated = compile_sampler(
859            1,
860            vec![Operation::Repeat {
861                count: 8,
862                body: body.clone(),
863            }],
864        )
865        .unwrap();
866        let simulated = SYMBOLIC_OPERATION_COUNT.with(std::cell::Cell::get);
867        let expanded = compile_sampler(
868            1,
869            (0..8)
870                .flat_map(|_| body.clone())
871                .collect::<Vec<Operation>>(),
872        )
873        .unwrap();
874
875        assert_eq!(repeated.loop_kernel_count(), 1);
876        assert_eq!(simulated, body.len());
877        assert_eq!(repeated.operations(), expanded.operations());
878    }
879
880    #[test]
881    fn clifford_period_two_kernel_uses_two_real_iterations() {
882        SYMBOLIC_OPERATION_COUNT.with(|count| count.set(0));
883        let body = vec![
884            Operation::H(0),
885            Operation::Pauli {
886                qubits: vec![0],
887                pauli: "Z".to_string(),
888            },
889        ];
890        let repeated = compile_sampler(
891            1,
892            vec![Operation::Repeat {
893                count: 8,
894                body: body.clone(),
895            }],
896        )
897        .unwrap();
898        let simulated = SYMBOLIC_OPERATION_COUNT.with(std::cell::Cell::get);
899        let expanded = compile_sampler(
900            1,
901            (0..8)
902                .flat_map(|_| body.clone())
903                .collect::<Vec<Operation>>(),
904        )
905        .unwrap();
906
907        assert_eq!(repeated.loop_kernel_count(), 1);
908        assert_eq!(simulated, body.len() * 2);
909        assert_eq!(repeated.operations(), expanded.operations());
910    }
911
912    #[test]
913    fn failed_clifford_probe_continues_from_third_iteration() {
914        SYMBOLIC_OPERATION_COUNT.with(|count| count.set(0));
915        let body = vec![Operation::H(0), Operation::S(0)];
916        let repeated = compile_sampler(
917            1,
918            vec![Operation::Repeat {
919                count: 8,
920                body: body.clone(),
921            }],
922        )
923        .unwrap();
924        let simulated = SYMBOLIC_OPERATION_COUNT.with(std::cell::Cell::get);
925        let expanded = compile_sampler(
926            1,
927            (0..8)
928                .flat_map(|_| body.clone())
929                .collect::<Vec<Operation>>(),
930        )
931        .unwrap();
932
933        assert_eq!(repeated.loop_kernel_count(), 0);
934        assert_eq!(simulated, body.len() * 8);
935        assert_eq!(repeated.operations(), expanded.operations());
936    }
937
938    #[test]
939    fn rejects_dense_affine_templates() {
940        let mut dense = Expr::constant(false);
941        for source in 0..17 {
942            dense.xor_assign(&Expr::random(source));
943        }
944
945        assert!(!affine_template_is_compact(&[dense], &[]));
946    }
947
948    #[test]
949    fn rejects_duplicate_noise_location_ids() {
950        let location = NoiseLocation {
951            id: "n".to_string(),
952            model: NoiseModel::BernoulliPauli("X".to_string()),
953            rate: 0.1,
954            qubits: vec![0],
955            tags: HashMap::new(),
956        };
957
958        let err = compile_sampler(
959            1,
960            vec![
961                Operation::Noise(location.clone()),
962                Operation::Noise(location.clone()),
963            ],
964        )
965        .unwrap_err();
966
967        assert!(err.message().contains("unique noise location ids"));
968    }
969
970    #[test]
971    fn fuses_adjacent_measure_then_reset_without_changing_runtime_shape() {
972        let compiled = compile_sampler(
973            1,
974            vec![
975                Operation::H(0),
976                Operation::Measure {
977                    qubit: 0,
978                    key: Some("m".to_string()),
979                    basis: "Z".to_string(),
980                    noise: None,
981                },
982                Operation::Reset {
983                    qubit: 0,
984                    key: None,
985                    basis: "Z".to_string(),
986                },
987            ],
988        )
989        .unwrap();
990
991        assert_eq!(compiled.operations().len(), 3);
992        assert_eq!(compiled.capacities().random_sources, 1);
993        assert!(matches!(
994            compiled.operations(),
995            [
996                SamplerOperation::H(0),
997                SamplerOperation::MeasureSingle { ideal, .. },
998                SamplerOperation::Reset {
999                    ideal: reset_ideal,
1000                    ..
1001                }
1002            ] if ideal.terms() == [0] && reset_ideal.terms().is_empty()
1003        ));
1004    }
1005
1006    #[test]
1007    fn reuses_measurement_expressions_for_batched_measure_then_reset() {
1008        let compiled = compile_sampler(
1009            2,
1010            vec![
1011                Operation::H(0),
1012                Operation::H(1),
1013                Operation::Measure {
1014                    qubit: 0,
1015                    key: Some("m0".to_string()),
1016                    basis: "Z".to_string(),
1017                    noise: None,
1018                },
1019                Operation::Measure {
1020                    qubit: 1,
1021                    key: Some("m1".to_string()),
1022                    basis: "Z".to_string(),
1023                    noise: None,
1024                },
1025                Operation::Reset {
1026                    qubit: 0,
1027                    key: None,
1028                    basis: "Z".to_string(),
1029                },
1030                Operation::Reset {
1031                    qubit: 1,
1032                    key: None,
1033                    basis: "Z".to_string(),
1034                },
1035            ],
1036        )
1037        .unwrap();
1038
1039        assert_eq!(compiled.operations().len(), 6);
1040        assert_eq!(compiled.capacities().random_sources, 2);
1041        assert!(compiled.operations()[4..].iter().all(|operation| {
1042            matches!(operation, SamplerOperation::Reset { ideal, .. } if ideal.terms().is_empty())
1043        }));
1044    }
1045
1046    #[test]
1047    fn fused_measure_reset_preserves_seeded_masks_and_followup_measurements() {
1048        let suffix = vec![
1049            Operation::H(0),
1050            Operation::Measure {
1051                qubit: 0,
1052                key: Some("after".to_string()),
1053                basis: "Z".to_string(),
1054                noise: None,
1055            },
1056        ];
1057        let mut expanded = vec![
1058            Operation::H(0),
1059            Operation::Measure {
1060                qubit: 0,
1061                key: Some("m".to_string()),
1062                basis: "Z".to_string(),
1063                noise: None,
1064            },
1065            Operation::Reset {
1066                qubit: 0,
1067                key: None,
1068                basis: "Z".to_string(),
1069            },
1070        ];
1071        expanded.extend(suffix.clone());
1072        let mut combined = vec![
1073            Operation::H(0),
1074            Operation::Reset {
1075                qubit: 0,
1076                key: Some("m".to_string()),
1077                basis: "Z".to_string(),
1078            },
1079        ];
1080        combined.extend(suffix);
1081
1082        let expanded = compile_sampler(1, expanded).unwrap();
1083        let combined = compile_sampler(1, combined).unwrap();
1084        assert_eq!(
1085            expanded.capacities().random_sources,
1086            combined.capacities().random_sources
1087        );
1088        let expanded_state =
1089            crate::run_sampler_program(&expanded, 130, Some(12345), false).unwrap();
1090        let combined_state =
1091            crate::run_sampler_program(&combined, 130, Some(12345), false).unwrap();
1092        assert_eq!(expanded_state.measurements, combined_state.measurements);
1093    }
1094
1095    #[test]
1096    fn does_not_fuse_measure_reset_across_a_gate_or_basis_change() {
1097        let compiled = compile_sampler(
1098            1,
1099            vec![
1100                Operation::H(0),
1101                Operation::Measure {
1102                    qubit: 0,
1103                    key: Some("m".to_string()),
1104                    basis: "Z".to_string(),
1105                    noise: None,
1106                },
1107                Operation::H(0),
1108                Operation::Reset {
1109                    qubit: 0,
1110                    key: None,
1111                    basis: "X".to_string(),
1112                },
1113            ],
1114        )
1115        .unwrap();
1116
1117        assert_eq!(compiled.operations().len(), 4);
1118        assert!(matches!(
1119            compiled.operations().last(),
1120            Some(SamplerOperation::Reset { ideal, .. }) if !ideal.terms().is_empty()
1121        ));
1122    }
1123
1124    #[test]
1125    fn does_not_reuse_measurement_expression_across_noise() {
1126        let location = NoiseLocation {
1127            id: "between".to_string(),
1128            model: NoiseModel::BernoulliPauli("X".to_string()),
1129            rate: 0.1,
1130            qubits: vec![0],
1131            tags: HashMap::new(),
1132        };
1133        let compiled = compile_sampler(
1134            1,
1135            vec![
1136                Operation::H(0),
1137                Operation::Measure {
1138                    qubit: 0,
1139                    key: Some("m".to_string()),
1140                    basis: "Z".to_string(),
1141                    noise: None,
1142                },
1143                Operation::Noise(location),
1144                Operation::Reset {
1145                    qubit: 0,
1146                    key: None,
1147                    basis: "Z".to_string(),
1148                },
1149            ],
1150        )
1151        .unwrap();
1152
1153        assert!(matches!(
1154            compiled.operations().last(),
1155            Some(SamplerOperation::Reset { ideal, .. }) if !ideal.terms().is_empty()
1156        ));
1157    }
1158}