inspiring 0.1.0-rc.3

InspiRING.Pack: a single-primitive ring-packing crate (eprint 2025/1352, Algorithm 1) on top of spiral-rs.
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
//! Key-switching primitives `KS.Setup` and `KS.Switch`, plus helpers to
//! compute automorphic images `τ_g^{k-1}(K_g)` of a base matrix locally
//! (without extra key material). See SPEC.md §6 (Stage 3) and §9.b
//! (the structural reason InspiRING needs only two base KS matrices vs.
//! CDKS's `lg d`).
//!
//! The implementation patterns `KS.Switch` on the inline KS body of
//! `spiral_rs::server::coefficient_expansion` (lines 80–103 of
//! `spiral-rs/src/server.rs` at the pinned revision); we cannot call
//! `coefficient_expansion` directly because it is fused with
//! Spiral-PIR's expansion loop. See `docs/spiral-rs-mapping.md` §3.

use rand_chacha::ChaCha20Rng;
use spiral_rs::gadget::build_gadget;
use spiral_rs::poly::{
    add_into, from_ntt_alloc, multiply, scalar_multiply_alloc, stack_ntt, to_ntt_alloc, PolyMatrix,
    PolyMatrixNTT, PolyMatrixRaw,
};

use crate::automorph::{apply_tau_ntt_alloc, tau_ntt, NttAutomorphTable};
use crate::params::RlweParams;

/// A single key-switching matrix `K`. Internally a `[2, ℓ]` `PolyMatrixNTT`
/// (the row-2-by-cols-ℓ shape used by spiral-rs's gadget machinery).
///
/// `K = KS.Setup(s', s)` lets one transform a ciphertext under `s'`
/// (one of `τ_g(s̃)`, `τ_h(s̃)`, …) into one under `s = s̃`. SPEC.md §6.
///
/// `params` is bundled directly so [`ks_switch`] (and the cascade in
/// [`crate::collapse`]) does not need to be threaded a second `&RlweParams`
/// reference at every call site, *and* so a key matrix can never be paired
/// with mismatched gadget settings: callers literally cannot construct a
/// well-typed `(K, params)` pair where `K` was built under a different
/// gadget. Both `params.spiral` (the inner allocator the matrix borrows
/// from) and `params.gadget.ell` (the gadget width the matrix was built
/// for) come from the same `params` reference here, by construction.
///
/// Note: `Debug` / `Clone` are not derived because [`PolyMatrixNTT`] does
/// not implement them upstream; Phase 7 adds hand-written impls if needed.
pub struct KeySwitchingMatrix<'a> {
    /// The encrypted gadget-scaled secret. Shape `[2, ℓ]`.
    pub mat: PolyMatrixNTT<'a>,
    /// The RLWE parameter set this matrix was built against. Tied to the
    /// same `'a` lifetime as the inner spiral-rs allocator referenced by
    /// `mat`, so the borrow checker enforces consistency for free.
    pub params: &'a RlweParams,
}

/// `KS.Setup(s_from → s_to)` — encrypt the gadget-scaled `s_from` under
/// `s_to`, producing a key-switching matrix, per SPEC.md §6 / paper §2.
///
/// Concretely the returned matrix is a stacked `[2 × ℓ]` `PolyMatrixNTT`
///
/// ```text
/// K = [   −a    ]
///     [ s · a + e + s_from · g_z ]
/// ```
///
/// where `a ← R_q^ℓ` is uniformly random, `e ← χ^ℓ` is a discrete-Gaussian
/// noise vector of width `σ_χ · √(2π)` (the paper's centred convention), and
/// `g_z = [1, z, z^2, …, z^{ℓ-1}]` is the spiral-rs gadget vector. With this
/// matrix, [`ks_switch`] takes a ciphertext under `s_from` to one under
/// `s_to` (= `s` here) at a noise budget controlled by `σ_χ` and `ℓ`
/// (Theorem 2 in the paper, SPEC.md §7).
///
/// The function is **offline-only**: it samples fresh randomness from `rng`
/// and is never called on the online `pack` path. Callers should derive
/// `s_from_ntt` and `s_to_ntt` from the same `params.spiral` allocator that
/// is used everywhere else, so memory layouts match.
///
pub fn ks_setup<'a>(
    params: &'a RlweParams,
    s_from_ntt: &PolyMatrixNTT<'a>,
    s_to_ntt: &PolyMatrixNTT<'a>,
    rng: &mut ChaCha20Rng,
) -> KeySwitchingMatrix<'a> {
    // CT-sensitive: setup consumes secret-key polynomials (`s_from_ntt` and
    // `s_to_ntt`). It is offline key-generation code, not the online packing
    // path, and it does not branch on secret coefficients directly.
    assert_eq!(s_from_ntt.rows, 1);
    assert_eq!(s_from_ntt.cols, 1);
    assert_eq!(s_to_ntt.rows, 1);
    assert_eq!(s_to_ntt.cols, 1);

    let spiral = &params.spiral;
    let ell = params.gadget.ell;

    let gadget = build_gadget(spiral, 1, ell);
    let scaled = scalar_multiply_alloc(s_from_ntt, &to_ntt_alloc(&gadget));

    let dg = crate::gaussian::discrete_gaussian(params.sigma_chi);
    let a = PolyMatrixRaw::random_rng(spiral, 1, ell, rng);
    let e = PolyMatrixRaw::noise(spiral, 1, ell, &dg, rng);
    let a_ntt = to_ntt_alloc(&a);
    let w = (-&a).ntt();
    let mut y = PolyMatrixNTT::zero(spiral, 1, ell);
    multiply(&mut y, s_to_ntt, &a_ntt);
    add_into(&mut y, &to_ntt_alloc(&e));
    add_into(&mut y, &scaled);

    KeySwitchingMatrix {
        mat: stack_ntt(&w, &y),
        params,
    }
}

/// `KS.Switch(K, (c1, c2)) → (c1', c2')` — apply a key-switching matrix
/// to an RLWE pair, returning a new pair under `s_to`. SPEC.md §6.
///
/// The gadget shape comes from `k.params` (the `RlweParams` that `K` was
/// built against — see [`KeySwitchingMatrix`] — which makes it impossible
/// to call this with a `K` and an unrelated `params`). The function asserts
/// `K.mat` has the matching `[2 × ℓ]` layout. The body mirrors the inline
/// KS sequence in `spiral-rs/src/server.rs` lines 80–103 (which is fused
/// into Spiral-PIR's coefficient-expansion loop and therefore not reusable
/// directly):
///
/// 1. Round-trip `c1` to coefficient form and gadget-decompose it into `ℓ`
///    base-`z` digit polynomials. The choice of width here MUST match
///    `RlweParams::gadget.ell` so the digit decomposition is the inverse of
///    the `g_z` factor encoded into `K.mat` by [`ks_setup`]. We pass `ℓ`
///    explicitly via `k.params.gadget.ell` instead of reading
///    `K.mat.cols` so a malformed key matrix is caught by the assertion
///    below rather than silently miscomputing.
/// 2. NTT-forward the digits and multiply by `K.mat`. The result is a
///    `[2 × 1]` `PolyMatrixNTT` whose top half is the new `c1'` and whose
///    bottom half is `K.bottom · digits = s_to · c1' + e + s_from · c1`,
///    i.e. `c1' = -K.top · digits` and `c2' (before adding original c2) =
///    s_from · c1 + (small noise)`.
/// 3. Add the original `c2` into the bottom half. The output decrypts under
///    `s_to` to the same plaintext as the input did under `s_from`.
///
/// **Test-only instrumentation**: in `cfg(test)` builds a thread-local
/// counter is incremented on every call. `tests/inspiring_vs_cdks_recursion.rs`
/// asserts preprocessing evaluates exactly `d − 1` logical switches and that
/// online [`crate::pack::pack`] evaluates zero key-switch products.
///
pub fn ks_switch<'a>(
    k: &KeySwitchingMatrix<'a>,
    c1: &PolyMatrixNTT<'a>,
    c2: &PolyMatrixNTT<'a>,
) -> (PolyMatrixNTT<'a>, PolyMatrixNTT<'a>) {
    let params = k.params;
    assert_eq!(k.mat.rows, 2, "KS matrix must have 2 rows ([w; y])");
    assert_eq!(
        k.mat.cols, params.gadget.ell,
        "KS matrix width must match the gadget length ℓ",
    );
    assert_eq!(c1.rows, 1);
    assert_eq!(c1.cols, 1);
    assert_eq!(c2.rows, 1);
    assert_eq!(c2.cols, 1);

    // The gadget width passed here MUST match the `build_gadget(_, 1, ℓ)`
    // call in `ks_setup`. Anything else makes the digit decomposition
    // non-inverse to the `g_z` factor encoded in `K.mat`, breaking the KS
    // identity. `params.gadget.ell` is the validated source-of-truth (see
    // `RlweParams::new`), which is why `KeySwitchingMatrix` carries its own
    // `params` reference rather than letting us infer the width from
    // `K.mat.cols`.
    let digits_ntt = ks_digits_ntt_from_c1(params, c1);
    ks_switch_with_digits_ntt(k, &digits_ntt, c2)
}

/// Precompute the NTT-form gadget digits used by [`ks_switch`] for `c1`.
///
/// This is the preprocessable part of a switch when the `c1` cascade is
/// fixed by the CRS. It remains useful for direct `collapse_with_digits`
/// callers, while the main online pack path now consumes the fully
/// precomputed affine collapse form.
pub(crate) fn ks_digits_ntt_from_c1<'a>(
    params: &'a RlweParams,
    c1: &PolyMatrixNTT<'a>,
) -> PolyMatrixNTT<'a> {
    assert_eq!(c1.rows, 1);
    assert_eq!(c1.cols, 1);

    let digits_raw = signed_gadget_invert_alloc(params, &from_ntt_alloc(c1));
    to_ntt_alloc(&digits_raw)
}

/// Apply a key switch using precomputed NTT-form gadget digits for `c1`.
pub(crate) fn ks_switch_with_digits_ntt<'a>(
    k: &KeySwitchingMatrix<'a>,
    digits_ntt: &PolyMatrixNTT<'a>,
    c2: &PolyMatrixNTT<'a>,
) -> (PolyMatrixNTT<'a>, PolyMatrixNTT<'a>) {
    ks_call_count::inc();

    let params = k.params;
    assert_eq!(k.mat.rows, 2, "KS matrix must have 2 rows ([w; y])");
    assert_eq!(
        k.mat.cols, params.gadget.ell,
        "KS matrix width must match the gadget length ℓ",
    );
    assert_eq!(digits_ntt.rows, params.gadget.ell);
    assert_eq!(digits_ntt.cols, 1);
    assert_eq!(c2.rows, 1);
    assert_eq!(c2.cols, 1);

    let mut switched = PolyMatrixNTT::zero(&params.spiral, 2, 1);
    multiply(&mut switched, &k.mat, digits_ntt);

    let delta_a = switched.submatrix(0, 0, 1, 1);
    let mut delta_b = switched.submatrix(1, 0, 1, 1);
    add_into(&mut delta_b, c2);
    (delta_a, delta_b)
}

fn signed_gadget_invert_alloc<'a>(
    params: &'a RlweParams,
    input: &PolyMatrixRaw<'a>,
) -> PolyMatrixRaw<'a> {
    assert_eq!(input.rows, 1);
    assert_eq!(input.cols, 1);

    let mut out = PolyMatrixRaw::zero(&params.spiral, params.gadget.ell, 1);
    let z = params.gadget.z();
    let half = z / 2;
    // `z` is `2^bits_per` by construction (`RlweParams::new` validates it
    // against spiral's gadget width), so the digit extraction is a mask and a
    // shift. The compiler cannot prove that on its own because `z` is a runtime
    // value, and this loop runs `d * ell` times per key switch and `d - 1` key
    // switches per CRS block — 12.6 M iterations at the production set, each of
    // which was paying three hardware divisions plus an `i128` `rem_euclid`.
    let shift = params.gadget.bits_per;
    let mask = z - 1;
    assert!(
        half <= params.q,
        "signed digits must be representable modulo q"
    );
    // Balance the low ell-1 digits, then retain the entire remaining quotient
    // as the top digit. The quotient is at most z (a carry can propagate
    // through every lower digit), so the gadget identity is exact modulo q
    // without another key column. Reducing the top digit handles z >= q.

    for coeff_idx in 0..params.d {
        let mut x = input.get_poly(0, 0)[coeff_idx];
        // Coefficients arrive from `from_ntt_alloc`, which reduces; the branch
        // is for callers that have not.
        if x >= params.q {
            x %= params.q;
        }
        for digit_idx in 0..params.gadget.ell - 1 {
            let low = x & mask;
            x >>= shift;
            // Balanced digits: anything at or above z/2 becomes `low - z` and
            // carries one into the next digit. `+z` before the shift is exactly
            // `+1` after it.
            let digit = if low >= half {
                x += 1;
                params.q - (z - low)
            } else {
                low
            };
            out.get_poly_mut(digit_idx, 0)[coeff_idx] = digit;
        }
        debug_assert!(x <= z);
        let top = if x >= params.q { x % params.q } else { x };
        out.get_poly_mut(params.gadget.ell - 1, 0)[coeff_idx] = top;
    }
    out
}

/// Compute `τ_g^{k-1}(K_g)` from `K_g` without any extra key material.
/// The image is just `K_g` with `τ_g^{k-1}` applied component-wise to
/// each polynomial of the matrix. SPEC.md §6 / Appendix C.
///
/// The `params` reference is forwarded from the input — local images of a
/// KS matrix share its parameter set by definition.
#[must_use]
pub fn automorphic_image<'a>(k: &KeySwitchingMatrix<'a>, t: u64) -> KeySwitchingMatrix<'a> {
    KeySwitchingMatrix {
        mat: tau_ntt(&k.mat, t),
        params: k.params,
    }
}

/// `τ_t(K)` using a precomputed NTT slot permutation.
///
/// Identical result to [`automorphic_image`], but an automorphism in the NTT
/// domain is only a slot permutation, so this avoids the inverse/forward NTT
/// pair per polynomial that [`crate::automorph::tau_ntt`] pays — `6 + 6` of
/// them per image, `d - 2` images per collapse. `tau_ntt` stays as the
/// coefficient-domain oracle the tests check this against.
#[must_use]
pub fn automorphic_image_with_table<'a>(
    k: &KeySwitchingMatrix<'a>,
    table: &NttAutomorphTable,
) -> KeySwitchingMatrix<'a> {
    KeySwitchingMatrix {
        mat: apply_tau_ntt_alloc(&k.mat, table),
        params: k.params,
    }
}

/// Test/diagnostic thread-local counter for `KS.Switch` calls. Used by
/// `tests/inspiring_vs_cdks_recursion.rs` to assert the linear-cascade
/// `KS.Switch` count of exactly `d − 1` during preprocessing and zero online
/// key-switch products during `pack`.
#[doc(hidden)]
pub mod ks_call_count {
    use std::cell::Cell;

    thread_local! {
        static COUNTER: Cell<u64> = const { Cell::new(0) };
    }

    /// Reset to 0. Call before a measured `pack`.
    pub fn reset() {
        COUNTER.with(|c| c.set(0));
    }

    /// Increment by one. Called from inside `ks_switch`.
    pub fn inc() {
        COUNTER.with(|c| c.set(c.get() + 1));
    }

    /// Read the current count.
    #[must_use]
    pub fn get() -> u64 {
        COUNTER.with(Cell::get)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::automorph::tau_g_pow;
    use crate::params::GadgetParams;
    use rand_chacha::rand_core::SeedableRng;
    use spiral_rs::gadget::gadget_invert_alloc;
    use spiral_rs::poly::PolyMatrix;

    // ---- helpers --------------------------------------------------------

    fn params() -> RlweParams {
        // Small parameters: d=8, q=12289 (NTT-friendly 14-bit prime), p=4,
        // gadget z=8, ℓ=5 so z^ℓ = 32768 ≥ q. Noise width is intentionally
        // tiny (σ=0.1) so that round-trip tests below decrypt exactly even
        // without rounding-margin reasoning.
        RlweParams::new(
            8,
            12289,
            4,
            0.1,
            GadgetParams {
                bits_per: 3,
                ell: 5,
            },
        )
        .expect("valid params")
    }

    fn raw_from_coeffs<'a>(params: &'a RlweParams, coeffs: &[u64]) -> PolyMatrixRaw<'a> {
        let mut raw = PolyMatrixRaw::zero(&params.spiral, 1, 1);
        raw.get_poly_mut(0, 0).copy_from_slice(coeffs);
        raw
    }

    fn ntt_from_coeffs<'a>(params: &'a RlweParams, coeffs: &[u64]) -> PolyMatrixNTT<'a> {
        to_ntt_alloc(&raw_from_coeffs(params, coeffs))
    }

    /// Apply `τ_t : p(X) ↦ p(X^t)` to a length-`d` coefficient vector at the
    /// quotient ring `R_q = Z_q[X]/(X^d + 1)`.
    fn tau_coeffs(poly: &[u64], exponent: u64, q: u64) -> Vec<u64> {
        let d = poly.len();
        let mut out = vec![0; d];
        for (i, coeff) in poly.iter().enumerate() {
            let exp = (i as u64 * exponent) % (2 * d as u64);
            let reduced = coeff % q;
            let (idx, value) = if exp < d as u64 {
                (exp as usize, reduced)
            } else {
                (
                    (exp - d as u64) as usize,
                    if reduced == 0 { 0 } else { q - reduced },
                )
            };
            out[idx] = (out[idx] + value) % q;
        }
        out
    }

    /// Negacyclic polynomial multiplication in `R_q`, computed in `u128` so
    /// the test oracle is independent of spiral-rs's NTT path.
    fn negacyclic_mul(lhs: &[u64], rhs: &[u64], q: u64) -> Vec<u64> {
        let d = lhs.len();
        let mut out = vec![0; d];
        for (i, l) in lhs.iter().enumerate() {
            for (j, r) in rhs.iter().enumerate() {
                let product = (u128::from(*l) * u128::from(*r) % u128::from(q)) as u64;
                let degree = i + j;
                if degree < d {
                    out[degree] = (out[degree] + product) % q;
                } else if product != 0 {
                    out[degree - d] = (out[degree - d] + q - product) % q;
                }
            }
        }
        out
    }

    fn add_poly(lhs: &[u64], rhs: &[u64], q: u64) -> Vec<u64> {
        lhs.iter().zip(rhs).map(|(x, y)| (x + y) % q).collect()
    }

    fn sub_poly(lhs: &[u64], rhs: &[u64], q: u64) -> Vec<u64> {
        lhs.iter().zip(rhs).map(|(x, y)| (q + x - y) % q).collect()
    }

    /// Decrypt `(c1, c2)` under `s` and round to the plaintext slot of `Δ·m`.
    fn decrypt(params: &RlweParams, c1: &[u64], c2: &[u64], s: &[u64]) -> Vec<u64> {
        let inner = add_poly(c2, &negacyclic_mul(c1, s, params.q), params.q);
        inner
            .iter()
            .map(|coeff| ((coeff + params.delta / 2) / params.delta) % params.p)
            .collect()
    }

    // ---- regression test for spiral-rs scalar multiply correctness ------

    /// **Regression guard for spiral-rs `multiply_add_modular` correctness**.
    ///
    /// The old upstream revision dropped the accumulator on `crt_count == 1`,
    /// collapsing `[1 × ℓ] · [ℓ × 1]` products to "last term only". Valar's
    /// fork fixes that scalar path; this test keeps the pin honest by
    /// multiplying a `[1 × 3]` by a `[3 × 1]` matrix where every inner term is
    /// non-zero, with a known reference computed in `u128` outside spiral-rs.
    #[test]
    fn spiral_matrix_multiply_accumulates_along_inner_dim() {
        let params = params();
        let mut a = PolyMatrixNTT::zero(&params.spiral, 1, 3);
        let mut b = PolyMatrixNTT::zero(&params.spiral, 3, 1);
        let inputs: [[u64; 8]; 3] = [
            [3, 1, 4, 1, 5, 9, 2, 6],
            [2, 7, 1, 8, 2, 8, 1, 8],
            [1, 6, 1, 8, 0, 3, 3, 9],
        ];
        let factors: [[u64; 8]; 3] = [
            [11, 13, 17, 19, 23, 29, 31, 37],
            [41, 43, 47, 53, 59, 61, 67, 71],
            [73, 79, 83, 89, 97, 101, 103, 107],
        ];

        for k in 0..3 {
            let a_ntt = to_ntt_alloc(&raw_from_coeffs(&params, &inputs[k]));
            a.get_poly_mut(0, k).copy_from_slice(a_ntt.get_poly(0, 0));
            let b_ntt = to_ntt_alloc(&raw_from_coeffs(&params, &factors[k]));
            b.get_poly_mut(k, 0).copy_from_slice(b_ntt.get_poly(0, 0));
        }

        let mut prod = PolyMatrixNTT::zero(&params.spiral, 1, 1);
        multiply(&mut prod, &a, &b);
        let prod_raw = from_ntt_alloc(&prod);

        let mut expected = vec![0_u64; params.d];
        for k in 0..3 {
            expected = add_poly(
                &expected,
                &negacyclic_mul(&inputs[k], &factors[k], params.q),
                params.q,
            );
        }

        assert_eq!(
            prod_raw.get_poly(0, 0).to_vec(),
            expected,
            "spiral-rs multiply lost the accumulator; see docs/spiral-rs-mapping.md §1"
        );
    }

    // ---- gadget sanity --------------------------------------------------

    #[test]
    fn spiral_gadget_invert_reconstructs_each_coefficient_mod_q() {
        let params = params();
        let mut input = PolyMatrixRaw::zero(&params.spiral, 1, 1);
        input
            .get_poly_mut(0, 0)
            .copy_from_slice(&[0, 1, 7, 8, 63, 64, params.q - 1, params.q - 4]);

        let digits = gadget_invert_alloc(params.gadget.ell, &input);
        let z = u128::from(params.gadget.z());
        let q = u128::from(params.q);
        for coeff_idx in 0..params.d {
            let mut acc = 0u128;
            for digit_row in 0..params.gadget.ell {
                acc +=
                    u128::from(digits.get_poly(digit_row, 0)[coeff_idx]) * z.pow(digit_row as u32);
            }
            assert_eq!(
                input.get_poly(0, 0)[coeff_idx],
                (acc % q) as u64,
                "coefficient index {coeff_idx}"
            );
        }
    }

    #[test]
    fn signed_gadget_invert_uses_balanced_digits_and_reconstructs() {
        let params = params();
        let input = raw_from_coeffs(&params, &[0, 1, 4, 7, 8, 63, 64, params.q - 1]);

        let digits = signed_gadget_invert_alloc(&params, &input);
        let z = u128::from(params.gadget.z());
        let q = u128::from(params.q);
        for coeff_idx in 0..params.d {
            let mut acc = 0_u128;
            for digit_row in 0..params.gadget.ell {
                acc +=
                    u128::from(digits.get_poly(digit_row, 0)[coeff_idx]) * z.pow(digit_row as u32);
            }
            assert_eq!(
                input.get_poly(0, 0)[coeff_idx],
                (acc % q) as u64,
                "coefficient index {coeff_idx}"
            );
        }

        assert_eq!(digits.get_poly(0, 0)[2], params.q - 4);
        assert_eq!(digits.get_poly(0, 0)[3], params.q - 1);
    }

    #[test]
    fn signed_gadget_invert_retains_top_carry() {
        for gadget in [
            GadgetParams {
                bits_per: 1,
                ell: 14,
            },
            GadgetParams {
                bits_per: 3,
                ell: 5,
            },
        ] {
            let params = RlweParams::new(8, 12289, 4, 3.2, gadget).unwrap();
            let values = [
                0,
                1,
                gadget.z() / 2,
                gadget.z() / 2 + 1,
                params.q / 2,
                params.q - 2,
                params.q - 1,
                params.q,
            ];
            let digits = signed_gadget_invert_alloc(&params, &raw_from_coeffs(&params, &values));
            for (coeff_idx, value) in values.into_iter().enumerate() {
                let mut reconstructed = 0_u128;
                let mut power = 1_u128;
                for digit_idx in 0..gadget.ell {
                    reconstructed = (reconstructed
                        + u128::from(digits.get_poly(digit_idx, 0)[coeff_idx]) * power)
                        % u128::from(params.q);
                    power = power * u128::from(gadget.z()) % u128::from(params.q);
                }
                assert_eq!(reconstructed as u64, value % params.q);
            }
        }

        let params = RlweParams::new(
            8,
            12289,
            4,
            3.2,
            GadgetParams {
                bits_per: 1,
                ell: 14,
            },
        )
        .unwrap();
        let digits =
            signed_gadget_invert_alloc(&params, &raw_from_coeffs(&params, &[params.q - 2; 8]));
        assert_eq!(digits.get_poly(13, 0)[0], 2);
    }

    #[test]
    fn high_carry_key_switch_preserves_zero_phase() {
        let params = RlweParams::new(
            8,
            12289,
            4,
            3.2,
            GadgetParams {
                bits_per: 1,
                ell: 14,
            },
        )
        .unwrap();
        let gadget = build_gadget(&params.spiral, 1, params.gadget.ell);
        let zero = PolyMatrixRaw::zero(&params.spiral, 1, params.gadget.ell);
        let k = KeySwitchingMatrix {
            mat: stack_ntt(&to_ntt_alloc(&zero), &to_ntt_alloc(&gadget)),
            params: &params,
        };
        let c1 = ntt_from_coeffs(&params, &[params.q - 1, 0, 0, 0, 0, 0, 0, 0]);
        let c2 = ntt_from_coeffs(&params, &[1, 0, 0, 0, 0, 0, 0, 0]);
        let digits = ks_digits_ntt_from_c1(&params, &c1);
        let (a_direct, b_direct) = ks_switch(&k, &c1, &c2);
        let (a_cached, b_cached) = ks_switch_with_digits_ntt(&k, &digits, &c2);
        assert_eq!(a_direct.as_slice(), a_cached.as_slice());
        assert_eq!(b_direct.as_slice(), b_cached.as_slice());
        assert_eq!(from_ntt_alloc(&b_direct).get_poly(0, 0)[0], 0);
        assert_eq!(
            decrypt(
                &params,
                from_ntt_alloc(&a_direct).get_poly(0, 0),
                from_ntt_alloc(&b_direct).get_poly(0, 0),
                &[0; 8]
            ),
            vec![0; 8]
        );
    }

    #[test]
    fn ks_switch_with_precomputed_digits_matches_full_switch() {
        let params = params();
        let mut rng = rand_chacha::ChaCha20Rng::seed_from_u64(0xD161_7A11);
        let k = ks_setup(
            &params,
            &ntt_from_coeffs(&params, &[1, 2, 3, 4, 5, 6, 7, 8]),
            &ntt_from_coeffs(&params, &[8, 7, 6, 5, 4, 3, 2, 1]),
            &mut rng,
        );
        let c1 = ntt_from_coeffs(&params, &[3, 1, 4, 1, 5, 9, 2, 6]);
        let c2_values = [
            [0, 0, 0, 0, 0, 0, 0, 0],
            [9, 2, 6, 5, 3, 5, 8, 9],
            [
                params.q - 1,
                1,
                params.q - 2,
                2,
                params.q - 3,
                3,
                params.q - 4,
                4,
            ],
        ];
        let digits = ks_digits_ntt_from_c1(&params, &c1);

        for c2_coeffs in c2_values {
            let c2 = ntt_from_coeffs(&params, &c2_coeffs);
            let (expected_a, expected_b) = ks_switch(&k, &c1, &c2);
            let (actual_a, actual_b) = ks_switch_with_digits_ntt(&k, &digits, &c2);

            assert_eq!(actual_a.as_slice(), expected_a.as_slice());
            assert_eq!(actual_b.as_slice(), expected_b.as_slice());
        }
    }

    // ---- KS round-trip --------------------------------------------------

    /// Encrypt a known plaintext under `s_from`, apply `ks_switch` with a
    /// real `ks_setup` matrix (real RNG, real noise), decrypt under
    /// `s_to`, expect the plaintext back. Exercises the production code
    /// path end-to-end at small parameters where the noise budget is
    /// comfortably below `Δ/2`.
    #[test]
    fn ks_setup_then_ks_switch_recovers_plaintext_under_target_secret() {
        let params = params();
        let s_from = vec![3, 1, 4, 1, 5, 9, 2, 6];
        let s_to = vec![1, 0, params.q - 1, 1, 0, 1, params.q - 1, 0];
        let messages = vec![0_u64, 1, 2, 3, 3, 2, 1, 0];
        let c1 = vec![5_u64, 7, 11, 13, 17, 19, 23, 29];

        // c2 = Δ·m − c1·s_from (mod q), so (c1, c2) decrypts to `messages`
        // under s_from with zero noise.
        let encoded: Vec<_> = messages
            .iter()
            .map(|m| (params.delta * m) % params.q)
            .collect();
        let c2 = sub_poly(&encoded, &negacyclic_mul(&c1, &s_from, params.q), params.q);

        let mut rng = rand_chacha::ChaCha20Rng::seed_from_u64(0xC0DE_C0DE);
        let k = ks_setup(
            &params,
            &ntt_from_coeffs(&params, &s_from),
            &ntt_from_coeffs(&params, &s_to),
            &mut rng,
        );

        let (c1_new, c2_new) = ks_switch(
            &k,
            &ntt_from_coeffs(&params, &c1),
            &ntt_from_coeffs(&params, &c2),
        );

        let c1_new_raw = from_ntt_alloc(&c1_new);
        let c2_new_raw = from_ntt_alloc(&c2_new);
        assert_eq!(
            decrypt(
                &params,
                c1_new_raw.get_poly(0, 0),
                c2_new_raw.get_poly(0, 0),
                &s_to
            ),
            messages,
        );
    }

    // ---- automorphic image ----------------------------------------------

    /// Local automorphic images of `K = KS.Setup(s_from → s_to)` are
    /// themselves valid KS matrices — for `K' = automorphic_image(K, t)`,
    /// switching a ciphertext under `τ_t(s_from)` through `K'` produces a
    /// ciphertext that decrypts under `τ_t(s_to)`. SPEC.md §6 / paper
    /// Appendix C is the formal statement; this test pins it down at small
    /// parameters with a non-identity rotation.
    #[test]
    fn automorphic_image_yields_ks_for_rotated_secret_pair() {
        let params = params();
        let s_from = vec![3, 1, 4, 1, 5, 9, 2, 6];
        let s_to = vec![1, 0, params.q - 1, 1, 0, 1, params.q - 1, 0];
        let messages = vec![0_u64, 1, 2, 3, 3, 2, 1, 0];
        let c1 = vec![5_u64, 7, 11, 13, 17, 19, 23, 29];

        let mut rng = rand_chacha::ChaCha20Rng::seed_from_u64(0xA70_A0E);
        let k = ks_setup(
            &params,
            &ntt_from_coeffs(&params, &s_from),
            &ntt_from_coeffs(&params, &s_to),
            &mut rng,
        );

        // Pick a non-trivial rotation `t = τ_g^2`.
        let t = tau_g_pow(2, params.d);
        let s_from_rot = tau_coeffs(&s_from, t, params.q);
        let s_to_rot = tau_coeffs(&s_to, t, params.q);
        let k_image = automorphic_image(&k, t);

        // Encrypt `messages` under the rotated source secret with c1.
        let encoded: Vec<_> = messages
            .iter()
            .map(|m| (params.delta * m) % params.q)
            .collect();
        let c2 = sub_poly(
            &encoded,
            &negacyclic_mul(&c1, &s_from_rot, params.q),
            params.q,
        );

        let (c1_new, c2_new) = ks_switch(
            &k_image,
            &ntt_from_coeffs(&params, &c1),
            &ntt_from_coeffs(&params, &c2),
        );
        let c1_new_raw = from_ntt_alloc(&c1_new);
        let c2_new_raw = from_ntt_alloc(&c2_new);
        assert_eq!(
            decrypt(
                &params,
                c1_new_raw.get_poly(0, 0),
                c2_new_raw.get_poly(0, 0),
                &s_to_rot
            ),
            messages,
            "ks_switch through automorphic_image(K, t) must decrypt under τ_t(s_to)",
        );
    }

    // ---- ks_call_count instrumentation ----------------------------------

    /// Sanity check on the test-only call counter that
    /// `tests/inspiring_vs_cdks_recursion.rs` relies on. If this counter
    /// stops working, the linear-cascade preprocessing invariant becomes
    /// unobservable.
    #[test]
    fn ks_call_count_increments_once_per_ks_switch() {
        let params = params();
        let mut rng = rand_chacha::ChaCha20Rng::seed_from_u64(0xCA11);
        let k = ks_setup(
            &params,
            &ntt_from_coeffs(&params, &[1, 2, 3, 4, 5, 6, 7, 8]),
            &ntt_from_coeffs(&params, &[8, 7, 6, 5, 4, 3, 2, 1]),
            &mut rng,
        );
        let c1 = ntt_from_coeffs(&params, &[1, 0, 0, 0, 0, 0, 0, 0]);
        let c2 = PolyMatrixNTT::zero(&params.spiral, 1, 1);

        ks_call_count::reset();
        let _ = ks_switch(&k, &c1, &c2);
        let _ = ks_switch(&k, &c1, &c2);
        let _ = ks_switch(&k, &c1, &c2);
        assert_eq!(ks_call_count::get(), 3);
    }
}