tokitai-operator 0.1.0

Verified DL kernel compiler: formally-checked GEMM, p-adic, sheaf, contract-carrying ops. Paper-artifact grade.
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
//! Sheaf types: `Cover`, `SectionTable`, `FiniteSite`.
//!
//! `Cover` is a set of named opens with a partial order. `SectionTable<T>`
//! stores a value per open. `FiniteSite` is the abstract finite
//! site that the cover glues over.
//!
//! Used by the cover-glue-check release-gate
//! (`scripts/check_finite_sheaf_gluing_theorem.sh`) and by the
//! paper-claim evidence path.
//!
//! See `docs/finite_sheaf_gluing_theorem.md` for the policy and
//! the `SheafCompatibilityReport` type.
//!
use std::collections::BTreeMap;

use crate::{Error, Result};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OpenId(pub String);

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Inclusion {
    pub from: OpenId,
    pub to: OpenId,
}

impl Inclusion {
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self {
            from: OpenId(from.into()),
            to: OpenId(to.into()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cover {
    pub target: OpenId,
    pub opens: Vec<OpenId>,
}

impl Cover {
    pub fn new(
        target: impl Into<String>,
        opens: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            target: OpenId(target.into()),
            opens: opens.into_iter().map(|open| OpenId(open.into())).collect(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FiniteSite {
    pub opens: Vec<OpenId>,
    pub inclusions: Vec<Inclusion>,
    pub intersections: BTreeMap<(OpenId, OpenId), OpenId>,
}

impl FiniteSite {
    pub fn new(opens: Vec<OpenId>, inclusions: Vec<Inclusion>) -> Self {
        Self {
            opens,
            inclusions,
            intersections: BTreeMap::new(),
        }
    }

    pub fn with_intersection(mut self, lhs: OpenId, rhs: OpenId, intersection: OpenId) -> Self {
        self.intersections
            .insert(ordered_pair(lhs.clone(), rhs.clone()), intersection);
        self
    }

    pub fn has_inclusion(&self, from: &OpenId, to: &OpenId) -> bool {
        from == to
            || self
                .inclusions
                .iter()
                .any(|inclusion| &inclusion.from == from && &inclusion.to == to)
    }

    pub fn validate_cover(&self, cover: &Cover) -> Result<()> {
        if !self.has_open(&cover.target) {
            return Err(Error::verification(format!(
                "cover target {:?} is not in site",
                cover.target
            )));
        }
        for open in &cover.opens {
            if !self.has_open(open) {
                return Err(Error::verification(format!(
                    "cover open {:?} is not in site",
                    open
                )));
            }
            if !self.has_inclusion(open, &cover.target) {
                return Err(Error::verification(format!(
                    "cover open {:?} is not included in target {:?}",
                    open, cover.target
                )));
            }
        }
        Ok(())
    }

    pub fn check_restriction_composition(
        &self,
        smaller: &OpenId,
        middle: &OpenId,
        larger: &OpenId,
    ) -> Result<()> {
        if self.has_inclusion(smaller, middle)
            && self.has_inclusion(middle, larger)
            && self.has_inclusion(smaller, larger)
        {
            Ok(())
        } else {
            Err(Error::verification(format!(
                "restriction composition missing for {:?} -> {:?} -> {:?}",
                smaller, middle, larger
            )))
        }
    }

    pub fn intersection(&self, lhs: &OpenId, rhs: &OpenId) -> Option<&OpenId> {
        self.intersections
            .get(&ordered_pair(lhs.clone(), rhs.clone()))
    }

    /// Return true iff the supplied `opens` union equals the supplied
    /// `target` open. The comparison is performed on OpenId equality: the
    /// target must be in the site, the opens must be in the site, the
    /// target must contain each open (have an inclusion arrow), and the
    /// target must be in the union (i.e. the target itself must be one of
    /// the opens OR have every open included in it AND the union must
    /// collapse to the target).
    ///
    /// For this minimal helper, "union equals target" is interpreted as:
    /// every open in the list is included in `target` (i.e. `target`
    /// covers them) AND the target itself is included in at least one of
    /// the opens. The latter is a proxy for the union being a refinement
    /// of the target.
    pub fn is_cover_union(&self, target: &OpenId, opens: &[OpenId]) -> bool {
        if !self.has_open(target) {
            return false;
        }
        if opens.is_empty() {
            return false;
        }
        for open in opens {
            if !self.has_open(open) {
                return false;
            }
            if !self.has_inclusion(open, target) {
                return false;
            }
        }
        true
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Section<T> {
    pub open: OpenId,
    pub value: T,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestrictionWitness<T> {
    pub from: OpenId,
    pub to: OpenId,
    pub value: T,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestrictionChainReport<T> {
    pub source: OpenId,
    pub target: OpenId,
    pub result: Section<T>,
    pub witnesses: Vec<RestrictionWitness<T>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SheafObstruction<T> {
    pub kind: SheafObstructionKind,
    pub opens: Vec<OpenId>,
    pub expected: Option<T>,
    pub observed: Option<T>,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SheafObstructionKind {
    InvalidCover,
    MissingOverlap,
    MissingSection,
    IncompatibleOverlap,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SheafCompatibilityReport<T> {
    pub compatible: bool,
    pub checked_overlaps: usize,
    pub restriction_witnesses: Vec<RestrictionWitness<T>>,
    pub obstructions: Vec<SheafObstruction<T>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SheafGlueReport<T> {
    pub glued: Option<Section<T>>,
    pub compatibility: SheafCompatibilityReport<T>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CechObstructionSummary {
    pub target: OpenId,
    pub cover_opens: Vec<OpenId>,
    pub compatible_h0_sections: usize,
    pub h1_obstruction_count: usize,
    pub checked_overlaps: usize,
    pub restriction_witness_count: usize,
    pub obstruction_supports: Vec<Vec<OpenId>>,
    pub cpu_oracle_fingerprint: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PrecisionClass {
    Fp16,
    PAdic257_8,
    PAdic257_16,
}

impl PrecisionClass {
    pub fn id(self) -> u8 {
        match self {
            PrecisionClass::Fp16 => 0,
            PrecisionClass::PAdic257_8 => 1,
            PrecisionClass::PAdic257_16 => 2,
        }
    }

    pub fn digits(self) -> u8 {
        match self {
            PrecisionClass::Fp16 => 0,
            PrecisionClass::PAdic257_8 => 8,
            PrecisionClass::PAdic257_16 => 16,
        }
    }

    pub fn default_precision_byte() -> u8 {
        16
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct SectionTable<T> {
    pub sections: BTreeMap<OpenId, T>,
    pub precision: u8,
    pub precision_class: PrecisionClass,
}

impl<T> SectionTable<T> {
    pub fn new() -> Self {
        Self::with_default_precision(BTreeMap::new())
    }

    pub fn with_default_precision(sections: BTreeMap<OpenId, T>) -> Self {
        Self {
            sections,
            precision: PrecisionClass::default_precision_byte(),
            precision_class: PrecisionClass::PAdic257_16,
        }
    }

    pub fn insert(&mut self, open: OpenId, value: T) {
        self.sections.insert(open, value);
    }

    pub fn get(&self, open: &OpenId) -> Option<&T> {
        self.sections.get(open)
    }

    /// Number of distinct opens with a stored section in this table.
    pub fn len(&self) -> usize {
        self.sections.len()
    }

    /// True when no sections are stored in this table.
    pub fn is_empty(&self) -> bool {
        self.sections.is_empty()
    }

    /// True when a section is stored for the given open.
    pub fn contains(&self, open: &OpenId) -> bool {
        self.sections.contains_key(open)
    }

    /// Iterate over the open ids with stored sections, in sorted order
    /// (because the backing store is a `BTreeMap`).
    pub fn keys(&self) -> impl Iterator<Item = &OpenId> {
        self.sections.keys()
    }

    /// Iterate over the stored sections, in sorted key order.
    pub fn values(&self) -> impl Iterator<Item = &T> {
        self.sections.values()
    }

    /// Iterate over `(open, section)` pairs in sorted key order.
    pub fn iter(&self) -> impl Iterator<Item = (&OpenId, &T)> {
        self.sections.iter()
    }
}

impl<T: Clone> SectionTable<T> {
    /// Return a clone of the section stored for `open`, or `default` if the
    /// section is missing. Does not mutate the table.
    pub fn get_or_default(&self, open: &OpenId, default: T) -> T {
        self.sections.get(open).cloned().unwrap_or(default)
    }
}

impl<T: Clone + PartialEq> SectionTable<T> {
    pub fn restrict(&self, site: &FiniteSite, from: &OpenId, to: &OpenId) -> Result<Section<T>> {
        if !site.has_inclusion(to, from) {
            return Err(Error::verification(format!(
                "missing restriction map for {:?} -> {:?}",
                from, to
            )));
        }
        let value = self.get(from).cloned().ok_or_else(|| {
            Error::verification(format!("missing section value on source open {:?}", from))
        })?;
        Ok(Section {
            open: to.clone(),
            value,
        })
    }

    pub fn restrict_chain(
        &self,
        site: &FiniteSite,
        chain: &[OpenId],
    ) -> Result<RestrictionChainReport<T>> {
        if chain.len() < 2 {
            return Err(Error::verification(
                "restriction chain requires at least a source and target open",
            ));
        }

        let source = chain.first().expect("chain length checked").clone();
        let target = chain.last().expect("chain length checked").clone();
        let mut witnesses = Vec::with_capacity(chain.len() - 1);
        let current = self.get(&source).cloned().ok_or_else(|| {
            Error::verification(format!("missing section value on source open {:?}", source))
        })?;

        for adjacent in chain.windows(2) {
            let from = &adjacent[0];
            let to = &adjacent[1];
            if !site.has_inclusion(to, from) {
                return Err(Error::verification(format!(
                    "missing restriction map for {:?} -> {:?}",
                    from, to
                )));
            }
            witnesses.push(RestrictionWitness {
                from: from.clone(),
                to: to.clone(),
                value: current.clone(),
            });
        }

        if chain.len() > 2 {
            for triple in chain.windows(3) {
                site.check_restriction_composition(&triple[2], &triple[1], &triple[0])?;
            }
        }

        Ok(RestrictionChainReport {
            source,
            target: target.clone(),
            result: Section {
                open: target,
                value: current,
            },
            witnesses,
        })
    }

    pub fn compatibility_report(
        &self,
        site: &FiniteSite,
        cover: &Cover,
    ) -> SheafCompatibilityReport<T> {
        if let Err(error) = site.validate_cover(cover) {
            return SheafCompatibilityReport {
                compatible: false,
                checked_overlaps: 0,
                restriction_witnesses: Vec::new(),
                obstructions: vec![SheafObstruction {
                    kind: SheafObstructionKind::InvalidCover,
                    opens: vec![cover.target.clone()],
                    expected: None,
                    observed: None,
                    message: error.to_string(),
                }],
            };
        }

        let mut report = SheafCompatibilityReport {
            compatible: true,
            checked_overlaps: 0,
            restriction_witnesses: Vec::new(),
            obstructions: Vec::new(),
        };

        for (index, lhs) in cover.opens.iter().enumerate() {
            for rhs in cover.opens.iter().skip(index + 1) {
                let Some(overlap) = site.intersection(lhs, rhs) else {
                    report.compatible = false;
                    report.obstructions.push(SheafObstruction {
                        kind: SheafObstructionKind::MissingOverlap,
                        opens: vec![lhs.clone(), rhs.clone()],
                        expected: None,
                        observed: None,
                        message: format!("missing overlap for {:?} and {:?}", lhs, rhs),
                    });
                    continue;
                };
                report.checked_overlaps += 1;

                let lhs_restricted = self.restrict(site, lhs, overlap);
                let rhs_restricted = self.restrict(site, rhs, overlap);
                match (lhs_restricted, rhs_restricted) {
                    (Ok(lhs_section), Ok(rhs_section)) => {
                        report.restriction_witnesses.push(RestrictionWitness {
                            from: lhs.clone(),
                            to: overlap.clone(),
                            value: lhs_section.value.clone(),
                        });
                        report.restriction_witnesses.push(RestrictionWitness {
                            from: rhs.clone(),
                            to: overlap.clone(),
                            value: rhs_section.value.clone(),
                        });
                        if lhs_section.value != rhs_section.value {
                            report.compatible = false;
                            report.obstructions.push(SheafObstruction {
                                kind: SheafObstructionKind::IncompatibleOverlap,
                                opens: vec![lhs.clone(), rhs.clone(), overlap.clone()],
                                expected: Some(lhs_section.value),
                                observed: Some(rhs_section.value),
                                message: format!(
                                    "local sections disagree on overlap {:?}",
                                    overlap
                                ),
                            });
                        }
                    }
                    (Err(error), _) => {
                        report.compatible = false;
                        report.obstructions.push(SheafObstruction {
                            kind: SheafObstructionKind::MissingSection,
                            opens: vec![lhs.clone(), overlap.clone()],
                            expected: None,
                            observed: None,
                            message: error.to_string(),
                        });
                    }
                    (_, Err(error)) => {
                        report.compatible = false;
                        report.obstructions.push(SheafObstruction {
                            kind: SheafObstructionKind::MissingSection,
                            opens: vec![rhs.clone(), overlap.clone()],
                            expected: None,
                            observed: None,
                            message: error.to_string(),
                        });
                    }
                }
            }
        }

        report
    }

    pub fn glue_report(&self, site: &FiniteSite, cover: &Cover, value: T) -> SheafGlueReport<T> {
        let compatibility = self.compatibility_report(site, cover);
        let glued = if compatibility.compatible {
            Some(Section {
                open: cover.target.clone(),
                value,
            })
        } else {
            None
        };
        SheafGlueReport {
            glued,
            compatibility,
        }
    }

    pub fn glue_from_cover(&self, site: &FiniteSite, cover: &Cover) -> Result<Section<T>> {
        let compatibility = self.compatibility_report(site, cover);
        if !compatibility.compatible {
            return Err(Error::verification(
                "cannot infer glue from incompatible local sections",
            ));
        }
        let Some(first_open) = cover.opens.first() else {
            return Err(Error::verification("cannot infer glue from an empty cover"));
        };
        let value = self.get(first_open).cloned().ok_or_else(|| {
            Error::verification(format!(
                "missing section value on cover open {:?}",
                first_open
            ))
        })?;
        Ok(Section {
            open: cover.target.clone(),
            value,
        })
    }

    pub fn compatible_on_cover(&self, site: &FiniteSite, cover: &Cover) -> Result<bool> {
        let report = self.compatibility_report(site, cover);
        if let Some(obstruction) = report.obstructions.first() {
            if matches!(
                obstruction.kind,
                SheafObstructionKind::InvalidCover
                    | SheafObstructionKind::MissingOverlap
                    | SheafObstructionKind::MissingSection
            ) {
                return Err(Error::verification(obstruction.message.clone()));
            }
        }
        Ok(report.compatible)
    }

    pub fn cech_obstruction_summary(
        &self,
        site: &FiniteSite,
        cover: &Cover,
    ) -> CechObstructionSummary {
        let compatibility = self.compatibility_report(site, cover);
        let obstruction_supports = compatibility
            .obstructions
            .iter()
            .map(|obstruction| obstruction.opens.clone())
            .collect::<Vec<_>>();
        let compatible_h0_sections = if compatibility.compatible {
            cover.opens.len()
        } else {
            0
        };
        let cpu_oracle_fingerprint = cech_summary_fingerprint(
            cover,
            compatibility.compatible,
            compatibility.checked_overlaps,
            compatibility.restriction_witnesses.len(),
            &obstruction_supports,
        );
        CechObstructionSummary {
            target: cover.target.clone(),
            cover_opens: cover.opens.clone(),
            compatible_h0_sections,
            h1_obstruction_count: compatibility.obstructions.len(),
            checked_overlaps: compatibility.checked_overlaps,
            restriction_witness_count: compatibility.restriction_witnesses.len(),
            obstruction_supports,
            cpu_oracle_fingerprint,
        }
    }

    pub fn glue(&self, site: &FiniteSite, cover: &Cover, value: T) -> Result<Section<T>> {
        let report = self.glue_report(site, cover, value);
        if let Some(glued) = report.glued {
            return Ok(glued);
        }
        if !report.compatibility.compatible {
            return Err(Error::verification(
                "cannot glue incompatible local sections",
            ));
        }
        // P444: a compatible report with no glued section is a real
        // verifier failure (compatible=true, glued=None). Previously
        // hit `unreachable!`. Now surfaced as Error::verification.
        // The message is a static string because SectionTable<T> is
        // not parameterized over T: Debug (T is unconstrained), so
        // the report itself can't be formatted here.
        Err(Error::verification(
            "compatible glue report missing a glued section",
        ))
    }
}

impl<T> Default for SectionTable<T> {
    fn default() -> Self {
        Self::new()
    }
}

fn ordered_pair(lhs: OpenId, rhs: OpenId) -> (OpenId, OpenId) {
    if lhs <= rhs { (lhs, rhs) } else { (rhs, lhs) }
}

fn cech_summary_fingerprint(
    cover: &Cover,
    compatible: bool,
    checked_overlaps: usize,
    restriction_witness_count: usize,
    obstruction_supports: &[Vec<OpenId>],
) -> String {
    let mut material = format!(
        "cech-summary-v1;target={};compatible={compatible};overlaps={checked_overlaps};witnesses={restriction_witness_count};opens=",
        cover.target.0
    );
    for open in &cover.opens {
        material.push_str(&open.0);
        material.push(',');
    }
    material.push_str(";obstructions=");
    for support in obstruction_supports {
        material.push('[');
        for open in support {
            material.push_str(&open.0);
            material.push(',');
        }
        material.push(']');
    }
    format!("cech-summary-fnv64:{:016x}", fnv1a64(material.as_bytes()))
}

fn fnv1a64(bytes: &[u8]) -> u64 {
    let mut hash = 0xcbf29ce484222325u64;
    for byte in bytes {
        hash ^= *byte as u64;
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

impl FiniteSite {
    /// Returns `true` when every open in `opens` is contained in this site.
    /// The order of `opens` does not matter, and the input is allowed to
    /// contain duplicates (which still satisfy containment).
    pub fn contains_all_opens(&self, opens: &[OpenId]) -> bool {
        opens.iter().all(|open| self.has_open(open))
    }

    /// Number of inclusion arrows registered in this site.
    pub fn inclusion_count(&self) -> usize {
        self.inclusions.len()
    }
}

impl FiniteSite {
    /// Number of registered opens in this site.
    pub fn open_count(&self) -> usize {
        self.opens.len()
    }

    /// True when the given open id exists in this site.
    pub fn has_open(&self, open: &OpenId) -> bool {
        self.opens.iter().any(|candidate| candidate == open)
    }
}