Skip to main content

deq_runtime/
coordinator.rs

1use crate::decoder::DynDecoder;
2#[cfg(feature = "cli")]
3use crate::misc::util::help_message;
4#[cfg(feature = "cli")]
5use clap::ValueEnum;
6use serde::Serialize;
7use std::sync::Arc;
8#[cfg(feature = "cli")]
9use tonic::transport::Endpoint;
10#[cfg(feature = "cli")]
11use tonic::transport::server::Router;
12use tonic::{Request, Status};
13
14// Re-export so that generated proto code in window_coordinator::trace can
15// reference `super::super::bin::*` (i.e. coordinator::bin).
16pub(crate) use crate::bin;
17
18include!("proto/deq.coordinator.rs");
19#[cfg(feature = "cli")]
20use coordinator_server::CoordinatorServer;
21
22#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Debug)]
23#[cfg_attr(feature = "cli", derive(ValueEnum))]
24pub enum CoordinatorType {
25    /// a coordinator that does nothing but returning all-0 or random readouts
26    Naive,
27    /// a monolithic coordinator that only decode when all the output ports are
28    /// connected and the measurements are loaded.
29    Monolithic,
30    /// window decoding
31    Window,
32}
33
34impl crate::controller::ParseByName for CoordinatorType {
35    fn from_name(name: &str) -> Option<Self> {
36        match name {
37            "naive" => Some(Self::Naive),
38            "monolithic" => Some(Self::Monolithic),
39            "window" => Some(Self::Window),
40            _ => None,
41        }
42    }
43
44    fn variant_names() -> Vec<&'static str> {
45        vec!["naive", "monolithic", "window"]
46    }
47}
48
49pub mod naive_coordinator;
50pub use naive_coordinator::NaiveCoordinator;
51
52pub mod monolithic_coordinator;
53pub use monolithic_coordinator::MonolithicCoordinator;
54
55pub mod window_coordinator;
56pub use window_coordinator::WindowCoordinator;
57
58pub mod mock_coordinator;
59pub use mock_coordinator::MockCoordinator;
60
61pub mod decoder_cache_key;
62pub use decoder_cache_key::{
63    DecoderCacheKey, ErrorModelFingerprint, FingerprintSource, ProbabilityModifierBits, build_modifier_fingerprints,
64};
65
66pub mod reweight_handler;
67pub use reweight_handler::{DecodeProjection, DecoderReweighting, LoadedDecoder};
68
69pub mod loss_handler;
70pub use loss_handler::{EnvelopeReweightPolicy, LossHandler, LossStrategy, ReweightScale};
71
72mod forced_gap_handler;
73
74/// Latches the first seed for a shot and rejects later differences.
75/// `None` means no call yet; `Some(None)` latches an absent seed.
76#[cfg(any(feature = "cli", test))]
77pub(crate) fn accept_decoder_seed(slot: &mut Option<Option<u64>>, decoder_seed: Option<u64>) -> Result<(), Status> {
78    let expected = *slot.get_or_insert(decoder_seed);
79    if expected == decoder_seed {
80        Ok(())
81    } else {
82        Err(Status::invalid_argument(format!(
83            "decoder_seed cannot change within a shot: expected {expected:?}, received {decoder_seed:?}"
84        )))
85    }
86}
87
88/// Returns the common seed, or `InvalidArgument` if the inputs differ.
89/// Empty input returns `None`.
90pub(crate) fn common_decoder_seed(seeds: impl IntoIterator<Item = Option<u64>>) -> Result<Option<u64>, Status> {
91    let mut seeds = seeds.into_iter();
92    let Some(first) = seeds.next() else {
93        return Ok(None);
94    };
95    match seeds.find(|&seed| seed != first) {
96        None => Ok(first),
97        Some(other) => Err(Status::invalid_argument(format!(
98            "decoder_seed must match across gadgets decoded together: found {first:?} and {other:?}"
99        ))),
100    }
101}
102
103#[cfg(test)]
104mod decoder_seed_tests {
105    use super::*;
106
107    #[test]
108    fn decoder_seed_is_fixed_until_reset() {
109        let mut slot = None;
110        accept_decoder_seed(&mut slot, Some(42)).unwrap();
111        accept_decoder_seed(&mut slot, Some(42)).unwrap();
112
113        let error = accept_decoder_seed(&mut slot, Some(23)).unwrap_err();
114        assert_eq!(error.code(), tonic::Code::InvalidArgument);
115        assert_eq!(
116            error.message(),
117            "decoder_seed cannot change within a shot: expected Some(42), received Some(23)"
118        );
119
120        slot = None;
121        accept_decoder_seed(&mut slot, None).unwrap();
122    }
123
124    #[test]
125    fn gadgets_decoded_together_share_one_seed() {
126        assert_eq!(common_decoder_seed(std::iter::empty()).unwrap(), None);
127        assert_eq!(common_decoder_seed([None, None]).unwrap(), None);
128        assert_eq!(common_decoder_seed([Some(42), Some(42)]).unwrap(), Some(42));
129
130        let error = common_decoder_seed([Some(42), Some(23)]).unwrap_err();
131        assert_eq!(error.code(), tonic::Code::InvalidArgument);
132        assert!(error.message().contains("found Some(42) and Some(23)"));
133        assert!(
134            common_decoder_seed([Some(0), None]).is_err(),
135            "seed zero is not an absent seed"
136        );
137    }
138}
139
140impl CoordinatorType {
141    pub fn create(&self, config: serde_json::Value, decoder: DynDecoder) -> DynCoordinator {
142        self.create_with_gap_decoder(config, decoder, None)
143    }
144
145    /// Create a coordinator with an optional backend for forced-gap alternatives.
146    /// `None` reuses the hard decoder; the naive coordinator does not score gaps.
147    #[must_use]
148    pub fn create_with_gap_decoder(
149        &self,
150        config: serde_json::Value,
151        decoder: DynDecoder,
152        gap_decoder: Option<DynDecoder>,
153    ) -> DynCoordinator {
154        match self {
155            Self::Naive => DynCoordinator::Naive(Arc::new(NaiveCoordinator::new(config))),
156            Self::Monolithic => DynCoordinator::Monolithic(Arc::new(MonolithicCoordinator::with_gap_decoder(
157                config,
158                decoder,
159                gap_decoder,
160            ))),
161            Self::Window => {
162                DynCoordinator::Window(Arc::new(WindowCoordinator::with_gap_decoder(config, decoder, gap_decoder)))
163            }
164        }
165    }
166
167    #[cfg(feature = "cli")]
168    pub fn config_help() -> String {
169        help_message::<naive_coordinator::NaiveCoordinatorConfig>("NaiveCoordinatorConfig:")
170            + &*help_message::<monolithic_coordinator::MonolithicCoordinatorConfig>("MonolithicCoordinatorConfig:")
171            + &*help_message::<window_coordinator::WindowCoordinatorConfig>("WindowCoordinatorConfig:")
172    }
173
174    #[cfg(not(feature = "cli"))]
175    pub fn config_help() -> String {
176        String::new()
177    }
178}
179
180#[derive(Clone)]
181pub enum DynCoordinator {
182    None,
183    Naive(Arc<NaiveCoordinator>),
184    Monolithic(Arc<MonolithicCoordinator>),
185    Window(Arc<WindowCoordinator>),
186    Mock(Arc<MockCoordinator>),
187}
188
189impl DynCoordinator {
190    pub fn inner(&self) -> Arc<dyn coordinator_server::Coordinator> {
191        match self {
192            DynCoordinator::None => panic!("DynCoordinator::None has no inner coordinator"),
193            DynCoordinator::Naive(v) => v.clone(),
194            DynCoordinator::Monolithic(v) => v.clone(),
195            DynCoordinator::Window(v) => v.clone(),
196            DynCoordinator::Mock(v) => v.clone(),
197        }
198    }
199
200    #[cfg(feature = "cli")]
201    fn add_service_by(router: Router, service: &Arc<impl coordinator_server::Coordinator>) -> Router {
202        let service = CoordinatorServer::from_arc(service.clone()).max_decoding_message_size(usize::MAX);
203        router.add_service(service)
204    }
205
206    #[cfg(feature = "cli")]
207    pub fn add_service(&self, router: Router) -> Router {
208        match self {
209            DynCoordinator::None => router,
210            DynCoordinator::Naive(c) => Self::add_service_by(router, c),
211            DynCoordinator::Monolithic(c) => Self::add_service_by(router, c),
212            DynCoordinator::Window(c) => Self::add_service_by(router, c),
213            DynCoordinator::Mock(c) => Self::add_service_by(router, c),
214        }
215    }
216
217    pub async fn start(&self) {}
218
219    /// Fire each underlying coordinator's cancellation token to abort pending
220    /// decode tasks. Coordinators without a cancellation surface (`Naive`,
221    /// `Mock`) are no-ops. Used by [`crate::server::LocalServer::shutdown`].
222    pub async fn cancel_pending(&self) {
223        match self {
224            DynCoordinator::None => {}
225            DynCoordinator::Naive(_) => {}
226            DynCoordinator::Monolithic(c) => c.cancel_pending().await,
227            DynCoordinator::Window(c) => c.cancel_pending().await,
228            DynCoordinator::Mock(_) => {}
229        }
230    }
231}
232
233/// a client wrapper that can either be a remote gRPC client or a local reference
234#[derive(Clone)]
235pub enum CoordinatorClient {
236    #[cfg(feature = "cli")]
237    Remote(coordinator_client::CoordinatorClient<tonic::transport::Channel>),
238    Local(DynCoordinator),
239}
240
241impl CoordinatorClient {
242    #[cfg(feature = "cli")]
243    pub async fn from_endpoint(endpoint: Endpoint) -> Self {
244        CoordinatorClient::Remote(
245            crate::coordinator::coordinator_client::CoordinatorClient::connect(endpoint)
246                .await
247                .unwrap(),
248        )
249    }
250
251    /// Create a CoordinatorClient from a MockCoordinator for testing.
252    pub fn from_mock(mock: Arc<MockCoordinator>) -> Self {
253        CoordinatorClient::Local(DynCoordinator::Mock(mock))
254    }
255
256    pub async fn reset(&self, flags: ResetRequest) -> std::result::Result<(), Status> {
257        let request = Request::new(flags);
258        (match self {
259            #[cfg(feature = "cli")]
260            CoordinatorClient::Remote(client) => client.clone().reset(request).await,
261            CoordinatorClient::Local(local) => local.inner().reset(request).await,
262        })
263        .map(|v| v.into_inner())
264    }
265
266    pub async fn load_library(&self, library: crate::bin::Library) -> std::result::Result<(), Status> {
267        let request = Request::new(library);
268        (match self {
269            #[cfg(feature = "cli")]
270            CoordinatorClient::Remote(client) => client.clone().load_library(request).await,
271            CoordinatorClient::Local(local) => local.inner().load_library(request).await,
272        })
273        .map(|v| v.into_inner())
274    }
275
276    pub async fn unload(&self, _unload: UnloadLibrary) -> std::result::Result<(), Status> {
277        unimplemented!()
278    }
279
280    pub async fn execute(&self, instruction: crate::bin::Instruction) -> std::result::Result<ExecuteResponse, Status> {
281        let request = Request::new(instruction);
282        (match self {
283            #[cfg(feature = "cli")]
284            CoordinatorClient::Remote(client) => client.clone().execute(request).await,
285            CoordinatorClient::Local(local) => local.inner().execute(request).await,
286        })
287        .map(|v| v.into_inner())
288    }
289
290    pub async fn decode(&self, outcomes: Outcomes) -> std::result::Result<Readouts, Status> {
291        let request = Request::new(outcomes);
292        (match self {
293            #[cfg(feature = "cli")]
294            CoordinatorClient::Remote(client) => client.clone().decode(request).await,
295            CoordinatorClient::Local(local) => local.inner().decode(request).await,
296        })
297        .map(|v| v.into_inner())
298    }
299}
300
301#[cfg(any(feature = "cli", feature = "simulator"))]
302impl Readouts {
303    pub(crate) fn gather(gadget_readouts: &[Self]) -> Result<Self, Status> {
304        let mut result = Self {
305            readouts: Some(crate::util::BitVector::default()),
306            ..Default::default()
307        };
308        for gadget in gadget_readouts {
309            let readouts = gadget
310                .readouts
311                .as_ref()
312                .ok_or_else(|| Status::internal("decoder returned no readouts"))?;
313            crate::misc::bit_vector::append(result.readouts.as_mut().unwrap(), readouts);
314            result.probabilities.extend_from_slice(&gadget.probabilities);
315            result.syndrome_count += gadget.syndrome_count;
316            result.correction_count += gadget.correction_count;
317            result.correction_weight += gadget.correction_weight;
318        }
319        Ok(result)
320    }
321}