qec-code 0.3.0

Rust primitives for constructing and analyzing quantum error-correcting codes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;

use serde::Deserialize;
use serde_json::Value;

use crate::error::{CssMatrixReadSource, QecError};
use crate::family_contract::{
    CssCodeStats, CssConstructionResult, RequestedFamilyId, construct_css,
    parse_css_construction_json, verify_css_orthogonality,
};

const MANIFEST_REL_PATH: &str = "tests/fixtures/family_manifest/manifest.v1.json";
const EXPECTED_FAMILY_IDS: [&str; 14] = [
    "directional",
    "quantum_tanner",
    "generalized_bicycle",
    "la_cross",
    "random_hgp",
    "lifted_product",
    "hyperbolic_5_5",
    "coprime_bb",
    "toric_3d",
    "color_666",
    "surface",
    "shor_like",
    "random_two_block",
    "perturbed_hgp",
];
const EXPECTED_SUPPORTED_FAMILIES: usize = 12;
const EXPECTED_DEFERRED_FAMILIES: usize = 2;

#[derive(Debug, Clone, Copy)]
struct DeferredFamilyBoundary {
    tracking_issue: usize,
    contract_path: &'static str,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FamilyVerificationReport {
    pub output: String,
    pub failed: usize,
}

pub fn verify_checked_in_family_manifest() -> Result<FamilyVerificationReport, QecError> {
    let path = checked_in_manifest_path();
    let text = fs::read_to_string(&path).map_err(|error| QecError::CssMatrixReadFailed {
        path: path.display().to_string(),
        source: CssMatrixReadSource(error.to_string()),
    })?;
    Ok(verify_family_manifest_text(&text))
}

pub fn verify_family_manifest_text(text: &str) -> FamilyVerificationReport {
    match serde_json::from_str::<FamilyCatalog>(text) {
        Ok(catalog) => verify_catalog(&catalog),
        Err(error) => failure_report(format!("FAIL manifest invalid_json={error}"), 0, 0),
    }
}

fn checked_in_manifest_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(MANIFEST_REL_PATH)
}

#[derive(Debug, Deserialize)]
struct FamilyCatalog {
    families: Vec<FamilyCatalogEntry>,
}

#[derive(Debug, Deserialize)]
struct FamilyCatalogEntry {
    family_id: String,
    disposition: FamilyDisposition,
    availability: RuntimeAvailability,
    #[serde(default)]
    research_contracts: Vec<String>,
    callable_constructor: Option<CallableConstructorRef>,
    expected: Option<ExpectedStats>,
    row_weight_summary: Option<RowWeightSummary>,
    #[serde(default)]
    executable_cases: Vec<ExecutableCase>,
}

#[derive(Debug, Deserialize)]
struct CallableConstructorRef {
    rust_path: String,
}

#[derive(Debug, PartialEq, Eq, Deserialize)]
struct ExpectedStats {
    n: usize,
    m_x: usize,
    m_z: usize,
    rank_x: usize,
    rank_z: usize,
    k: usize,
    d_x: Option<usize>,
    d_z: Option<usize>,
}

#[derive(Debug, PartialEq, Eq, Deserialize)]
struct RowWeightSummary {
    h_x: Vec<RowWeightBucket>,
    h_z: Vec<RowWeightBucket>,
}

#[derive(Debug, PartialEq, Eq, Deserialize)]
struct RowWeightBucket {
    weight: usize,
    count: usize,
}

#[derive(Debug, Deserialize)]
struct ExecutableCase {
    case_kind: ExecutableCaseKind,
    expected_outcome: ExpectedOutcome,
    request: Option<Value>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum FamilyDisposition {
    Supported,
    Deferred,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum RuntimeAvailability {
    Planned,
    Available,
    NotApplicable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ExecutableCaseKind {
    Positive,
    Negative,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ExpectedOutcome {
    Success,
    Rejection,
}

enum EntryVerification {
    Line(String),
    Failure(String),
}

fn verify_catalog(catalog: &FamilyCatalog) -> FamilyVerificationReport {
    let supported = catalog
        .families
        .iter()
        .filter(|entry| entry.disposition == FamilyDisposition::Supported)
        .count();
    let deferred = catalog
        .families
        .iter()
        .filter(|entry| entry.disposition == FamilyDisposition::Deferred)
        .count();
    let mut lines = manifest_contract_failures(catalog, supported, deferred);
    let mut failed = lines.len();

    for entry in &catalog.families {
        match verify_entry(entry) {
            EntryVerification::Line(line) => lines.push(line),
            EntryVerification::Failure(line) => {
                failed += 1;
                lines.push(line);
            }
        }
    }

    let status = if failed == 0 { "PASS" } else { "FAIL" };
    lines.push(format!(
        "SUMMARY {status} supported={supported} deferred={deferred} failed={failed}"
    ));
    FamilyVerificationReport {
        output: lines.join("\n"),
        failed,
    }
}

fn manifest_contract_failures(
    catalog: &FamilyCatalog,
    supported: usize,
    deferred: usize,
) -> Vec<String> {
    let mut failures = Vec::new();

    for family_id in EXPECTED_FAMILY_IDS {
        let occurrences = catalog
            .families
            .iter()
            .filter(|entry| entry.family_id == family_id)
            .count();
        match occurrences {
            0 => failures.push(format!("FAIL manifest missing family_id={family_id}")),
            1 => {}
            _ => failures.push(format!("FAIL manifest duplicate family_id={family_id}")),
        }
    }

    for entry in &catalog.families {
        if !EXPECTED_FAMILY_IDS.contains(&entry.family_id.as_str()) {
            failures.push(format!(
                "FAIL manifest unexpected family_id={}",
                entry.family_id
            ));
        }
    }

    for (index, entry) in catalog.families.iter().enumerate() {
        let expected = EXPECTED_FAMILY_IDS.get(index).copied().unwrap_or("none");
        if entry.family_id != expected {
            failures.push(format!(
                "FAIL manifest family_id_order index={index} expected={expected} actual={}",
                entry.family_id
            ));
        }
    }

    if supported != EXPECTED_SUPPORTED_FAMILIES {
        failures.push(format!(
            "FAIL manifest expected supported={EXPECTED_SUPPORTED_FAMILIES} actual supported={supported}"
        ));
    }
    if deferred != EXPECTED_DEFERRED_FAMILIES {
        failures.push(format!(
            "FAIL manifest expected deferred={EXPECTED_DEFERRED_FAMILIES} actual deferred={deferred}"
        ));
    }

    failures
}

fn verify_entry(entry: &FamilyCatalogEntry) -> EntryVerification {
    match entry.disposition {
        FamilyDisposition::Supported => verify_supported_entry(entry),
        FamilyDisposition::Deferred => verify_deferred_entry(entry),
    }
}

fn verify_supported_entry(entry: &FamilyCatalogEntry) -> EntryVerification {
    if entry.availability != RuntimeAvailability::Available {
        return failure(format!(
            "FAIL {} disposition=supported availability={} expected=available",
            entry.family_id,
            availability_name(entry.availability)
        ));
    }

    let Some(case) = entry.executable_cases.iter().find(|case| {
        case.case_kind == ExecutableCaseKind::Positive
            && case.expected_outcome == ExpectedOutcome::Success
    }) else {
        return failure(format!(
            "FAIL {} missing positive success case",
            entry.family_id
        ));
    };
    let Some(request) = case.request.as_ref() else {
        return failure(format!(
            "FAIL {} positive success case missing request",
            entry.family_id
        ));
    };
    let request_text = match serde_json::to_string(request) {
        Ok(text) => text,
        Err(error) => return failure(format!("FAIL {} request_json={error}", entry.family_id)),
    };
    let result = match parse_css_construction_json(&request_text).and_then(construct_css) {
        Ok(result) => result,
        Err(error) => return failure(format!("FAIL {} construction={error}", entry.family_id)),
    };

    if let Err(error) =
        verify_css_orthogonality(result.stats.n, &result.checks.h_x, &result.checks.h_z)
    {
        return failure(format!("FAIL {} orthogonality={error}", entry.family_id));
    }

    if let Some(line) = verify_result_metadata(entry, &result) {
        return failure(line);
    }

    EntryVerification::Line(format_pass_line(&entry.family_id, &result))
}

fn verify_result_metadata(
    entry: &FamilyCatalogEntry,
    result: &CssConstructionResult,
) -> Option<String> {
    if result.requested_family_id.map(RequestedFamilyId::as_str) != Some(entry.family_id.as_str()) {
        return Some(format!(
            "FAIL {} expected requested_family_id={} actual requested_family_id={}",
            entry.family_id,
            entry.family_id,
            result
                .requested_family_id
                .map(RequestedFamilyId::as_str)
                .unwrap_or("none")
        ));
    }

    let Some(callable) = entry.callable_constructor.as_ref() else {
        return Some(format!(
            "FAIL {} missing callable_constructor",
            entry.family_id
        ));
    };
    if result.provenance.source != callable.rust_path {
        return Some(format!(
            "FAIL {} expected provenance={} actual provenance={}",
            entry.family_id, callable.rust_path, result.provenance.source
        ));
    }

    let Some(expected) = entry.expected.as_ref() else {
        return Some(format!("FAIL {} missing expected stats", entry.family_id));
    };
    if let Some(line) = stats_mismatch(&entry.family_id, expected, &result.stats) {
        return Some(line);
    }

    let Some(expected_weights) = entry.row_weight_summary.as_ref() else {
        return Some(format!(
            "FAIL {} missing row_weight_summary",
            entry.family_id
        ));
    };
    let actual_h_x = row_weight_summary(&result.checks.h_x);
    if actual_h_x != expected_weights.h_x {
        return Some(format!(
            "FAIL {} expected row_weights_h_x={} actual row_weights_h_x={}",
            entry.family_id,
            format_row_weights(&expected_weights.h_x),
            format_row_weights(&actual_h_x)
        ));
    }
    let actual_h_z = row_weight_summary(&result.checks.h_z);
    if actual_h_z != expected_weights.h_z {
        return Some(format!(
            "FAIL {} expected row_weights_h_z={} actual row_weights_h_z={}",
            entry.family_id,
            format_row_weights(&expected_weights.h_z),
            format_row_weights(&actual_h_z)
        ));
    }

    None
}

fn stats_mismatch(
    family_id: &str,
    expected: &ExpectedStats,
    actual: &CssCodeStats,
) -> Option<String> {
    macro_rules! compare_stat {
        ($field:ident) => {
            if expected.$field != actual.$field {
                return Some(format!(
                    "FAIL {family_id} expected {}={} actual {}={}",
                    stringify!($field),
                    expected.$field,
                    stringify!($field),
                    actual.$field
                ));
            }
        };
    }

    compare_stat!(n);
    compare_stat!(m_x);
    compare_stat!(m_z);
    compare_stat!(rank_x);
    compare_stat!(rank_z);
    compare_stat!(k);
    if expected.d_x != actual.d_x {
        return Some(format!(
            "FAIL {family_id} expected d_x={:?} actual d_x={:?}",
            expected.d_x, actual.d_x
        ));
    }
    if expected.d_z != actual.d_z {
        return Some(format!(
            "FAIL {family_id} expected d_z={:?} actual d_z={:?}",
            expected.d_z, actual.d_z
        ));
    }
    None
}

fn verify_deferred_entry(entry: &FamilyCatalogEntry) -> EntryVerification {
    if entry.availability != RuntimeAvailability::NotApplicable {
        return failure(format!(
            "FAIL {} disposition=deferred availability={} expected=not_applicable",
            entry.family_id,
            availability_name(entry.availability)
        ));
    }
    if entry.research_contracts.len() != 1 {
        return failure(format!(
            "FAIL {} expected exactly one research_contract",
            entry.family_id
        ));
    }
    let Some(boundary) = deferred_family_boundary(&entry.family_id) else {
        return failure(format!("FAIL {} unknown deferred family", entry.family_id));
    };
    if entry.research_contracts[0] != boundary.contract_path {
        return failure(format!(
            "FAIL {} expected contract={} actual contract={}",
            entry.family_id, boundary.contract_path, entry.research_contracts[0]
        ));
    }
    EntryVerification::Line(format!(
        "DEFERRED {} tracking_issue=#{} contract={}",
        entry.family_id, boundary.tracking_issue, boundary.contract_path
    ))
}

fn deferred_family_boundary(family_id: &str) -> Option<DeferredFamilyBoundary> {
    match family_id {
        "hyperbolic_5_5" => Some(DeferredFamilyBoundary {
            tracking_issue: 571,
            contract_path: "qec-code/doc/hyperbolic_5_5_contract.md",
        }),
        "perturbed_hgp" => Some(DeferredFamilyBoundary {
            tracking_issue: 572,
            contract_path: "qec-code/doc/perturbed_hgp_contract.md",
        }),
        _ => None,
    }
}

fn format_pass_line(family_id: &str, result: &CssConstructionResult) -> String {
    let params = serde_json::to_string(&result.normalized_parameters)
        .expect("normalized CSS construction parameters should serialize");
    format!(
        "PASS {family_id} params={params} n={} checks=h_x:{},h_z:{} ranks=rank_x:{},rank_z:{} k={} row_weights=h_x:{},h_z:{} orthogonal=true provenance={}@{}",
        result.stats.n,
        result.stats.m_x,
        result.stats.m_z,
        result.stats.rank_x,
        result.stats.rank_z,
        result.stats.k,
        format_row_weights(&row_weight_summary(&result.checks.h_x)),
        format_row_weights(&row_weight_summary(&result.checks.h_z)),
        result.provenance.source,
        result.provenance.normalized_input_digest,
    )
}

fn row_weight_summary(rows: &[Vec<usize>]) -> Vec<RowWeightBucket> {
    let mut counts = BTreeMap::new();
    for row in rows {
        *counts.entry(row.len()).or_insert(0usize) += 1;
    }
    counts
        .into_iter()
        .map(|(weight, count)| RowWeightBucket { weight, count })
        .collect()
}

fn format_row_weights(buckets: &[RowWeightBucket]) -> String {
    let values = buckets
        .iter()
        .map(|bucket| format!("w{}={}", bucket.weight, bucket.count))
        .collect::<Vec<_>>();
    format!("[{}]", values.join(","))
}

fn availability_name(availability: RuntimeAvailability) -> &'static str {
    match availability {
        RuntimeAvailability::Planned => "planned",
        RuntimeAvailability::Available => "available",
        RuntimeAvailability::NotApplicable => "not_applicable",
    }
}

fn failure(line: String) -> EntryVerification {
    EntryVerification::Failure(line)
}

fn failure_report(line: String, supported: usize, deferred: usize) -> FamilyVerificationReport {
    FamilyVerificationReport {
        output: format!("{line}\nSUMMARY FAIL supported={supported} deferred={deferred} failed=1"),
        failed: 1,
    }
}