Skip to main content

deq_runtime/simulator/
common.rs

1//! Common simulation functionality shared between static and JIT static simulators.
2
3#[cfg(feature = "simulator")]
4use crate::SIGNAL_CHECKER;
5#[cfg(feature = "simulator")]
6use crate::misc::bit_vector::{self, bit_vector_to_string};
7#[cfg(feature = "simulator")]
8use crate::misc::fastrace::{Event, Span, SpanContext};
9use crate::simulator::DeterministicRng;
10#[cfg(feature = "simulator")]
11use crate::simulator::{SimulatorShot, SimulatorTrace};
12use crate::util::BitVector;
13#[cfg(all(feature = "cli", feature = "simulator"))]
14use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle};
15#[cfg(feature = "simulator")]
16use prost::Message;
17use serde::{Deserialize, Serialize};
18#[cfg(all(feature = "cli", feature = "simulator"))]
19use std::io::IsTerminal;
20#[cfg(feature = "simulator")]
21use std::time::Instant;
22#[cfg(feature = "cli")]
23use structdoc::StructDoc;
24#[cfg(feature = "simulator")]
25use tokio::sync::oneshot::Sender;
26
27/// Common configuration fields shared by all static-style simulators.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[cfg_attr(feature = "cli", derive(StructDoc))]
30#[serde(deny_unknown_fields)]
31pub struct CommonSimulatorConfig {
32    /// the optional seed for the random number generator
33    pub seed: Option<u64>,
34    /// skipping the first N shots (without actually decoding them)
35    #[serde(default)]
36    pub skip_shots: usize,
37    /// the number of shots to simulate, by default 4000; setting it to 0 means
38    /// infinite shots until reaching the error limit
39    #[serde(default = "default_shots")]
40    pub shots: usize,
41    /// the number of logical errors before terminating, by default 4000; setting it to 0 means
42    /// infinite errors until reaching the shot limit
43    #[serde(default = "default_shots")]
44    pub errors: usize,
45    /// iterate single errors, helpful for testing if a decoder works properly
46    #[serde(default)]
47    pub iterate_single_error: bool,
48    #[serde(default)]
49    pub print_all: bool,
50    #[serde(default)]
51    pub print_on_error: bool,
52    /// when true, (1) sampling is synchronous with decoding so that decoder
53    /// timing measurements are not distorted by concurrent sampling work,
54    /// and (2) measurement delays specified via ``#!delay`` directives in
55    /// the Stim file are respected (the simulator sleeps before delivering
56    /// each batch); when false, all measurements are delivered at once and
57    /// the sampler runs ahead in the background for throughput
58    #[serde(default)]
59    pub strict_timing: bool,
60    /// optional path to a Rhai script that defines
61    /// `fn is_logical_error(shot, readouts, measurements)`;
62    /// when set, the script is the sole arbiter of logical errors instead of
63    /// the built-in readout comparison
64    #[serde(default)]
65    pub logical_assert_filepath: Option<String>,
66    /// Optional protobuf path for per-gadget readouts and decoding statistics,
67    /// optional scores, and per-shot logical-error labels. No selection is applied.
68    #[serde(default)]
69    pub simulator_trace_output: Option<String>,
70    /// Maximum number of resample attempts when preselect checks fail.
71    /// Only used when the Stim circuit contains `SELECT { ... REQUIRE ... }`
72    /// blocks (QDK v1.30+).
73    #[serde(default = "default_preselect_max_attempts")]
74    pub preselect_max_attempts: u64,
75}
76
77pub fn default_preselect_max_attempts() -> u64 {
78    1_000_000
79}
80
81pub fn default_shots() -> usize {
82    4000
83}
84
85/// Trait for decoder clients that can be used with the common simulation loop.
86#[allow(async_fn_in_trait)]
87pub trait DecoderClient: Send {
88    /// Initialize the client connection and any setup required before simulation.
89    async fn initialize(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
90
91    /// Decode a sample and return each gadget's readouts and statistics in program order.
92    async fn decode(
93        &mut self,
94        sample: &ErrorSet,
95    ) -> Result<Vec<crate::coordinator::Readouts>, Box<dyn std::error::Error + Send + Sync>>;
96
97    /// Reset the decoder state for the next shot.
98    async fn reset(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
99
100    /// Get the name of the simulator for logging purposes.
101    fn simulator_name(&self) -> &'static str;
102
103    /// Return the latency of the last decode batch (time from sending the final
104    /// measurement batch to receiving readouts). For batch mode this equals the
105    /// total decode time; for streaming mode it measures only the final blocking
106    /// call. Returns 0.0 if not applicable.
107    fn last_decode_latency_secs(&self) -> f64 {
108        0.0
109    }
110}
111
112/// A delay schedule entry: send measurements [0..count) at the given delay.
113#[derive(Debug, Clone)]
114pub struct DelayBatch {
115    /// Cumulative measurement count up to and including this batch.
116    pub cumulative_count: usize,
117    /// Time in seconds at which this batch becomes available.
118    pub delay_seconds: f64,
119}
120
121/// Run the common simulation loop with the given decoder client.
122#[cfg(feature = "simulator")]
123pub async fn run_simulation_loop<C: DecoderClient>(
124    config: &CommonSimulatorConfig,
125    sampler: &dyn Sampler,
126    rng: &mut DeterministicRng,
127    client: &mut C,
128    shutdown: Sender<()>,
129    rhai_engine: &crate::simulator::rhai_assert::RhaiAssertEngine,
130) {
131    // Initialize the client
132    if let Err(e) = client.initialize().await {
133        eprintln!("Failed to initialize client: {e}");
134        shutdown.send(()).unwrap();
135        return;
136    }
137
138    let mut max_shots = if config.shots == 0 { usize::MAX } else { config.shots };
139    let mut max_errors = if config.errors == 0 { usize::MAX } else { config.errors };
140    if config.iterate_single_error {
141        max_shots = sampler.count_single_error();
142        max_errors = max_shots;
143    }
144
145    // Progress bar setup (only with indicatif feature)
146    #[cfg(feature = "cli")]
147    let (multi, shot_bar, error_bar, stats_bar) = {
148        let is_tty = std::io::stdout().is_terminal() && std::io::stderr().is_terminal();
149        let multi = if is_tty {
150            MultiProgress::new()
151        } else {
152            MultiProgress::with_draw_target(ProgressDrawTarget::hidden())
153        };
154        let shot_bar = ProgressBar::new(max_shots as u64);
155        shot_bar.set_style(ProgressStyle::with_template(" shots: [{eta_precise}] {wide_bar} {pos}/{len}").unwrap());
156        multi.add(shot_bar.clone());
157        let error_bar = ProgressBar::new(max_errors as u64);
158        error_bar.set_style(ProgressStyle::with_template("errors: [{eta_precise}] {wide_bar} {pos}/{len}").unwrap());
159        multi.add(error_bar.clone());
160        let stats_bar = ProgressBar::new(1_u64);
161        stats_bar.set_style(ProgressStyle::with_template("elapsed: [{elapsed_precise}] {msg}").unwrap());
162        multi.add(stats_bar.clone());
163        (multi, shot_bar, error_bar, stats_bar)
164    };
165
166    for _ in 0..config.skip_shots {
167        #[cfg(feature = "cli")]
168        shot_bar.inc(1);
169        rng.jump();
170    }
171
172    let mut decode_elapsed = 0.0;
173    let mut latency_elapsed = 0.0;
174    let mut actual_shots = 0;
175    let mut logical_errors = 0;
176    let mut failed_shots = 0;
177    let mut interrupted = false;
178    let mut reset_failed = false;
179    let simulator_name = client.simulator_name();
180    let mut trace_output = config.simulator_trace_output.as_ref().map(|path| {
181        std::io::BufWriter::new(
182            std::fs::File::create(path).unwrap_or_else(|error| panic!("failed to create {path}: {error}")),
183        )
184    });
185
186    for shot in config.skip_shots..max_shots {
187        // Check for Ctrl+C signal
188        if SIGNAL_CHECKER.check().is_err() {
189            println!("\nInterrupted by user (Ctrl+C)");
190            interrupted = true;
191            break;
192        }
193
194        let span = Span::root(simulator_name, SpanContext::random());
195        span.add_property(|| ("shot", format!("{shot}")));
196        actual_shots += 1;
197        #[cfg(feature = "cli")]
198        shot_bar.inc(1);
199
200        // Sample errors
201        let sample = if config.iterate_single_error {
202            sampler.sample_single_error(shot)
203        } else {
204            sampler.sample(rng)
205        };
206        span.add_property(|| ("sample", format!("{sample:?}")));
207        rng.jump();
208
209        // Decode
210        span.add_event(Event::new("start_decoding"));
211        let decode_start = Instant::now();
212        let (gadget_readouts, decoded) = match client.decode(&sample).await {
213            Ok(gadget_readouts) => {
214                let decoded = crate::coordinator::Readouts::gather(&gadget_readouts).map_err(Into::into);
215                (gadget_readouts, decoded)
216            }
217            Err(error) => (vec![], Err(error)),
218        };
219        decode_elapsed += decode_start.elapsed().as_secs_f64();
220        let shot_latency = client.last_decode_latency_secs();
221        latency_elapsed += shot_latency;
222        span.add_property(|| ("last_decode_latency_secs", format!("{shot_latency}")));
223
224        // Process results
225        span.add_event(Event::new("process_result"));
226        let is_decode_failure = decoded.is_err();
227        failed_shots += usize::from(is_decode_failure);
228        let is_logical_error = decoded
229            .as_ref()
230            .is_ok_and(|decoded| rhai_engine.is_logical_error(shot, decoded.readouts.as_ref(), &sample.measurements));
231        if is_logical_error {
232            logical_errors += 1;
233            #[cfg(feature = "cli")]
234            error_bar.inc(1);
235        }
236        span.add_property(|| ("readouts", format!("{decoded:?}")));
237        span.add_property(|| ("error", (if is_logical_error { "1" } else { "0" }).to_string()));
238
239        if config.print_all || (config.print_on_error && (is_logical_error || is_decode_failure)) {
240            let logical_str = if is_decode_failure {
241                "(failed)"
242            } else if is_logical_error {
243                "(error)"
244            } else {
245                ""
246            };
247            let readouts_str = decoded
248                .as_ref()
249                .ok()
250                .and_then(|result| result.readouts.as_ref())
251                .map_or_else(|| "None".to_string(), bit_vector_to_string);
252            let physical_str = sample
253                .errors
254                .iter()
255                .map(|(mi, ei)| format!("({mi},{ei})'{}'", sampler.error_tag(*mi, *ei)))
256                .collect::<Vec<_>>()
257                .join(",");
258            let message = format!(
259                "\n[{}]{}: readouts:{}, physical_errors:{}",
260                shot, logical_str, readouts_str, physical_str
261            );
262            #[cfg(feature = "cli")]
263            let _ = multi.println(message);
264            #[cfg(not(feature = "cli"))]
265            println!("{}", message);
266        }
267
268        if let Some(output) = trace_output.as_mut() {
269            let decoded = decoded.ok();
270            if let Some(decoded) = &decoded {
271                assert!(
272                    decoded.probabilities.is_empty()
273                        || decoded.probabilities.len() == usize::try_from(decoded.readouts.as_ref().unwrap().size).unwrap(),
274                    "forced-gap probability count must match the logical readout count"
275                );
276            }
277            let record = SimulatorShot {
278                shot: shot as u64,
279                decode_result: decoded,
280                logical_error: is_logical_error,
281                gadget_readouts,
282            };
283            write_simulator_shot(output, record).expect("failed to write simulator trace");
284        }
285
286        // Reset for next shot
287        span.add_event(Event::new("reset"));
288        if let Err(e) = client.reset().await {
289            eprintln!("Failed to reset client: {e}");
290            reset_failed = true;
291            break;
292        }
293
294        // Update progress bar
295        #[cfg(feature = "cli")]
296        {
297            error_bar.tick();
298            let retained_shots = actual_shots - failed_shots;
299            let error_rate = logical_errors as f64 / retained_shots.max(1) as f64;
300            let confidence_interval_95_percent =
301                1.96 * (error_rate * (1. - error_rate) / retained_shots.max(1) as f64).sqrt() / error_rate;
302            stats_bar.set_message(format!(
303                "decoding time: {:.3e}s ({:.3e}s per shots), failed shots: {}, logical error rate: {:.3e} ± {:.1e}",
304                decode_elapsed,
305                decode_elapsed / (actual_shots as f64),
306                failed_shots,
307                error_rate,
308                confidence_interval_95_percent
309            ));
310        }
311
312        if logical_errors >= max_errors {
313            #[cfg(feature = "cli")]
314            {
315                shot_bar.force_draw();
316                error_bar.force_draw();
317                stats_bar.force_draw();
318            }
319            break;
320        }
321    }
322
323    if let Some(output) = trace_output.as_mut() {
324        std::io::Write::flush(output).expect("failed to flush simulator trace");
325    }
326
327    // Print summary
328    let status = if reset_failed {
329        "Failed"
330    } else if interrupted {
331        "Interrupted"
332    } else {
333        "Complete"
334    };
335    let retained_shots = actual_shots - failed_shots;
336    let error_rate: f64 = if retained_shots > 0 {
337        (logical_errors as f64) / (retained_shots as f64)
338    } else {
339        0.0
340    };
341    let confidence_interval = if retained_shots > 0 {
342        1.96 * (error_rate * (1. - error_rate) / (retained_shots as f64)).sqrt()
343    } else {
344        0.0
345    };
346    println!("=== Simulation {status} ===");
347    if max_shots == usize::MAX {
348        println!("  Shots: {}", actual_shots);
349    } else {
350        println!("  Shots: {}/{}", actual_shots, max_shots);
351    }
352    if max_errors == usize::MAX {
353        println!("  Logical errors: {}", logical_errors);
354    } else {
355        println!("  Logical errors: {}/{}", logical_errors, max_errors);
356    }
357    println!("  Failed shots: {failed_shots}");
358    let retries = sampler.filtered_count();
359    if retries > 0 {
360        let total = retries + actual_shots as u64;
361        let pct = 100.0 * retries as f64 / total.max(1) as f64;
362        println!("  Retries: {retries} ({pct:.2}%)");
363    }
364    if retained_shots > 0 {
365        println!("  Error rate: {:.6e} ± {:.2e}", error_rate, confidence_interval);
366    } else {
367        println!("  Error rate: unavailable (no successful shots)");
368    }
369    println!(
370        "  Decoding time: {:.3}s ({:.3e}s per shot)",
371        decode_elapsed,
372        if actual_shots > 0 {
373            decode_elapsed / (actual_shots as f64)
374        } else {
375            0.0
376        }
377    );
378    if latency_elapsed > 0.0 {
379        println!(
380            "  Last-batch latency: {:.3}s ({:.3e}s per shot)",
381            latency_elapsed,
382            if actual_shots > 0 {
383                latency_elapsed / (actual_shots as f64)
384            } else {
385                0.0
386            }
387        );
388    }
389
390    // Don't drop the progress bar so that the final printings are preserved
391    #[cfg(feature = "cli")]
392    {
393        std::mem::forget(multi);
394        std::mem::forget(shot_bar);
395        std::mem::forget(error_bar);
396        std::mem::forget(stats_bar);
397    }
398
399    let _ = std::io::Write::flush(&mut std::io::stdout());
400
401    shutdown.send(()).unwrap();
402}
403
404#[cfg(feature = "simulator")]
405fn write_simulator_shot(output: &mut impl std::io::Write, shot: SimulatorShot) -> std::io::Result<()> {
406    output.write_all(&SimulatorTrace { shots: vec![shot] }.encode_to_vec())
407}
408
409#[derive(Clone, Debug)]
410pub struct ErrorSet {
411    /// (index of the marginal, index of the error in the marginal)
412    pub errors: Vec<(usize, usize)>,
413    pub measurements: BitVector,
414    /// Optional per-measurement loss mask, one bit per measurement in
415    /// `measurements`. A set bit means the corresponding measurement came from
416    /// a lost qubit. `None` when the
417    /// sampler cannot distinguish loss from a regular outcome (which is the
418    /// case for every loss-unaware sampler today).
419    pub loss_mask: Option<BitVector>,
420}
421
422/// Trait for measurement samplers used by the simulation loop.
423pub trait Sampler: Send + Sync {
424    /// Sample a set of errors.
425    fn sample(&self, rng: &mut DeterministicRng) -> ErrorSet;
426
427    /// Return the error set for a specific single error by index.
428    fn sample_single_error(&self, index: usize) -> ErrorSet;
429
430    /// Total number of individual errors across all marginals.
431    fn count_single_error(&self) -> usize;
432
433    /// Check if actual readouts match expected, respecting the readout mask.
434    fn readouts_match(&self, actual: &BitVector, expected: &BitVector) -> bool;
435
436    /// Get the tag string for a specific error in a specific marginal.
437    fn error_tag(&self, marginal_index: usize, error_index: usize) -> &str;
438
439    /// Number of samples that were filtered out (e.g. due to preselect
440    /// failures).  Returns 0 by default.
441    fn filtered_count(&self) -> u64 {
442        0
443    }
444}
445
446/// Load a Stim circuit file and return the sampler, delay schedule, and
447/// any embedded Rhai script.
448#[cfg(feature = "simulator")]
449pub fn load_stim_circuit(
450    filepath: &str,
451    seed: u64,
452    skip_shots: usize,
453    strict_timing: bool,
454) -> (Box<dyn Sampler>, Vec<DelayBatch>, Option<String>) {
455    let circuit_text =
456        std::fs::read_to_string(filepath).unwrap_or_else(|e| panic!("Failed to read Stim circuit file '{filepath}': {e}"));
457    let embedded_rhai_script = crate::simulator::rhai_assert::extract_rhai_script(&circuit_text);
458    let preselect_schedule = crate::simulator::preselect_directives::extract_preselect_schedule(&circuit_text);
459    // The upstream `stim` crate does not understand PREPARE/REQUIRE, so
460    // feed it the residual text with those directives removed.
461    let stim_only_text = crate::simulator::preselect_directives::strip_preselect_directives(&circuit_text);
462    let sampler = StimSampler::new(&stim_only_text, seed, skip_shots, strict_timing);
463    let delay_schedule = {
464        let circuit: stim::Circuit = stim_only_text
465            .parse()
466            .expect("Failed to parse Stim circuit for measurement counting");
467        let expected = usize::try_from(circuit.num_measurements()).unwrap();
468        crate::simulator::stim_delays::extract_delay_schedule(&circuit_text, expected)
469    };
470    let sampler: Box<dyn Sampler> = if preselect_schedule.is_empty() {
471        Box::new(sampler)
472    } else {
473        Box::new(ResamplePreselectSampler::new(
474            Box::new(sampler),
475            preselect_schedule,
476            1_000_000,
477        ))
478    };
479    (sampler, delay_schedule, embedded_rhai_script)
480}
481
482/// Backend selector for the standalone Python sampler.
483///
484/// Every variant accepts a Stim-format circuit string; backends differ in how
485/// they drive sampling and how they handle preselect directives. Constructed
486/// via [`SamplerType::from_name`] and turned into a [`Sampler`] by
487/// [`SamplerType::create`].
488#[cfg(feature = "simulator")]
489#[derive(Copy, Clone, PartialEq, Eq, Debug)]
490pub enum SamplerType {
491    /// Stim's compiled measurement sampler. When the circuit contains
492    /// `SELECT { ... REQUIRE ... }` blocks, the result is automatically
493    /// wrapped with [`ResamplePreselectSampler`], which resamples each shot
494    /// from the beginning until every REQUIRE check passes.
495    Stim,
496    /// Tableau-based sampler with retry-from-checkpoint semantics. Drives
497    /// `stim::TableauSimulator` directly and handles preselect natively.
498    /// More efficient than the `Stim` backend when many shots would be
499    /// rejected.
500    Preselect,
501}
502
503#[cfg(feature = "simulator")]
504impl SamplerType {
505    /// Look up a backend by its lowercase name.
506    pub fn from_name(name: &str) -> Option<Self> {
507        match name {
508            "stim" => Some(Self::Stim),
509            "preselect" => Some(Self::Preselect),
510            _ => None,
511        }
512    }
513
514    /// List of recognized backend names, for error messages.
515    pub fn variant_names() -> &'static [&'static str] {
516        &["stim", "preselect"]
517    }
518
519    /// Build a sampler backend from this variant and a JSON config.
520    ///
521    /// Each variant deserializes its **own** config struct, so the accepted
522    /// keys depend on the selected backend — see [`StimSamplerConfig`] and
523    /// [`crate::simulator::tableau_preselect_sampler::PreselectSamplerConfig`].
524    pub fn create(
525        &self,
526        circuit_text: &str,
527        seed: u64,
528        skip_shots: usize,
529        config: serde_json::Value,
530    ) -> Result<std::sync::Arc<dyn Sampler>, String> {
531        match self {
532            Self::Stim => {
533                let config: StimSamplerConfig =
534                    serde_json::from_value(config).map_err(|e| format!("invalid stim simulator_config: {e}"))?;
535                let schedule = crate::simulator::preselect_directives::extract_preselect_schedule(circuit_text);
536                let stim_only_text = crate::simulator::preselect_directives::strip_preselect_directives(circuit_text);
537                let base = StimSampler::new(&stim_only_text, seed, skip_shots, false);
538                if schedule.is_empty() {
539                    Ok(std::sync::Arc::new(base))
540                } else {
541                    Ok(std::sync::Arc::new(ResamplePreselectSampler::new(
542                        Box::new(base),
543                        schedule,
544                        config.preselect_max_attempts,
545                    )))
546                }
547            }
548            Self::Preselect => {
549                let config: crate::simulator::tableau_preselect_sampler::PreselectSamplerConfig =
550                    serde_json::from_value(config).map_err(|e| format!("invalid preselect simulator_config: {e}"))?;
551                Ok(std::sync::Arc::new(
552                    crate::simulator::tableau_preselect_sampler::TableauPreselectSampler::new(
553                        circuit_text,
554                        seed,
555                        skip_shots,
556                        false,
557                        config.preselect_max_attempts,
558                    ),
559                ))
560            }
561        }
562    }
563}
564
565/// A wrapper sampler that resamples until all preselect checks pass.
566///
567/// This is used by the static and jit-static simulators: after drawing a
568/// sample from the inner sampler, it checks the measurement record against
569/// the preselect schedule and retries (up to `max_attempts`) if any check
570/// fails.
571#[cfg(feature = "simulator")]
572pub struct ResamplePreselectSampler {
573    inner: Box<dyn Sampler>,
574    schedule: crate::simulator::preselect_directives::PreselectSchedule,
575    max_attempts: u64,
576    filtered: std::sync::atomic::AtomicU64,
577}
578
579#[cfg(feature = "simulator")]
580impl ResamplePreselectSampler {
581    pub fn new(
582        inner: Box<dyn Sampler>,
583        schedule: crate::simulator::preselect_directives::PreselectSchedule,
584        max_attempts: u64,
585    ) -> Self {
586        Self {
587            inner,
588            schedule,
589            max_attempts,
590            filtered: std::sync::atomic::AtomicU64::new(0),
591        }
592    }
593
594    fn checks_pass(&self, measurements: &BitVector) -> bool {
595        for check in &self.schedule.checks {
596            let all_in_range = check.targets.iter().all(|t| (t.abs_meas_idx as u64) < measurements.size);
597            if !all_in_range {
598                return false;
599            }
600            let passes = check.is_satisfied(|idx| bit_vector::get_bit(measurements, idx as u64));
601            if !passes {
602                return false;
603            }
604        }
605        true
606    }
607}
608
609#[cfg(feature = "simulator")]
610impl Sampler for ResamplePreselectSampler {
611    fn sample(&self, rng: &mut DeterministicRng) -> ErrorSet {
612        for _ in 0..self.max_attempts {
613            let sample = self.inner.sample(rng);
614            if self.checks_pass(&sample.measurements) {
615                return sample;
616            }
617            self.filtered.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
618        }
619        panic!(
620            "Preselect checks failed after {} attempts; \
621             consider increasing preselect_max_attempts",
622            self.max_attempts
623        );
624    }
625
626    fn sample_single_error(&self, index: usize) -> ErrorSet {
627        self.inner.sample_single_error(index)
628    }
629
630    fn count_single_error(&self) -> usize {
631        self.inner.count_single_error()
632    }
633
634    fn readouts_match(&self, actual: &BitVector, expected: &BitVector) -> bool {
635        self.inner.readouts_match(actual, expected)
636    }
637
638    fn error_tag(&self, marginal_index: usize, error_index: usize) -> &str {
639        self.inner.error_tag(marginal_index, error_index)
640    }
641
642    fn filtered_count(&self) -> u64 {
643        self.filtered.load(std::sync::atomic::Ordering::Relaxed)
644    }
645}
646
647/// JSON config for the [`SamplerType::Stim`] backend.
648///
649/// Used by [`SamplerType::create`]; unrelated to [`CommonSimulatorConfig`],
650/// which configures the full LER simulator harness.
651#[cfg(feature = "simulator")]
652#[derive(Debug, Clone, Serialize, Deserialize)]
653#[serde(deny_unknown_fields, default)]
654pub struct StimSamplerConfig {
655    /// Maximum number of resample attempts when the circuit contains
656    /// `SELECT { ... REQUIRE ... }` blocks. Ignored when the circuit has no
657    /// preselect directives.
658    pub preselect_max_attempts: u64,
659}
660
661#[cfg(feature = "simulator")]
662impl Default for StimSamplerConfig {
663    fn default() -> Self {
664        Self {
665            preselect_max_attempts: default_preselect_max_attempts(),
666        }
667    }
668}
669
670/// A sampler that pulls measurements from a Stim circuit via a background
671/// thread.  The thread parses the circuit text, builds a `stim::MeasurementSampler`,
672/// and streams one shot at a time through a channel.  The thread stops
673/// automatically when the `StimSampler` (and its receiver) is dropped.
674#[cfg(feature = "simulator")]
675pub struct StimSampler {
676    receiver: std::sync::Mutex<std::sync::mpsc::Receiver<Vec<bool>>>,
677    /// In strict-timing mode, a request is sent before each sample so the
678    /// background thread only works on-demand.
679    request: Option<std::sync::mpsc::SyncSender<()>>,
680}
681
682#[cfg(feature = "simulator")]
683impl StimSampler {
684    /// Create a new stim sampler.
685    ///
686    /// When `strict_timing` is true the background thread only samples
687    /// on-demand (one request → one sample) so it does not consume CPU while
688    /// the decoder is running, keeping timing measurements accurate.  When
689    /// false the thread samples ahead into a bounded buffer for throughput.
690    pub fn new(circuit_text: &str, seed: u64, skip_shots: usize, strict_timing: bool) -> Self {
691        let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<bool>>(if strict_timing { 0 } else { 16 });
692        let circuit_text = circuit_text.to_owned();
693
694        let (request, request_rx) = if strict_timing {
695            let (req_tx, req_rx) = std::sync::mpsc::sync_channel::<()>(0);
696            (Some(req_tx), Some(req_rx))
697        } else {
698            (None, None)
699        };
700
701        std::thread::Builder::new()
702            .name("stim-sampler".into())
703            .spawn(move || {
704                let circuit: stim::Circuit = circuit_text.parse().expect("Failed to parse Stim circuit");
705                let mut sampler = circuit.compile_sampler_with_seed(false, seed);
706
707                for _ in 0..skip_shots {
708                    let _ = sampler.sample(1);
709                }
710
711                loop {
712                    if let Some(ref req_rx) = request_rx
713                        && req_rx.recv().is_err()
714                    {
715                        break;
716                    }
717
718                    let batch = sampler.sample(1);
719                    let shot: Vec<bool> = batch.row(0).iter().copied().collect();
720                    if tx.send(shot).is_err() {
721                        break;
722                    }
723                }
724            })
725            .expect("Failed to spawn stim sampler thread");
726
727        Self {
728            receiver: std::sync::Mutex::new(rx),
729            request,
730        }
731    }
732
733    fn recv_sample(&self) -> ErrorSet {
734        if let Some(ref req) = self.request {
735            req.send(()).expect("Stim sampling thread stopped unexpectedly");
736        }
737        let rx = self.receiver.lock().unwrap();
738        let measurements_bool = rx.recv().expect("Stim sampling thread stopped unexpectedly");
739        ErrorSet {
740            errors: vec![],
741            measurements: BitVector {
742                size: measurements_bool.len() as u64,
743                data: bit_vector::pack_bits(&measurements_bool),
744            },
745            loss_mask: None,
746        }
747    }
748}
749
750#[cfg(feature = "simulator")]
751impl Sampler for StimSampler {
752    fn sample(&self, _rng: &mut DeterministicRng) -> ErrorSet {
753        self.recv_sample()
754    }
755
756    fn sample_single_error(&self, _index: usize) -> ErrorSet {
757        panic!("sample_single_error is not supported for StimSampler")
758    }
759
760    fn count_single_error(&self) -> usize {
761        panic!("count_single_error is not supported for StimSampler")
762    }
763
764    fn readouts_match(&self, _actual: &BitVector, _expected: &BitVector) -> bool {
765        true // readout assertion not yet implemented for stim
766    }
767
768    fn error_tag(&self, _marginal_index: usize, _error_index: usize) -> &str {
769        ""
770    }
771}
772
773/// Convert an [`ErrorSet`] (the in-Rust per-shot record produced by a
774/// [`Sampler`]) into a [`crate::simulator::ShotSample`] proto suitable for
775/// crossing the Python FFI as raw bytes. Used by the standalone Python
776/// `Sampler` binding.
777#[cfg(feature = "simulator")]
778pub fn error_set_to_shot_sample(sample: &ErrorSet) -> crate::simulator::ShotSample {
779    crate::simulator::ShotSample {
780        outcomes: Some(sample.measurements.clone()),
781        loss_mask: sample.loss_mask.clone(),
782    }
783}
784
785#[cfg(all(test, feature = "simulator"))]
786mod tests {
787    use super::*;
788    use rand::SeedableRng;
789
790    #[tokio::test]
791    async fn decode_failures_are_recorded_and_do_not_stop_later_shots() {
792        struct Client {
793            attempts: usize,
794            resets: usize,
795        }
796
797        impl DecoderClient for Client {
798            async fn initialize(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
799                Ok(())
800            }
801            async fn decode(
802                &mut self,
803                _sample: &ErrorSet,
804            ) -> Result<Vec<crate::coordinator::Readouts>, Box<dyn std::error::Error + Send + Sync>> {
805                self.attempts += 1;
806                match self.attempts {
807                    1 => Err(tonic::Status::failed_precondition("invalid decoder state").into()),
808                    3 => Err(tonic::Status::internal("decoder failure").into()),
809                    5 => Err(std::io::Error::other("local decoder failure").into()),
810                    _ => Ok(vec![crate::coordinator::Readouts {
811                        gid: 7,
812                        readouts: Some(BitVector {
813                            size: 1,
814                            data: vec![if self.attempts == 4 { 0x80 } else { 0 }],
815                        }),
816                        syndrome_count: 3,
817                        correction_count: 20,
818                        correction_weight: 12.5,
819                        ..Default::default()
820                    }]),
821                }
822            }
823            async fn reset(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
824                self.resets += 1;
825                Ok(())
826            }
827            fn simulator_name(&self) -> &'static str {
828                "failure-test"
829            }
830        }
831
832        let output = tempfile::NamedTempFile::new().unwrap();
833        let config: CommonSimulatorConfig = serde_json::from_value(serde_json::json!({
834            "shots": 6, "errors": 7, "simulator_trace_output": output.path(),
835        }))
836        .unwrap();
837        let sampler = StimSampler::new("M 0\n", 3, 0, false);
838        let mut client = Client { attempts: 0, resets: 0 };
839        let (shutdown, receiver) = tokio::sync::oneshot::channel();
840        let engine = crate::simulator::rhai_assert::RhaiAssertEngine::from_source(
841            "test",
842            "fn is_logical_error(shot, readouts, measurements) { readouts[0] }",
843        );
844        run_simulation_loop(
845            &config,
846            &sampler,
847            &mut DeterministicRng::seed_from_u64(3),
848            &mut client,
849            shutdown,
850            &engine,
851        )
852        .await;
853        receiver.await.unwrap();
854        assert_eq!((client.attempts, client.resets), (6, 6));
855        let trace = SimulatorTrace::decode(std::fs::read(output.path()).unwrap().as_slice()).unwrap();
856        assert_eq!(trace.shots.len(), 6);
857        assert_eq!(trace.shots[1].gadget_readouts[0].gid, 7);
858        assert_eq!(trace.shots[1].gadget_readouts[0].correction_count, 20);
859        assert_eq!(trace.shots[1].decode_result.as_ref().unwrap().correction_weight, 12.5);
860        assert_eq!(
861            trace
862                .shots
863                .iter()
864                .map(|shot| shot.decode_result.is_some())
865                .collect::<Vec<_>>(),
866            vec![false, true, false, true, false, true]
867        );
868        assert_eq!(
869            trace.shots.iter().map(|shot| shot.logical_error).collect::<Vec<_>>(),
870            vec![false, false, false, true, false, false]
871        );
872    }
873
874    #[test]
875    fn streamed_trace_roundtrips_hard_and_scored_readouts() {
876        let shots = vec![
877            SimulatorShot {
878                shot: 17,
879                decode_result: Some(crate::coordinator::Readouts {
880                    readouts: Some(BitVector { size: 1, data: vec![0] }),
881                    ..Default::default()
882                }),
883                logical_error: false,
884                gadget_readouts: vec![],
885            },
886            SimulatorShot {
887                shot: 18,
888                decode_result: Some(crate::coordinator::Readouts {
889                    readouts: Some(BitVector {
890                        size: 1,
891                        data: vec![0x80],
892                    }),
893                    probabilities: vec![0.1],
894                    ..Default::default()
895                }),
896                logical_error: true,
897                gadget_readouts: vec![],
898            },
899        ];
900        let mut output = vec![];
901        for shot in &shots {
902            write_simulator_shot(&mut output, shot.clone()).unwrap();
903        }
904        assert_eq!(SimulatorTrace::decode(output.as_slice()).unwrap().shots, shots);
905    }
906
907    #[test]
908    fn trace_preserves_gadget_statistics_without_choosing_an_aggregation_policy() {
909        let gadget_readouts = vec![
910            crate::coordinator::Readouts {
911                gid: 17,
912                readouts: Some(BitVector::default()),
913                frame_probabilities: vec![0.2, 0.05],
914                syndrome_count: 2,
915                correction_count: 3,
916                correction_weight: 7.0,
917                ..Default::default()
918            },
919            crate::coordinator::Readouts {
920                gid: 9,
921                readouts: Some(BitVector {
922                    size: 1,
923                    data: vec![0x80],
924                }),
925                probabilities: vec![0.1],
926                syndrome_count: 1,
927                correction_count: 2,
928                correction_weight: 4.0,
929                frame_probabilities: vec![],
930            },
931        ];
932        let aggregate = crate::coordinator::Readouts::gather(&gadget_readouts).unwrap();
933        assert_eq!((aggregate.syndrome_count, aggregate.correction_count), (3, 5));
934        assert_eq!(aggregate.correction_weight, 11.0);
935        let shot = SimulatorShot {
936            shot: 0,
937            decode_result: Some(aggregate),
938            logical_error: true,
939            gadget_readouts,
940        };
941        let mut output = vec![];
942        write_simulator_shot(&mut output, shot.clone()).unwrap();
943        let trace = SimulatorTrace::decode(output.as_slice()).unwrap();
944        assert_eq!(trace.shots, vec![shot]);
945        assert_eq!(
946            trace.shots[0]
947                .gadget_readouts
948                .iter()
949                .map(|gadget| gadget.correction_count)
950                .max(),
951            Some(3)
952        );
953    }
954
955    #[test]
956    fn resample_preselect_filters_and_counts() {
957        // Circuit: H 0 then M 0 — measurement is random 50/50.
958        // The PREPARE/REQUIRE block enforces that measurement 0 == 0
959        // (REQUIRE rec[-1] succeeds when XOR of listed records is 0).
960        // About half the samples should be rejected.
961        let circuit_text = "SELECT {\nH 0\nM 0\nREQUIRE rec[-1]\n}\n";
962        let stim_text = crate::simulator::preselect_directives::strip_preselect_directives(circuit_text);
963
964        let inner = StimSampler::new(&stim_text, 42, 0, false);
965        let schedule = crate::simulator::preselect_directives::extract_preselect_schedule(circuit_text);
966        assert!(!schedule.is_empty(), "schedule should have 1 check");
967
968        let sampler = ResamplePreselectSampler::new(Box::new(inner), schedule, 1_000_000);
969
970        let mut rng = DeterministicRng::seed_from_u64(99);
971        for _ in 0..20 {
972            let sample = sampler.sample(&mut rng);
973            // Measurement 0 must always be false (preselected to 0)
974            let bit = bit_vector::get_bit(&sample.measurements, 0);
975            assert!(!bit, "preselect should enforce measurement 0 == false");
976        }
977
978        let filtered = sampler.filtered_count();
979        assert!(
980            filtered > 0,
981            "with 50/50 outcomes over 20 shots, some should have been filtered; got {filtered}"
982        );
983        println!("Filtered {filtered} samples out of 20 successful shots");
984    }
985
986    #[test]
987    fn error_set_to_shot_sample_propagates_loss_mask() {
988        let measurements = BitVector {
989            size: 4,
990            data: vec![0b1010_0000],
991        };
992        let loss_mask = BitVector {
993            size: 4,
994            data: vec![0b0100_0000],
995        };
996
997        let with_loss = ErrorSet {
998            errors: vec![],
999            measurements: measurements.clone(),
1000            loss_mask: Some(loss_mask.clone()),
1001        };
1002        let shot = error_set_to_shot_sample(&with_loss);
1003        assert_eq!(shot.outcomes.as_ref(), Some(&measurements));
1004        assert_eq!(shot.loss_mask.as_ref(), Some(&loss_mask));
1005
1006        let without_loss = ErrorSet {
1007            errors: vec![],
1008            measurements: measurements.clone(),
1009            loss_mask: None,
1010        };
1011        let shot = error_set_to_shot_sample(&without_loss);
1012        assert_eq!(shot.outcomes.as_ref(), Some(&measurements));
1013        assert!(
1014            shot.loss_mask.is_none(),
1015            "loss_mask should stay absent when the sampler did not produce one"
1016        );
1017    }
1018}