1use crate::decoder::blackbox_decoder::{self, black_box_decoder_server};
7use crate::decoder::decoder_features::DecoderFeatures;
8use crate::util::BitVector;
9use hashbrown::HashMap;
10use serde::{Deserialize, Serialize};
11use std::sync::Arc;
12#[cfg(feature = "cli")]
13use structdoc::StructDoc;
14use tokio::sync::{Notify, RwLock};
15#[cfg(feature = "cli")]
16use tonic::transport::server::Router;
17use tonic::{Request, Response, Status};
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
21#[cfg_attr(feature = "cli", derive(StructDoc))]
22#[serde(deny_unknown_fields)]
23pub struct MockDecoderConfig {
24 #[serde(default)]
26 pub decode_delay_ms: u64,
27}
28
29pub struct MockDecoder {
31 pub state: RwLock<MockDecoderState>,
32 pub decode_delay: std::sync::Mutex<Option<std::time::Duration>>,
34 decode_blocker: std::sync::Mutex<Option<Arc<MockDecoderDecodeBlocker>>>,
35 features: DecoderFeatures,
36}
37
38pub struct MockDecoderDecodeBlocker {
39 started: Notify,
40 release: Notify,
41}
42
43impl MockDecoderDecodeBlocker {
44 pub async fn wait_until_started(&self) {
45 self.started.notified().await;
46 }
47
48 pub fn release(&self) {
49 self.release.notify_one();
50 }
51}
52
53#[derive(Default)]
54pub struct MockDecoderState {
55 pub decode_calls: Vec<DecodeProblem>,
57 pub loaded_hypergraphs: HashMap<u64, blackbox_decoder::DecodingHypergraph>,
59 pub decode_loaded_calls: Vec<LoadedDecodeProblem>,
61 pub next_hid: u64,
63 pub reset_count: usize,
65 pub load_error: Option<Status>,
66 pub decode_error: Option<Status>,
67 pub custom_responses: HashMap<Vec<u8>, Vec<u64>>,
70}
71
72#[derive(Clone, Debug)]
74pub struct DecodeProblem {
75 pub hypergraph: blackbox_decoder::DecodingHypergraph,
76 pub syndrome: BitVector,
77 pub loss: Option<blackbox_decoder::LossInfo>,
78 pub decoder_seed: Option<u64>,
79}
80
81#[derive(Clone, Debug)]
83pub struct LoadedDecodeProblem {
84 pub hid: u64,
85 pub syndrome: BitVector,
86 pub reweights: Vec<blackbox_decoder::EdgeReweight>,
87 pub loss: Option<blackbox_decoder::LossInfo>,
88 pub decoder_seed: Option<u64>,
89}
90
91impl MockDecoder {
92 pub fn new() -> Self {
93 Self::with_features(DecoderFeatures::REWEIGHTS | DecoderFeatures::LOSS | DecoderFeatures::SEED)
94 }
95
96 pub fn with_features(features: DecoderFeatures) -> Self {
97 Self {
98 state: RwLock::new(MockDecoderState {
99 next_hid: 1,
100 ..Default::default()
101 }),
102 decode_delay: std::sync::Mutex::new(None),
103 decode_blocker: std::sync::Mutex::new(None),
104 features,
105 }
106 }
107
108 pub fn supported_features(&self) -> DecoderFeatures {
109 self.features
110 }
111
112 pub fn from_config(config: serde_json::Value) -> Self {
114 let config: MockDecoderConfig = serde_json::from_value(config).unwrap();
115 let delay = if config.decode_delay_ms > 0 {
116 Some(std::time::Duration::from_millis(config.decode_delay_ms))
117 } else {
118 None
119 };
120 Self {
121 state: RwLock::new(MockDecoderState {
122 next_hid: 1,
123 ..Default::default()
124 }),
125 decode_delay: std::sync::Mutex::new(delay),
126 decode_blocker: std::sync::Mutex::new(None),
127 features: DecoderFeatures::REWEIGHTS | DecoderFeatures::LOSS | DecoderFeatures::SEED,
128 }
129 }
130
131 #[cfg(feature = "cli")]
132 pub fn add_service(self: &Arc<Self>, router: Router) -> Router {
133 let service =
134 black_box_decoder_server::BlackBoxDecoderServer::from_arc(self.clone()).max_decoding_message_size(usize::MAX);
135 router.add_service(service)
136 }
137
138 pub async fn clear(&self) {
140 let mut state = self.state.write().await;
141 state.decode_calls.clear();
142 state.loaded_hypergraphs.clear();
143 state.decode_loaded_calls.clear();
144 state.next_hid = 1;
145 state.reset_count = 0;
146 state.load_error = None;
147 state.decode_error = None;
148 state.custom_responses.clear();
149 }
150
151 pub async fn set_response(&self, syndrome_data: Vec<u8>, subgraph: Vec<u64>) {
153 let mut state = self.state.write().await;
154 state.custom_responses.insert(syndrome_data, subgraph);
155 }
156
157 pub fn set_decode_delay(&self, delay: std::time::Duration) {
159 *self.decode_delay.lock().unwrap() = Some(delay);
160 }
161
162 pub fn block_next_decode(&self) -> Arc<MockDecoderDecodeBlocker> {
164 let blocker = Arc::new(MockDecoderDecodeBlocker {
165 started: Notify::new(),
166 release: Notify::new(),
167 });
168 *self.decode_blocker.lock().unwrap() = Some(Arc::clone(&blocker));
169 blocker
170 }
171
172 fn get_response(state: &MockDecoderState, syndrome: &BitVector) -> Vec<u64> {
174 state.custom_responses.get(&syndrome.data).cloned().unwrap_or_default()
175 }
176
177 async fn apply_delay(&self) {
179 let blocker = self.decode_blocker.lock().unwrap().take();
180 if let Some(blocker) = blocker {
181 blocker.started.notify_one();
182 blocker.release.notified().await;
183 }
184 let delay = *self.decode_delay.lock().unwrap();
185 if let Some(delay) = delay {
186 tokio::time::sleep(delay).await;
187 }
188 }
189}
190
191impl Default for MockDecoder {
192 fn default() -> Self {
193 Self::new()
194 }
195}
196
197impl std::fmt::Debug for MockDecoder {
198 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199 f.debug_struct("MockDecoder").finish()
200 }
201}
202
203#[tonic::async_trait]
204impl black_box_decoder_server::BlackBoxDecoder for MockDecoder {
205 async fn get_capabilities(
206 &self,
207 _request: Request<()>,
208 ) -> Result<Response<blackbox_decoder::DecoderCapabilities>, Status> {
209 Ok(Response::new(self.features.to_proto()))
210 }
211
212 async fn decode(
213 &self,
214 request: Request<blackbox_decoder::DecodingProblem>,
215 ) -> Result<Response<blackbox_decoder::ParityFactor>, Status> {
216 let problem = request.into_inner();
217 DecoderFeatures::required(problem.decoder_seed.is_some(), false, problem.loss.is_some())
218 .require_supported_by(self.features)
219 .map_err(|unsupported| Status::failed_precondition(format!("unsupported decoder features: {unsupported}")))?;
220 let hypergraph = problem
221 .hypergraph
222 .ok_or_else(|| Status::invalid_argument("missing hypergraph"))?;
223 let syndrome = problem.syndrome.ok_or_else(|| Status::invalid_argument("missing syndrome"))?;
224
225 let mut state = self.state.write().await;
226 state.decode_calls.push(DecodeProblem {
227 hypergraph: hypergraph.clone(),
228 syndrome: syndrome.clone(),
229 loss: problem.loss,
230 decoder_seed: problem.decoder_seed,
231 });
232
233 let subgraph = Self::get_response(&state, &syndrome);
234 let error = state.decode_error.clone();
235 drop(state);
236 self.apply_delay().await;
237 if let Some(error) = error {
238 return Err(error);
239 }
240 Ok(Response::new(blackbox_decoder::ParityFactor { subgraph }))
241 }
242
243 async fn load_hypergraph(
244 &self,
245 request: Request<blackbox_decoder::DecodingHypergraph>,
246 ) -> Result<Response<blackbox_decoder::LoadHypergraphResponse>, Status> {
247 let hypergraph = request.into_inner();
248
249 let mut state = self.state.write().await;
250 if let Some(error) = &state.load_error {
251 return Err(error.clone());
252 }
253 let hid = state.next_hid;
254 state.next_hid += 1;
255 state.loaded_hypergraphs.insert(hid, hypergraph);
256
257 Ok(Response::new(blackbox_decoder::LoadHypergraphResponse { hid }))
258 }
259
260 async fn decode_loaded(
261 &self,
262 request: Request<blackbox_decoder::LoadedDecodingProblem>,
263 ) -> Result<Response<blackbox_decoder::ParityFactor>, Status> {
264 let problem = request.into_inner();
265 DecoderFeatures::required(
266 problem.decoder_seed.is_some(),
267 !problem.reweights.is_empty(),
268 problem.loss.is_some(),
269 )
270 .require_supported_by(self.features)
271 .map_err(|unsupported| Status::failed_precondition(format!("unsupported decoder features: {unsupported}")))?;
272 let syndrome = problem.syndrome.ok_or_else(|| Status::invalid_argument("missing syndrome"))?;
273
274 let mut state = self.state.write().await;
275 if !state.loaded_hypergraphs.contains_key(&problem.hid) {
276 return Err(Status::not_found(format!("hid={}", problem.hid)));
277 }
278
279 state.decode_loaded_calls.push(LoadedDecodeProblem {
280 hid: problem.hid,
281 syndrome: syndrome.clone(),
282 reweights: problem.reweights,
283 loss: problem.loss,
284 decoder_seed: problem.decoder_seed,
285 });
286
287 let subgraph = Self::get_response(&state, &syndrome);
288 let error = state.decode_error.clone();
289 drop(state);
290 self.apply_delay().await;
291 if let Some(error) = error {
292 return Err(error);
293 }
294 Ok(Response::new(blackbox_decoder::ParityFactor { subgraph }))
295 }
296
297 async fn reset(&self, request: Request<blackbox_decoder::ResetRequest>) -> Result<Response<()>, Status> {
298 let flags = request.into_inner();
299 let mut state = self.state.write().await;
300 state.reset_count += 1;
301 if flags.reset_hypergraphs {
302 state.loaded_hypergraphs.clear();
303 state.next_hid = 1;
304 }
305 Ok(().into())
306 }
307}