qleisli 0.2.2

Experimental quantum language with linear ownership, exact contracts and independent finite IR verification
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Bounded, exact semantic evidence for finite pure circuit implementations.
//!
//! Checked values have private fields. Their constructors validate the
//! operator equation or derive it using a qualified composition rule. They
//! describe encoded inputs; possession of a theorem is not ownership of, or
//! preparation evidence for, a quantum state. Raw IR always rechecks evidence.

pub mod exact;
pub mod function;
pub mod meaning;
pub use function::{FunctionEvidence, FunctionIdentity};

use std::fmt;

use crate::ir::{BitControl, CircuitAction, CircuitStep};
use exact::{Budget, Exact, ExactError, Matrix};

pub const MAX_CONTRACT_BITS: usize = 6;
pub const MAX_CONTRACT_STEPS: usize = 1024;
pub const DEFAULT_EXACT_WORK: usize = 10_000_000;

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ContractError {
    Limit(&'static str),
    Type(&'static str),
    InvalidCircuit(String),
    NotIsometric,
    EquationMismatch,
    EvidenceMismatch,
    Arithmetic(ExactError),
}

impl fmt::Display for ContractError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Limit(message) | Self::Type(message) => f.write_str(message),
            Self::InvalidCircuit(message) => write!(f, "invalid circuit: {message}"),
            Self::NotIsometric => f.write_str("encoding or logical operator is not an isometry"),
            Self::EquationMismatch => f.write_str("exact equation U E_in = E_out u does not hold"),
            Self::EvidenceMismatch => {
                f.write_str("evidence does not match the circuit, contract, or entry encoding")
            }
            Self::Arithmetic(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for ContractError {}

impl ContractError {
    pub(crate) fn is_capacity(&self) -> bool {
        matches!(
            self,
            Self::Limit(_)
                | Self::Arithmetic(
                    ExactError::WorkLimit
                        | ExactError::ArithmeticCapacity
                        | ExactError::Dimension { .. }
                )
        )
    }
}

impl From<ExactError> for ContractError {
    fn from(error: ExactError) -> Self {
        Self::Arithmetic(error)
    }
}

/// Internal diagnostic detail; the public error variants remain unchanged.
#[derive(Debug)]
pub(crate) struct ContractDiagnostic {
    pub(crate) error: ContractError,
    detail: Option<String>,
}

impl From<ContractError> for ContractDiagnostic {
    fn from(error: ContractError) -> Self {
        Self {
            error,
            detail: None,
        }
    }
}

impl From<ExactError> for ContractDiagnostic {
    fn from(error: ExactError) -> Self {
        ContractError::Arithmetic(error).into()
    }
}

impl fmt::Display for ContractDiagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.error)?;
        if let Some(detail) = &self.detail {
            write!(f, "; {detail}")?;
        }
        Ok(())
    }
}

fn check_equation(actual: &Matrix, expected: &Matrix) -> Result<(), ContractDiagnostic> {
    if actual.rows() != expected.rows() || actual.cols() != expected.cols() {
        return Err(ContractError::EquationMismatch.into());
    }
    // Retain a counterexample from the matrices already computed under the
    // caller's budget. The first column is a logical input basis state.
    for column in 0..actual.cols() {
        for row in 0..actual.rows() {
            let index = row * actual.cols() + column;
            let actual = actual.entries()[index];
            let expected = expected.entries()[index];
            if actual != expected {
                return Err(ContractDiagnostic {
                    error: ContractError::EquationMismatch,
                    detail: Some(format!(
                        "input column {column}, output row {row} (zero-based): actual {}, expected {}",
                        actual.diagnostic(),
                        expected.diagnostic()
                    )),
                });
            }
        }
    }
    Ok(())
}

/// The exact basis tree of one owned quantum register, including Unit nodes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BasisType {
    Unit,
    Bit,
    Pair(Box<BasisType>, Box<BasisType>),
    /// An arity-preserving product of at least three immediate fields.
    Tuple(Vec<BasisType>),
}

// A rejected public tree can be much deeper than our accepted type profile.
// Rejection must not recurse again while destroying that untrusted input.
impl Drop for BasisType {
    fn drop(&mut self) {
        let mut pending = Vec::new();
        if let Self::Pair(a, b) = self {
            pending.push(std::mem::replace(a.as_mut(), Self::Unit));
            pending.push(std::mem::replace(b.as_mut(), Self::Unit));
        }
        if let Self::Tuple(fields) = self {
            pending.append(fields);
        }
        while let Some(mut node) = pending.pop() {
            if let Self::Pair(a, b) = &mut node {
                pending.push(std::mem::replace(a.as_mut(), Self::Unit));
                pending.push(std::mem::replace(b.as_mut(), Self::Unit));
            }
            if let Self::Tuple(fields) = &mut node {
                pending.append(fields);
            }
            // The children now are leaves, so this node's drop is bounded.
        }
    }
}

impl BasisType {
    pub fn pair(left: Self, right: Self) -> Self {
        Self::Pair(Box::new(left), Box::new(right))
    }

    /// Validate type-tree capacity before any recursive transformation.
    pub fn bits(&self) -> Result<usize, ContractError> {
        let mut pending = vec![(self, 0)];
        let mut nodes = 0;
        let mut bits = 0;
        while let Some((ty, depth)) = pending.pop() {
            nodes += 1;
            if nodes > 128 || depth > 32 {
                return Err(ContractError::Limit(
                    "contract type exceeds 128 nodes or depth 32",
                ));
            }
            match ty {
                Self::Unit => (),
                Self::Bit => bits += 1,
                Self::Pair(a, b) => {
                    pending.extend([(a.as_ref(), depth + 1), (b.as_ref(), depth + 1)])
                }
                Self::Tuple(fields) => {
                    if fields.len() < 3 {
                        return Err(ContractError::Type(
                            "tuple type requires at least three fields",
                        ));
                    }
                    if fields.len() > 128 {
                        return Err(ContractError::Limit(
                            "contract tuple exceeds type-node limit",
                        ));
                    }
                    pending.extend(fields.iter().map(|field| (field, depth + 1)));
                }
            }
        }
        if bits > MAX_CONTRACT_BITS {
            return Err(ContractError::Limit(
                "exact contracts support at most 6 physical/logical bits",
            ));
        }
        Ok(bits)
    }

    fn register(bits: usize) -> Result<Self, ContractError> {
        if bits > MAX_CONTRACT_BITS {
            return Err(ContractError::Limit(
                "exact contracts support at most 6 bits",
            ));
        }
        Ok((0..bits)
            .fold(None, |tree, _| {
                Some(match tree {
                    None => Self::Bit,
                    Some(tree) => Self::pair(tree, Self::Bit),
                })
            })
            .unwrap_or(Self::Unit))
    }
}

/// A checked flat circuit. Its basis fixes tensor order and type identity.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Circuit {
    basis: BasisType,
    steps: Vec<CircuitStep>,
}

impl Circuit {
    pub fn new(basis: BasisType, steps: Vec<CircuitStep>) -> Result<Self, ContractError> {
        Self::validate(&basis, &steps)?;
        Ok(Self { basis, steps })
    }

    fn validate(basis: &BasisType, steps: &[CircuitStep]) -> Result<(), ContractError> {
        let bits = basis.bits()?;
        if steps.len() > MAX_CONTRACT_STEPS {
            return Err(ContractError::Limit("contract circuit exceeds 1024 steps"));
        }
        // Bound untrusted vectors before traversing their contents.
        for step in steps {
            if step.controls.len() > bits {
                return Err(ContractError::Limit("too many circuit controls"));
            }
            if let CircuitAction::Contract { indices, .. } = &step.action {
                if indices.len() > bits {
                    return Err(ContractError::Limit("too many contract axes"));
                }
            }
            if let CircuitAction::Monomial {
                indices,
                permutation,
                phases,
            } = &step.action
            {
                if indices.len() > bits
                    || permutation.len() > (1 << bits)
                    || phases.len() > (1 << bits)
                {
                    return Err(ContractError::Limit(
                        "contract circuit table exceeds its register",
                    ));
                }
            }
        }
        crate::verify::check_circuit(steps, bits, &[])
            .map_err(|e| ContractError::InvalidCircuit(e.message))?;
        Ok(())
    }

    pub fn basis(&self) -> &BasisType {
        &self.basis
    }
    pub fn steps(&self) -> &[CircuitStep] {
        &self.steps
    }

    /// Direct exact column evaluation, independent of the frontend and simulator.
    pub fn matrix(&self, budget: &mut Budget) -> Result<Matrix, ContractError> {
        let dimension = 1usize << self.basis.bits()?;
        for step in &self.steps {
            let cost = match &step.action {
                CircuitAction::Contract { evidence, .. } => 3 * evidence.meaning().rows(),
                _ => 6,
            };
            budget.charge(dimension * dimension * cost)?;
        }
        let mut matrix = vec![Exact::zero(); dimension * dimension];
        for column in 0..dimension {
            let mut values = vec![Exact::zero(); dimension];
            values[column] = Exact::one();
            for step in &self.steps {
                let mut next = vec![Exact::zero(); dimension];
                for (label, value) in values.iter().copied().enumerate() {
                    if value == Exact::zero() {
                        continue;
                    }
                    let enabled = step
                        .controls
                        .iter()
                        .all(|c| ((label >> c.index) & 1 != 0) == c.when_one);
                    if !enabled {
                        next[label] = next[label].add(value)?;
                        continue;
                    }
                    match &step.action {
                        CircuitAction::Contract {
                            indices,
                            evidence,
                            adjoint,
                        } => {
                            let input =
                                indices.iter().enumerate().fold(0usize, |n, (place, axis)| {
                                    n | (((label >> axis) & 1) << place)
                                });
                            let meaning = evidence.meaning();
                            let local_dim = meaning.rows();
                            for output in 0..local_dim {
                                let entry = if *adjoint {
                                    meaning.entries()[input * local_dim + output].conjugate()?
                                } else {
                                    meaning.entries()[output * local_dim + input]
                                };
                                if entry == Exact::zero() {
                                    continue;
                                }
                                let mut target = label;
                                for (place, axis) in indices.iter().enumerate() {
                                    target =
                                        (target & !(1 << axis)) | (((output >> place) & 1) << axis);
                                }
                                next[target] = next[target].add(value.mul(entry)?)?;
                            }
                        }
                        CircuitAction::Hadamard { target } => {
                            let low = label & !(1 << target);
                            let high = low | (1 << target);
                            let scaled = value.mul(Exact::inv_sqrt2())?;
                            next[low] = next[low].add(scaled)?;
                            let signed = if label == high { scaled.neg()? } else { scaled };
                            next[high] = next[high].add(signed)?;
                        }
                        CircuitAction::Monomial {
                            indices,
                            permutation,
                            phases,
                        } => {
                            let input =
                                indices.iter().enumerate().fold(0usize, |n, (place, axis)| {
                                    n | (((label >> axis) & 1) << place)
                                });
                            let output = usize::from(permutation[input]);
                            let mut target = label;
                            for (place, axis) in indices.iter().enumerate() {
                                target =
                                    (target & !(1 << axis)) | (((output >> place) & 1) << axis);
                            }
                            next[target] = next[target]
                                .add(value.mul(Exact::phase(i32::from(phases[input])))?)?;
                        }
                    }
                }
                values = next;
            }
            for (row, value) in values.into_iter().enumerate() {
                matrix[row * dimension + column] = value;
            }
        }
        Ok(Matrix::new(dimension, dimension, matrix)?)
    }
}

/// A checked isometric map with fixed logical coordinates and physical layout.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Encoding {
    logical: BasisType,
    physical: BasisType,
    map: Matrix,
}

impl Encoding {
    pub fn new(
        logical: BasisType,
        physical: BasisType,
        map: Matrix,
        budget: &mut Budget,
    ) -> Result<Self, ContractError> {
        if map.cols() != 1usize << logical.bits()? || map.rows() != 1usize << physical.bits()? {
            return Err(ContractError::Type(
                "encoding dimensions do not match its exact types",
            ));
        }
        if !map.is_isometry(budget)? {
            return Err(ContractError::NotIsometric);
        }
        Ok(Self {
            logical,
            physical,
            map,
        })
    }

    pub fn identity(basis: BasisType) -> Result<Self, ContractError> {
        let map = Matrix::identity(1usize << basis.bits()?)?;
        Ok(Self {
            logical: basis.clone(),
            physical: basis,
            map,
        })
    }

    pub fn logical(&self) -> &BasisType {
        &self.logical
    }
    pub fn physical(&self) -> &BasisType {
        &self.physical
    }
    pub fn map(&self) -> &Matrix {
        &self.map
    }
}

/// An independently specified meaning. Equality includes encodings and phase.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Contract {
    input: Encoding,
    output: Encoding,
    logical: Matrix,
}

impl Contract {
    pub fn new(
        input: Encoding,
        output: Encoding,
        logical: Matrix,
        budget: &mut Budget,
    ) -> Result<Self, ContractError> {
        if logical.cols() != input.map.cols() || logical.rows() != output.map.cols() {
            return Err(ContractError::Type(
                "logical operator does not match the encoding domains",
            ));
        }
        if !logical.is_isometry(budget)? {
            return Err(ContractError::NotIsometric);
        }
        Ok(Self {
            input,
            output,
            logical,
        })
    }
    pub fn input(&self) -> &Encoding {
        &self.input
    }
    pub fn output(&self) -> &Encoding {
        &self.output
    }
    pub fn logical(&self) -> &Matrix {
        &self.logical
    }
}

/// Immutable evidence bound to the complete circuit and contract, not a name.
#[derive(Clone, Debug)]
pub struct CheckedContract {
    circuit: Circuit,
    contract: Contract,
}

impl CheckedContract {
    pub fn circuit(&self) -> &Circuit {
        &self.circuit
    }
    pub fn contract(&self) -> &Contract {
        &self.contract
    }

    /// Exact matrix leaf: all input columns and physical output rows are checked.
    pub fn check(
        circuit: Circuit,
        contract: Contract,
        budget: &mut Budget,
    ) -> Result<Self, ContractError> {
        Self::check_diagnostic(circuit, contract, budget).map_err(|diagnostic| diagnostic.error)
    }

    pub(crate) fn check_diagnostic(
        circuit: Circuit,
        contract: Contract,
        budget: &mut Budget,
    ) -> Result<Self, ContractDiagnostic> {
        if circuit.basis != contract.input.physical || circuit.basis != contract.output.physical {
            return Err(
                ContractError::Type("circuit type does not match the physical encodings").into(),
            );
        }
        let lhs = circuit
            .matrix(budget)?
            .compose(&contract.input.map, budget)?;
        let rhs = contract.output.map.compose(&contract.logical, budget)?;
        check_equation(&lhs, &rhs)?;
        Ok(Self { circuit, contract })
    }

    /// Identity primitive; no simulation is needed for this known equality.
    pub fn identity(encoding: Encoding) -> Result<Self, ContractError> {
        Ok(Self {
            circuit: Circuit::new(encoding.physical.clone(), vec![])?,
            contract: Contract {
                logical: Matrix::identity(encoding.map.cols())?,
                input: encoding.clone(),
                output: encoding,
            },
        })
    }

    pub fn check_binding(
        &self,
        circuit: &Circuit,
        contract: &Contract,
    ) -> Result<(), ContractError> {
        if &self.circuit != circuit || &self.contract != contract {
            return Err(ContractError::EvidenceMismatch);
        }
        Ok(())
    }

    /// A caller must establish this exact encoding, not merely its image.
    /// This checks theorem compatibility; runtime ownership is checked by IR.
    pub fn check_entry(&self, entry: Option<&Encoding>) -> Result<&Encoding, ContractError> {
        if entry != Some(&self.contract.input) {
            return Err(ContractError::EvidenceMismatch);
        }
        Ok(&self.contract.output)
    }

    /// Derive next ∘ self without re-evaluating either physical circuit.
    pub fn then(&self, next: &Self, budget: &mut Budget) -> Result<Self, ContractError> {
        // Checked constructors bind both physical interfaces to the circuit's
        // exact basis tree. Matching middle encodings therefore also fixes the
        // basis on which the concatenated steps operate.
        for evidence in [self, next] {
            debug_assert_eq!(evidence.circuit.basis, evidence.contract.input.physical);
            debug_assert_eq!(evidence.circuit.basis, evidence.contract.output.physical);
        }
        if self.contract.output != next.contract.input {
            return Err(ContractError::Type(
                "sequential contracts require exactly matching middle encoding",
            ));
        }
        let steps = self
            .circuit
            .steps
            .iter()
            .chain(&next.circuit.steps)
            .cloned()
            .collect();
        Ok(Self {
            circuit: Circuit::new(self.circuit.basis.clone(), steps)?,
            contract: Contract {
                input: self.contract.input.clone(),
                output: next.contract.output.clone(),
                logical: next
                    .contract
                    .logical
                    .compose(&self.contract.logical, budget)?,
            },
        })
    }

    /// First operand occupies the low tensor axes. This does not assert separability.
    pub fn tensor(&self, other: &Self, budget: &mut Budget) -> Result<Self, ContractError> {
        let physical = BasisType::pair(self.circuit.basis.clone(), other.circuit.basis.clone());
        physical.bits()?;
        let mut steps = self.circuit.steps.clone();
        steps.extend(remapped(&other.circuit.steps, self.circuit.basis.bits()?));
        let encoding =
            |a: &Encoding, b: &Encoding, budget: &mut Budget| -> Result<Encoding, ContractError> {
                let logical = BasisType::pair(a.logical.clone(), b.logical.clone());
                logical.bits()?;
                Ok(Encoding {
                    logical,
                    physical: physical.clone(),
                    map: a.map.tensor(&b.map, budget)?,
                })
            };
        Ok(Self {
            circuit: Circuit::new(physical.clone(), steps)?,
            contract: Contract {
                input: encoding(&self.contract.input, &other.contract.input, budget)?,
                output: encoding(&self.contract.output, &other.contract.output, budget)?,
                logical: self
                    .contract
                    .logical
                    .tensor(&other.contract.logical, budget)?,
            },
        })
    }

    /// The physical circuit is unitary by construction. The logical map must
    /// also be square (it is already checked isometric) before reversing E.
    pub fn adjoint(&self, budget: &mut Budget) -> Result<Self, ContractError> {
        if self.contract.logical.rows() != self.contract.logical.cols() {
            return Err(ContractError::Type(
                "adjoint contract requires logical unitarity",
            ));
        }
        let mut steps = self.circuit.steps.clone();
        invert_steps(&mut steps);
        Ok(Self {
            circuit: Circuit::new(self.circuit.basis.clone(), steps)?,
            contract: Contract {
                input: self.contract.output.clone(),
                output: self.contract.input.clone(),
                logical: self.contract.logical.adjoint(budget)?,
            },
        })
    }

    /// Construct control of a known circuit, with identical input/output E.
    /// This is not an ability to control an unknown external device.
    pub fn controlled(&self, budget: &mut Budget) -> Result<Self, ContractError> {
        if self.contract.input != self.contract.output {
            return Err(ContractError::Type(
                "controlled contract requires identical input and output encodings",
            ));
        }
        let physical = BasisType::pair(BasisType::Bit, self.circuit.basis.clone());
        let logical_type = BasisType::pair(BasisType::Bit, self.contract.input.logical.clone());
        physical.bits()?;
        logical_type.bits()?;
        let mut steps = remapped(&self.circuit.steps, 1);
        for step in &mut steps {
            step.controls.push(BitControl {
                index: 0,
                when_one: true,
            });
        }
        let identity = Matrix::identity(2)?;
        let encoding = Encoding {
            logical: logical_type,
            physical: physical.clone(),
            map: identity.tensor(&self.contract.input.map, budget)?,
        };
        let old_dim = self.contract.logical.cols();
        let dimension = old_dim * 2;
        budget.charge(dimension * dimension)?;
        let mut entries = vec![Exact::zero(); dimension * dimension];
        for row in 0..old_dim {
            entries[(2 * row) * dimension + 2 * row] = Exact::one();
            for col in 0..old_dim {
                entries[(2 * row + 1) * dimension + 2 * col + 1] =
                    self.contract.logical.entries()[row * old_dim + col];
            }
        }
        Ok(Self {
            circuit: Circuit::new(physical, steps)?,
            contract: Contract {
                input: encoding.clone(),
                output: encoding,
                logical: Matrix::new(dimension, dimension, entries)?,
            },
        })
    }
}

fn remapped(steps: &[CircuitStep], offset: usize) -> Vec<CircuitStep> {
    steps
        .iter()
        .cloned()
        .map(|mut step| {
            for control in &mut step.controls {
                control.index += offset;
            }
            match &mut step.action {
                CircuitAction::Hadamard { target } => *target += offset,
                CircuitAction::Monomial { indices, .. }
                | CircuitAction::Contract { indices, .. } => {
                    for index in indices {
                        *index += offset;
                    }
                }
            }
            step
        })
        .collect()
}

/// Recheck the evidence carried by a raw certified compute/use/uncompute scope.
/// This IR-level boundary knows widths; the source checker additionally checks
/// exact source type trees and the two body ownerships, including `Q<Unit>`.
pub fn check_computed(
    source_bits: usize,
    function: &[u16],
    use_steps: &[CircuitStep],
    logical_steps: &[CircuitStep],
) -> Result<(), ContractError> {
    let mut budget = Budget::new(DEFAULT_EXACT_WORK);
    check_computed_with_budget(source_bits, function, use_steps, logical_steps, &mut budget)
}

pub(crate) fn check_computed_with_budget(
    source_bits: usize,
    function: &[u16],
    use_steps: &[CircuitStep],
    logical_steps: &[CircuitStep],
    budget: &mut Budget,
) -> Result<(), ContractError> {
    check_computed_diagnostic_with_budget(source_bits, function, use_steps, logical_steps, budget)
        .map_err(|diagnostic| diagnostic.error)
}

pub(crate) fn check_computed_diagnostic_with_budget(
    source_bits: usize,
    function: &[u16],
    use_steps: &[CircuitStep],
    logical_steps: &[CircuitStep],
    budget: &mut Budget,
) -> Result<(), ContractDiagnostic> {
    let available = budget.remaining().min(DEFAULT_EXACT_WORK);
    let mut local = Budget::new(available);
    let result = check_computed_inner(source_bits, function, use_steps, logical_steps, &mut local);
    budget.charge(available - local.remaining())?;
    result
}

fn check_computed_inner(
    source_bits: usize,
    function: &[u16],
    use_steps: &[CircuitStep],
    logical_steps: &[CircuitStep],
    budget: &mut Budget,
) -> Result<(), ContractDiagnostic> {
    if source_bits >= MAX_CONTRACT_BITS {
        return Err(ContractError::Limit(
            "certified computation supports at most 5 data bits plus one auxiliary",
        )
        .into());
    }
    let dim = 1usize << source_bits;
    if function.len() != dim || function.iter().any(|x| *x > 1) {
        return Err(
            ContractError::Type("computed predicate must be a total Bit-valued table").into(),
        );
    }
    // Validate capacities before cloning untrusted circuit vectors.
    if use_steps.len() > MAX_CONTRACT_STEPS || logical_steps.len() > MAX_CONTRACT_STEPS {
        return Err(ContractError::Limit("contract circuit exceeds 1024 steps").into());
    }
    let data = BasisType::register(source_bits)?;
    let physical = BasisType::pair(data.clone(), BasisType::Bit);
    Circuit::validate(&physical, use_steps)?;
    Circuit::validate(&data, logical_steps)?;
    let implementation = Circuit::new(physical.clone(), use_steps.to_vec())?;
    let logical = Circuit::new(data.clone(), logical_steps.to_vec())?;
    let mut entries = vec![Exact::zero(); 2 * dim * dim];
    for (x, fx) in function.iter().copied().enumerate() {
        entries[(x + usize::from(fx) * dim) * dim + x] = Exact::one();
    }
    let encoding = Encoding::new(data, physical, Matrix::new(2 * dim, dim, entries)?, budget)?;
    let meaning = logical.matrix(budget)?;
    let contract = Contract::new(encoding.clone(), encoding, meaning, budget)?;
    CheckedContract::check_diagnostic(implementation, contract, budget)?;
    Ok(())
}

/// Reverse a checked circuit without losing phase or nested evidence.
pub(crate) fn invert_steps(steps: &mut [CircuitStep]) {
    steps.reverse();
    for step in steps {
        match &mut step.action {
            CircuitAction::Contract { adjoint, .. } => *adjoint = !*adjoint,
            CircuitAction::Hadamard { .. } => (),
            CircuitAction::Monomial {
                permutation,
                phases,
                ..
            } => {
                let mut inverse = vec![0; permutation.len()];
                let mut inverse_phases = vec![0; phases.len()];
                for (x, y) in permutation.iter().copied().enumerate() {
                    inverse[usize::from(y)] = x as u16;
                    inverse_phases[usize::from(y)] = (8 - phases[x]) % 8;
                }
                *permutation = inverse;
                *phases = inverse_phases;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counterexample_diagnostic_preserves_the_shared_work_budget() {
        let use_steps = [CircuitStep {
            controls: vec![],
            action: CircuitAction::Hadamard { target: 1 },
        }];
        let mut public_budget = Budget::new(DEFAULT_EXACT_WORK);
        let mut diagnostic_budget = Budget::new(DEFAULT_EXACT_WORK);
        let error = check_computed_with_budget(1, &[0, 1], &use_steps, &[], &mut public_budget)
            .unwrap_err();
        let diagnostic = check_computed_diagnostic_with_budget(
            1,
            &[0, 1],
            &use_steps,
            &[],
            &mut diagnostic_budget,
        )
        .unwrap_err();
        assert_eq!(error, ContractError::EquationMismatch);
        assert_eq!(diagnostic.error, error);
        assert_eq!(public_budget.remaining(), diagnostic_budget.remaining());
        assert!(
            diagnostic
                .to_string()
                .contains("input column 0, output row 0")
        );

        let mut exhausted = Budget::new(0);
        let diagnostic =
            check_computed_diagnostic_with_budget(1, &[0, 1], &use_steps, &[], &mut exhausted)
                .unwrap_err();
        assert_eq!(
            diagnostic.error,
            ContractError::Arithmetic(ExactError::WorkLimit)
        );
        assert!(diagnostic.detail.is_none());
        assert_eq!(exhausted.remaining(), 0);
    }
}