Skip to main content

icydb_diagnostic_code/
fact.rs

1//! Module: fact
2//!
3//! Responsibility: production-safe numeric diagnostic-fact identities.
4//! Does not own: Candid records, rich labels, prose, or subsystem projections.
5//! Boundary: freezes the numeric vocabulary shared by public errors and host tooling.
6
7use std::fmt;
8
9use crate::ErrorCode;
10
11/// Maximum number of numeric facts carried by one public error.
12pub const MAX_PUBLIC_DIAGNOSTIC_FACTS: usize = 80;
13
14macro_rules! define_fact_tag_registry {
15    ($($name:ident = $raw:literal;)+) => {
16        /// Stable semantic identity for one numeric public diagnostic fact.
17        #[derive(Clone, Copy, Eq, Hash, PartialEq)]
18        pub enum DiagnosticFactTag {
19            $(
20                #[doc = concat!("Public fact tag ", stringify!($raw), ".")]
21                $name,
22            )+
23        }
24
25        impl DiagnosticFactTag {
26            /// Return the fixed public wire value.
27            #[must_use]
28            pub const fn raw(self) -> u8 {
29                match self {
30                    $(Self::$name => $raw,)+
31                }
32            }
33
34            /// Recover a known tag from its public wire value.
35            #[must_use]
36            pub const fn known(raw: u8) -> Option<Self> {
37                match raw {
38                    $($raw => Some(Self::$name),)+
39                    _ => None,
40                }
41            }
42        }
43
44        #[cfg(test)]
45        const ORDERED_FACT_TAGS: &[DiagnosticFactTag] = &[
46            $(DiagnosticFactTag::$name,)+
47        ];
48    };
49}
50
51// This table is a public numeric registry. Append only within a released
52// major-version contract; do not reuse or reinterpret an assigned value.
53define_fact_tag_registry! {
54    AcceptedSchemaFingerprintMethod = 1;
55    AcceptedSchemaFingerprintHigh = 2;
56    AcceptedSchemaFingerprintLow = 3;
57    ExpectedFingerprintPrefix = 4;
58    ActualFingerprintPrefix = 5;
59    EntityTag = 6;
60    ExpectedEntityTag = 7;
61    ActualEntityTag = 8;
62    ConstraintId = 9;
63    FieldId = 10;
64    IndexId = 11;
65    RelationId = 12;
66    MutationOperation = 13;
67    RowOperation = 14;
68    BatchPosition = 15;
69    FirstBatchPosition = 16;
70    DuplicateBatchPosition = 17;
71    ClauseIndex = 18;
72    TermIndex = 19;
73    FirstTermIndex = 20;
74    DuplicateTermIndex = 21;
75    ProjectionIndex = 22;
76    GroupIndex = 23;
77    AggregateIndex = 24;
78    ArgumentIndex = 25;
79    BranchIndex = 26;
80    ComponentIndex = 27;
81    ParameterIndex = 28;
82    SourceSpanStart = 29;
83    SourceSpanEnd = 30;
84    Expected = 31;
85    Actual = 32;
86    Minimum = 33;
87    Maximum = 34;
88    Limit = 35;
89    ExpectedCount = 36;
90    ActualCount = 37;
91    ExpectedRevision = 38;
92    ActualRevision = 39;
93    CurrentRevision = 40;
94    RequestedRevision = 41;
95    ExpectedVersion = 42;
96    ActualVersion = 43;
97    CurrentVersion = 44;
98    RequestedVersion = 45;
99    ExpectedOffset = 46;
100    ActualOffset = 47;
101    ExpectedArity = 48;
102    ActualArity = 49;
103    ExpectedLength = 50;
104    ActualLength = 51;
105    ExpectedSlotCount = 52;
106    ActualSlotCount = 53;
107    RowLayout = 54;
108    HistoryFloor = 55;
109    CurrentLayout = 56;
110    PhysicalSlot = 57;
111    PhysicalGeneration = 58;
112    ExpectedMemoryId = 59;
113    ActualMemoryId = 60;
114    ConstraintKind = 61;
115    ConstraintContext = 62;
116    FieldKind = 63;
117    ValueKind = 64;
118    TypeFamily = 65;
119    FunctionKind = 66;
120    OperatorKind = 67;
121    AggregateKind = 68;
122    KeyNamespaceKind = 69;
123    ComponentKind = 70;
124    MismatchKind = 71;
125    DecodeReason = 72;
126    BudgetResource = 73;
127    MigrationPhase = 74;
128    DatabaseControlRecordKind = 75;
129    StateKind = 76;
130    PayloadComponent = 77;
131    ExpectedSignaturePrefix = 78;
132    ActualSignaturePrefix = 79;
133    FindingPosition = 80;
134    RootField = 81;
135    RecordMember = 82;
136    TupleElement = 83;
137    Newtype = 84;
138    EnumVariant = 85;
139    ListElement = 86;
140    SetElement = 87;
141    MapEntryKey = 88;
142    MapEntryValue = 89;
143    ExecutionBudgetScope = 90;
144    ExecutionLane = 91;
145    QueryShapeFingerprintPrefix = 92;
146    BacklogResource = 93;
147    CurrentCount = 94;
148    ProposedCount = 95;
149}
150
151/// Compact reason carried by [`DiagnosticFactTag::DecodeReason`].
152///
153/// Values are global within that fact tag. They identify only bounded decode
154/// or validation categories and never retain rejected payload bytes.
155#[derive(Clone, Copy, Eq, Hash, PartialEq)]
156pub enum DiagnosticDecodeReason {
157    CursorEmpty,
158    CursorTooLong,
159    CursorOddLength,
160    CursorInvalidHex,
161    CursorGroupedDirectionMismatch,
162    CursorTokenEncode,
163    CursorTokenDecode,
164    RecoveryMarkerMagic,
165    RecoveryMarkerChecksum,
166    RecoveryMarkerState,
167}
168
169/// Compact operation carried by [`DiagnosticFactTag::MutationOperation`].
170#[derive(Clone, Copy, Eq, Hash, PartialEq)]
171pub enum DiagnosticMutationOperation {
172    Insert,
173    Replace,
174    Update,
175    Delete,
176}
177
178macro_rules! define_numeric_fact_value_registry {
179    (
180        $(#[$enum_meta:meta])*
181        pub enum $name:ident {
182            $($variant:ident = $raw:literal;)+
183        }
184    ) => {
185        $(#[$enum_meta])*
186        #[derive(Clone, Copy, Eq, Hash, PartialEq)]
187        pub enum $name {
188            $(
189                #[doc = concat!("Compact diagnostic value ", stringify!($raw), ".")]
190                $variant,
191            )+
192        }
193
194        impl $name {
195            /// Return the fixed numeric fact value.
196            #[must_use]
197            pub const fn raw(self) -> u64 {
198                match self {
199                    $(Self::$variant => $raw,)+
200                }
201            }
202
203            /// Recover a known compact value from its public numeric identity.
204            #[must_use]
205            pub const fn known(raw: u64) -> Option<Self> {
206                match raw {
207                    $($raw => Some(Self::$variant),)+
208                    _ => None,
209                }
210            }
211        }
212
213        impl fmt::Debug for $name {
214            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215                write!(f, "{}", self.raw())
216            }
217        }
218    };
219}
220
221define_numeric_fact_value_registry! {
222    /// Compact cumulative journal resource carried by [`DiagnosticFactTag::BacklogResource`].
223    pub enum DiagnosticBacklogResource {
224        Batches = 1;
225        Records = 2;
226        EncodedBytes = 3;
227    }
228}
229
230define_numeric_fact_value_registry! {
231    /// Compact hard-budget resource carried by [`DiagnosticFactTag::BudgetResource`].
232    pub enum DiagnosticExecutionBudgetResource {
233        QueryExecutions = 1;
234        PlanningSteps = 2;
235        PlanCompilations = 3;
236        KeyIndexEntriesVisited = 4;
237        RowsVisited = 5;
238        StoredBytesRead = 6;
239        PredicateExpressionSteps = 7;
240        NestedValueSteps = 8;
241        DecodedBytes = 9;
242        MaterializedBytes = 10;
243        SortEntries = 11;
244        SortComparisons = 12;
245        SortTemporaryBytes = 13;
246        GroupDistinctEntries = 14;
247        GroupDistinctStateBytes = 15;
248        CursorSteps = 16;
249        TemporaryBytes = 17;
250        ResultRows = 18;
251        ResultBytes = 19;
252        InstructionUnits = 20;
253    }
254}
255
256impl DiagnosticExecutionBudgetResource {
257    /// Every maintained hard-budget resource in stable numeric order.
258    pub const ALL: [Self; 20] = [
259        Self::QueryExecutions,
260        Self::PlanningSteps,
261        Self::PlanCompilations,
262        Self::KeyIndexEntriesVisited,
263        Self::RowsVisited,
264        Self::StoredBytesRead,
265        Self::PredicateExpressionSteps,
266        Self::NestedValueSteps,
267        Self::DecodedBytes,
268        Self::MaterializedBytes,
269        Self::SortEntries,
270        Self::SortComparisons,
271        Self::SortTemporaryBytes,
272        Self::GroupDistinctEntries,
273        Self::GroupDistinctStateBytes,
274        Self::CursorSteps,
275        Self::TemporaryBytes,
276        Self::ResultRows,
277        Self::ResultBytes,
278        Self::InstructionUnits,
279    ];
280}
281
282define_numeric_fact_value_registry! {
283    /// Compact counter owner carried by [`DiagnosticFactTag::ExecutionBudgetScope`].
284    pub enum DiagnosticExecutionBudgetScope {
285        Execution = 1;
286        Request = 2;
287    }
288}
289
290define_numeric_fact_value_registry! {
291    /// Compact execution lane carried by [`DiagnosticFactTag::ExecutionLane`].
292    pub enum DiagnosticExecutionLane {
293        PublicRead = 1;
294        TrustedRead = 2;
295        Diagnostic = 3;
296        Mutation = 4;
297        Recovery = 5;
298    }
299}
300
301define_numeric_fact_value_registry! {
302    /// Compact accepted constraint family carried by [`DiagnosticFactTag::ConstraintKind`].
303    pub enum DiagnosticConstraintKind {
304        Check = 1;
305        NotNull = 2;
306        Relation = 3;
307        TargetedRule = 4;
308        Unique = 5;
309    }
310}
311
312define_numeric_fact_value_registry! {
313    /// Compact enforcement boundary carried by [`DiagnosticFactTag::ConstraintContext`].
314    pub enum DiagnosticConstraintContext {
315        Integrity = 1;
316        MigrationValidation = 2;
317        WriteAdmission = 3;
318    }
319}
320
321define_numeric_fact_value_registry! {
322    /// Compact storage component carried by [`DiagnosticFactTag::ComponentKind`].
323    pub enum DiagnosticComponentKind {
324        CommitDataKey = 1;
325        IndexKey = 2;
326        IndexKeyComponent = 3;
327        RelationTargetPrimaryKey = 4;
328    }
329}
330
331define_numeric_fact_value_registry! {
332    /// Compact semantic family carried by [`DiagnosticFactTag::TypeFamily`].
333    pub enum DiagnosticTypeFamily {
334        Blob = 1;
335        Bool = 2;
336        Collection = 3;
337        Null = 4;
338        Numeric = 5;
339        Opaque = 6;
340        Structured = 7;
341        Text = 8;
342        Unknown = 9;
343    }
344}
345
346define_numeric_fact_value_registry! {
347    /// Compact function identity carried by [`DiagnosticFactTag::FunctionKind`].
348    pub enum DiagnosticFunctionKind {
349        Abs = 1;
350        Cbrt = 2;
351        Ceiling = 3;
352        Coalesce = 4;
353        CollectionContains = 5;
354        Contains = 6;
355        EndsWith = 7;
356        Exp = 8;
357        Floor = 9;
358        IsEmpty = 10;
359        IsMissing = 11;
360        IsNotEmpty = 12;
361        IsNotNull = 13;
362        IsNull = 14;
363        Left = 15;
364        Length = 16;
365        Ln = 17;
366        Log = 18;
367        Log2 = 19;
368        Log10 = 20;
369        Lower = 21;
370        Ltrim = 22;
371        Mod = 23;
372        NullIf = 24;
373        OctetLength = 25;
374        Position = 26;
375        Power = 27;
376        Replace = 28;
377        Right = 29;
378        Round = 30;
379        Rtrim = 31;
380        Sign = 32;
381        Sqrt = 33;
382        StartsWith = 34;
383        Substring = 35;
384        Trim = 36;
385        Trunc = 37;
386        Upper = 38;
387        InList = 39;
388    }
389}
390
391define_numeric_fact_value_registry! {
392    /// Compact operator identity carried by [`DiagnosticFactTag::OperatorKind`].
393    pub enum DiagnosticOperatorKind {
394        Not = 1;
395        Add = 2;
396        And = 3;
397        Div = 4;
398        Eq = 5;
399        Gt = 6;
400        Gte = 7;
401        Lt = 8;
402        Lte = 9;
403        Mul = 10;
404        Ne = 11;
405        Or = 12;
406        Sub = 13;
407        In = 14;
408        NotIn = 15;
409        Contains = 16;
410        StartsWith = 17;
411        EndsWith = 18;
412    }
413}
414
415define_numeric_fact_value_registry! {
416    /// Compact aggregate identity carried by [`DiagnosticFactTag::AggregateKind`].
417    pub enum DiagnosticAggregateKind {
418        Count = 1;
419        Sum = 2;
420        Avg = 3;
421        Exists = 4;
422        Min = 5;
423        Max = 6;
424        First = 7;
425        Last = 8;
426    }
427}
428
429impl DiagnosticDecodeReason {
430    /// Return the fixed numeric fact value.
431    #[must_use]
432    pub const fn raw(self) -> u64 {
433        match self {
434            Self::CursorEmpty => 1,
435            Self::CursorTooLong => 2,
436            Self::CursorOddLength => 3,
437            Self::CursorInvalidHex => 4,
438            Self::CursorGroupedDirectionMismatch => 5,
439            Self::CursorTokenEncode => 6,
440            Self::CursorTokenDecode => 7,
441            Self::RecoveryMarkerMagic => 8,
442            Self::RecoveryMarkerChecksum => 9,
443            Self::RecoveryMarkerState => 10,
444        }
445    }
446
447    /// Recover a known compact decode reason.
448    #[must_use]
449    pub const fn known(raw: u64) -> Option<Self> {
450        match raw {
451            1 => Some(Self::CursorEmpty),
452            2 => Some(Self::CursorTooLong),
453            3 => Some(Self::CursorOddLength),
454            4 => Some(Self::CursorInvalidHex),
455            5 => Some(Self::CursorGroupedDirectionMismatch),
456            6 => Some(Self::CursorTokenEncode),
457            7 => Some(Self::CursorTokenDecode),
458            8 => Some(Self::RecoveryMarkerMagic),
459            9 => Some(Self::RecoveryMarkerChecksum),
460            10 => Some(Self::RecoveryMarkerState),
461            _ => None,
462        }
463    }
464}
465
466impl DiagnosticMutationOperation {
467    /// Return the fixed numeric fact value.
468    #[must_use]
469    pub const fn raw(self) -> u64 {
470        match self {
471            Self::Insert => 1,
472            Self::Replace => 2,
473            Self::Update => 3,
474            Self::Delete => 4,
475        }
476    }
477
478    /// Recover a known compact mutation operation.
479    #[must_use]
480    pub const fn known(raw: u64) -> Option<Self> {
481        match raw {
482            1 => Some(Self::Insert),
483            2 => Some(Self::Replace),
484            3 => Some(Self::Update),
485            4 => Some(Self::Delete),
486            _ => None,
487        }
488    }
489}
490
491impl fmt::Debug for DiagnosticFactTag {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        write!(f, "{}", self.raw())
494    }
495}
496
497impl fmt::Debug for DiagnosticDecodeReason {
498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499        write!(f, "{}", self.raw())
500    }
501}
502
503impl fmt::Debug for DiagnosticMutationOperation {
504    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505        write!(f, "{}", self.raw())
506    }
507}
508
509/// Pack two accepted `u32` identities into one fact value without narrowing.
510#[must_use]
511pub const fn pack_u32_pair(high: u32, low: u32) -> u64 {
512    (high as u64) << 32 | low as u64
513}
514
515/// Recover the two accepted identities from one packed fact value.
516#[must_use]
517pub const fn unpack_u32_pair(value: u64) -> (u32, u32) {
518    let bytes = value.to_be_bytes();
519    (
520        u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
521        u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
522    )
523}
524
525/// Why one numeric fact sequence does not satisfy its owning E-code schema.
526///
527/// This taxonomy intentionally carries no prose. Host tooling owns rendering.
528#[derive(Clone, Copy, Debug, Eq, PartialEq)]
529pub enum DiagnosticFactSchemaMismatch {
530    /// The sequence exceeds the global public fact ceiling.
531    GlobalMaximumExceeded,
532    /// The sequence exceeds the tighter ceiling for its E-code.
533    CodeMaximumExceeded,
534    /// Required, allowed, repeated, or ordered tags do not match the E-code.
535    InvalidSequence,
536    /// One known compact tag carries a value outside its frozen numeric registry.
537    InvalidValue,
538}
539
540/// Validate facts already expressed with known production tag identities.
541///
542/// The validator allocates nothing. It is the runtime-side entry point used
543/// immediately before facts cross the public facade.
544pub fn validate_known_diagnostic_fact_schema(
545    code: ErrorCode,
546    facts: &[(DiagnosticFactTag, u64)],
547) -> Result<(), DiagnosticFactSchemaMismatch> {
548    validate_diagnostic_fact_schema(code, facts.len(), |index| {
549        let (tag, value) = facts[index];
550        (tag.raw(), value)
551    })
552}
553
554/// Validate raw host/tooling facts against their owning E-code schema.
555///
556/// Unknown tags remain renderable by callers, but make a known E-code context
557/// invalid instead of being heuristically reinterpreted.
558pub fn validate_raw_diagnostic_fact_schema(
559    code: ErrorCode,
560    facts: &[(u8, u64)],
561) -> Result<(), DiagnosticFactSchemaMismatch> {
562    validate_diagnostic_fact_schema(code, facts.len(), |index| facts[index])
563}
564
565#[expect(
566    clippy::too_many_lines,
567    reason = "the frozen E-code schema registry keeps every numeric owner visible in one exhaustive dispatch"
568)]
569fn validate_diagnostic_fact_schema(
570    code: ErrorCode,
571    fact_count: usize,
572    fact_at: impl Fn(usize) -> (u8, u64),
573) -> Result<(), DiagnosticFactSchemaMismatch> {
574    if fact_count > MAX_PUBLIC_DIAGNOSTIC_FACTS {
575        return Err(DiagnosticFactSchemaMismatch::GlobalMaximumExceeded);
576    }
577
578    let maximum = diagnostic_fact_maximum(code);
579    if fact_count > maximum {
580        return Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded);
581    }
582
583    let valid_sequence = match code.raw() {
584        3 => query_plan_schema(fact_count, &fact_at),
585        5 => cursor_schema(fact_count, &fact_at),
586        15 => store_corruption_schema(fact_count, &fact_at),
587        17 => runtime_corruption_schema(fact_count, &fact_at),
588        18 => incompatible_format_schema(fact_count, &fact_at),
589        19 => runtime_invariant_schema(fact_count, &fact_at),
590        20 => runtime_conflict_schema(fact_count, &fact_at),
591        22 => runtime_unsupported_schema(fact_count, &fact_at),
592        23 => runtime_internal_schema(fact_count, &fact_at),
593        130 => tags_match(
594            fact_count,
595            &fact_at,
596            &[
597                DiagnosticFactTag::ExpectedArity,
598                DiagnosticFactTag::ActualArity,
599            ],
600        ),
601        133 | 134 | 158 | 159 => {
602            tags_match(fact_count, &fact_at, &[DiagnosticFactTag::ProjectionIndex])
603        }
604        164 => tags_match(fact_count, &fact_at, &[DiagnosticFactTag::ParameterIndex]),
605        166 | 224 => {
606            tags_match(fact_count, &fact_at, &[DiagnosticFactTag::Limit])
607                || tags_match(
608                    fact_count,
609                    &fact_at,
610                    &[DiagnosticFactTag::ActualLength, DiagnosticFactTag::Limit],
611                )
612        }
613        167 | 169 | 191 | 192 | 194 | 223 | 248 | 264 => tags_match(
614            fact_count,
615            &fact_at,
616            &[DiagnosticFactTag::ActualCount, DiagnosticFactTag::Limit],
617        ),
618        262 => {
619            tags_match(fact_count, &fact_at, &[DiagnosticFactTag::Limit])
620                || tags_match(
621                    fact_count,
622                    &fact_at,
623                    &[DiagnosticFactTag::ActualCount, DiagnosticFactTag::Limit],
624                )
625        }
626        263 => tags_match(
627            fact_count,
628            &fact_at,
629            &[
630                DiagnosticFactTag::BacklogResource,
631                DiagnosticFactTag::CurrentCount,
632                DiagnosticFactTag::ProposedCount,
633                DiagnosticFactTag::Limit,
634            ],
635        ),
636        185 | 221 => tags_match(
637            fact_count,
638            &fact_at,
639            &[
640                DiagnosticFactTag::EntityTag,
641                DiagnosticFactTag::FieldId,
642                DiagnosticFactTag::MutationOperation,
643                DiagnosticFactTag::BatchPosition,
644            ],
645        ),
646        186 => tags_match(
647            fact_count,
648            &fact_at,
649            &[
650                DiagnosticFactTag::RowLayout,
651                DiagnosticFactTag::HistoryFloor,
652                DiagnosticFactTag::CurrentLayout,
653            ],
654        ),
655        187 => tags_match(
656            fact_count,
657            &fact_at,
658            &[
659                DiagnosticFactTag::RowLayout,
660                DiagnosticFactTag::ExpectedSlotCount,
661                DiagnosticFactTag::ActualSlotCount,
662            ],
663        ),
664        190 => tags_match(
665            fact_count,
666            &fact_at,
667            &[DiagnosticFactTag::ActualCount, DiagnosticFactTag::Minimum],
668        ),
669        210 => constraint_schema(fact_count, &fact_at, true),
670        212 => constraint_schema(fact_count, &fact_at, false),
671        220 => tags_match(
672            fact_count,
673            &fact_at,
674            &[
675                DiagnosticFactTag::EntityTag,
676                DiagnosticFactTag::MutationOperation,
677                DiagnosticFactTag::BatchPosition,
678            ],
679        ),
680        222 => {
681            tags_match(fact_count, &fact_at, &[DiagnosticFactTag::ActualCount]) && fact_at(0).1 == 0
682        }
683        225 | 249 | 250 | 251 => tags_match(
684            fact_count,
685            &fact_at,
686            &[DiagnosticFactTag::ActualLength, DiagnosticFactTag::Limit],
687        ),
688        252 => tags_match(
689            fact_count,
690            &fact_at,
691            &[
692                DiagnosticFactTag::BudgetResource,
693                DiagnosticFactTag::Limit,
694                DiagnosticFactTag::Actual,
695                DiagnosticFactTag::ExecutionBudgetScope,
696                DiagnosticFactTag::ExecutionLane,
697                DiagnosticFactTag::QueryShapeFingerprintPrefix,
698            ],
699        ),
700        253 => tags_match(
701            fact_count,
702            &fact_at,
703            &[
704                DiagnosticFactTag::BudgetResource,
705                DiagnosticFactTag::Limit,
706                DiagnosticFactTag::Actual,
707            ],
708        ),
709        226 => tags_match(
710            fact_count,
711            &fact_at,
712            &[
713                DiagnosticFactTag::BatchPosition,
714                DiagnosticFactTag::ExpectedEntityTag,
715                DiagnosticFactTag::ActualEntityTag,
716            ],
717        ),
718        227 => tags_match(
719            fact_count,
720            &fact_at,
721            &[
722                DiagnosticFactTag::EntityTag,
723                DiagnosticFactTag::FirstBatchPosition,
724                DiagnosticFactTag::DuplicateBatchPosition,
725            ],
726        ),
727        _ => fact_count == 0,
728    };
729    if !valid_sequence {
730        return Err(DiagnosticFactSchemaMismatch::InvalidSequence);
731    }
732
733    for index in 0..fact_count {
734        let (raw_tag, value) = fact_at(index);
735        let Some(tag) = DiagnosticFactTag::known(raw_tag) else {
736            return Err(DiagnosticFactSchemaMismatch::InvalidSequence);
737        };
738        if !diagnostic_fact_value_is_valid(tag, value) {
739            return Err(DiagnosticFactSchemaMismatch::InvalidValue);
740        }
741    }
742    Ok(())
743}
744
745const fn diagnostic_fact_maximum(code: ErrorCode) -> usize {
746    match code.raw() {
747        5 | 15 | 17 | 23 | 186 | 187 | 220 | 226 | 227 | 253 => 3,
748        133 | 134 | 158 | 159 | 164 | 222 => 1,
749        18 | 20 | 130 | 166 | 167 | 169 | 190 | 191 | 192 | 194 | 223 | 224 | 225 | 248 | 249
750        | 250 | 251 | 262 | 264 => 2,
751        3 | 19 => 5,
752        22 | 252 => 6,
753        185 | 221 | 263 => 4,
754        210 => 73,
755        212 => 9,
756        _ => 0,
757    }
758}
759
760#[expect(
761    clippy::too_many_lines,
762    reason = "the query-plan E-code deliberately owns several exact finite fact sequences"
763)]
764fn query_plan_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
765    fact_count == 0
766        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::TermIndex])
767        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ComponentIndex])
768        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::GroupIndex])
769        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ClauseIndex])
770        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::AggregateIndex])
771        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::AggregateKind])
772        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ProjectionIndex])
773        || tags_match(
774            fact_count,
775            fact_at,
776            &[
777                DiagnosticFactTag::FirstTermIndex,
778                DiagnosticFactTag::DuplicateTermIndex,
779            ],
780        )
781        || tags_match(
782            fact_count,
783            fact_at,
784            &[
785                DiagnosticFactTag::ClauseIndex,
786                DiagnosticFactTag::OperatorKind,
787            ],
788        )
789        || tags_match(
790            fact_count,
791            fact_at,
792            &[
793                DiagnosticFactTag::AggregateIndex,
794                DiagnosticFactTag::AggregateKind,
795            ],
796        )
797        || tags_match(
798            fact_count,
799            fact_at,
800            &[
801                DiagnosticFactTag::AggregateKind,
802                DiagnosticFactTag::TypeFamily,
803            ],
804        )
805        || tags_match(
806            fact_count,
807            fact_at,
808            &[
809                DiagnosticFactTag::OperatorKind,
810                DiagnosticFactTag::TypeFamily,
811            ],
812        )
813        || tags_match(
814            fact_count,
815            fact_at,
816            &[
817                DiagnosticFactTag::BranchIndex,
818                DiagnosticFactTag::TypeFamily,
819            ],
820        )
821        || tags_match(
822            fact_count,
823            fact_at,
824            &[DiagnosticFactTag::TypeFamily, DiagnosticFactTag::TypeFamily],
825        )
826        || tags_match(
827            fact_count,
828            fact_at,
829            &[
830                DiagnosticFactTag::ClauseIndex,
831                DiagnosticFactTag::AggregateIndex,
832                DiagnosticFactTag::ActualCount,
833            ],
834        )
835        || tags_match(
836            fact_count,
837            fact_at,
838            &[
839                DiagnosticFactTag::FunctionKind,
840                DiagnosticFactTag::ExpectedArity,
841                DiagnosticFactTag::ActualArity,
842            ],
843        )
844        || tags_match(
845            fact_count,
846            fact_at,
847            &[
848                DiagnosticFactTag::FunctionKind,
849                DiagnosticFactTag::ArgumentIndex,
850                DiagnosticFactTag::TypeFamily,
851            ],
852        )
853        || tags_match(
854            fact_count,
855            fact_at,
856            &[
857                DiagnosticFactTag::OperatorKind,
858                DiagnosticFactTag::TypeFamily,
859                DiagnosticFactTag::TypeFamily,
860            ],
861        )
862        || tags_match(
863            fact_count,
864            fact_at,
865            &[
866                DiagnosticFactTag::BranchIndex,
867                DiagnosticFactTag::TypeFamily,
868                DiagnosticFactTag::TypeFamily,
869            ],
870        )
871        || tags_match(
872            fact_count,
873            fact_at,
874            &[
875                DiagnosticFactTag::TypeFamily,
876                DiagnosticFactTag::BranchIndex,
877                DiagnosticFactTag::TypeFamily,
878            ],
879        )
880        || tags_match(
881            fact_count,
882            fact_at,
883            &[
884                DiagnosticFactTag::BranchIndex,
885                DiagnosticFactTag::TypeFamily,
886                DiagnosticFactTag::BranchIndex,
887                DiagnosticFactTag::TypeFamily,
888            ],
889        )
890        || tags_match(
891            fact_count,
892            fact_at,
893            &[
894                DiagnosticFactTag::FunctionKind,
895                DiagnosticFactTag::ArgumentIndex,
896                DiagnosticFactTag::TypeFamily,
897                DiagnosticFactTag::ArgumentIndex,
898                DiagnosticFactTag::TypeFamily,
899            ],
900        )
901}
902
903fn cursor_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
904    if fact_count == 0 {
905        return true;
906    }
907    if tags_match(fact_count, fact_at, &[DiagnosticFactTag::DecodeReason]) {
908        return matches!(fact_at(0).1, 1 | 3 | 5 | 6 | 7);
909    }
910    if tags_match(
911        fact_count,
912        fact_at,
913        &[
914            DiagnosticFactTag::ActualLength,
915            DiagnosticFactTag::Maximum,
916            DiagnosticFactTag::DecodeReason,
917        ],
918    ) {
919        return fact_at(2).1 == DiagnosticDecodeReason::CursorTooLong.raw();
920    }
921    if tags_match(
922        fact_count,
923        fact_at,
924        &[
925            DiagnosticFactTag::ComponentIndex,
926            DiagnosticFactTag::DecodeReason,
927        ],
928    ) {
929        return matches!(fact_at(1).1, 4 | 6 | 7);
930    }
931    tags_match(
932        fact_count,
933        fact_at,
934        &[
935            DiagnosticFactTag::ExpectedSignaturePrefix,
936            DiagnosticFactTag::ActualSignaturePrefix,
937        ],
938    ) || tags_match(
939        fact_count,
940        fact_at,
941        &[
942            DiagnosticFactTag::ExpectedOffset,
943            DiagnosticFactTag::ActualOffset,
944        ],
945    )
946}
947
948fn store_corruption_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
949    fact_count == 0
950        || (tags_match(
951            fact_count,
952            fact_at,
953            &[
954                DiagnosticFactTag::ComponentKind,
955                DiagnosticFactTag::ActualLength,
956                DiagnosticFactTag::Limit,
957            ],
958        ) && fact_at(0).1 == DiagnosticComponentKind::CommitDataKey.raw())
959        || tags_match(
960            fact_count,
961            fact_at,
962            &[
963                DiagnosticFactTag::ExpectedEntityTag,
964                DiagnosticFactTag::ActualEntityTag,
965            ],
966        )
967}
968
969fn runtime_corruption_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
970    store_corruption_schema(fact_count, fact_at)
971        || (tags_match(fact_count, fact_at, &[DiagnosticFactTag::DecodeReason])
972            && matches!(fact_at(0).1, 8..=10))
973}
974
975fn incompatible_format_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
976    fact_count == 0
977        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ExpectedVersion])
978        || tags_match(
979            fact_count,
980            fact_at,
981            &[
982                DiagnosticFactTag::ExpectedVersion,
983                DiagnosticFactTag::ActualVersion,
984            ],
985        )
986}
987
988fn runtime_invariant_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
989    fact_count == 0
990        || (tags_match(
991            fact_count,
992            fact_at,
993            &[
994                DiagnosticFactTag::EntityTag,
995                DiagnosticFactTag::PhysicalGeneration,
996                DiagnosticFactTag::ComponentKind,
997                DiagnosticFactTag::ActualArity,
998                DiagnosticFactTag::Maximum,
999            ],
1000        ) && fact_at(2).1 == DiagnosticComponentKind::IndexKey.raw())
1001}
1002
1003fn runtime_conflict_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
1004    fact_count == 0
1005        || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ExpectedRevision])
1006        || tags_match(
1007            fact_count,
1008            fact_at,
1009            &[
1010                DiagnosticFactTag::ExpectedRevision,
1011                DiagnosticFactTag::CurrentRevision,
1012            ],
1013        )
1014}
1015
1016fn runtime_unsupported_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
1017    fact_count == 0
1018        || (tags_match(
1019            fact_count,
1020            fact_at,
1021            &[
1022                DiagnosticFactTag::EntityTag,
1023                DiagnosticFactTag::PhysicalGeneration,
1024                DiagnosticFactTag::ComponentIndex,
1025                DiagnosticFactTag::ComponentKind,
1026                DiagnosticFactTag::ActualLength,
1027                DiagnosticFactTag::Limit,
1028            ],
1029        ) && fact_at(3).1 == DiagnosticComponentKind::IndexKeyComponent.raw())
1030}
1031
1032fn runtime_internal_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
1033    fact_count == 0
1034        || tags_match(
1035            fact_count,
1036            fact_at,
1037            &[
1038                DiagnosticFactTag::ExpectedMemoryId,
1039                DiagnosticFactTag::ActualMemoryId,
1040            ],
1041        )
1042        || (tags_match(
1043            fact_count,
1044            fact_at,
1045            &[
1046                DiagnosticFactTag::ComponentKind,
1047                DiagnosticFactTag::ExpectedArity,
1048                DiagnosticFactTag::ActualArity,
1049            ],
1050        ) && fact_at(0).1 == DiagnosticComponentKind::RelationTargetPrimaryKey.raw())
1051}
1052
1053fn constraint_schema(
1054    fact_count: usize,
1055    fact_at: &impl Fn(usize) -> (u8, u64),
1056    allow_targeted_path: bool,
1057) -> bool {
1058    const COMMON: &[DiagnosticFactTag] = &[
1059        DiagnosticFactTag::AcceptedSchemaFingerprintMethod,
1060        DiagnosticFactTag::AcceptedSchemaFingerprintHigh,
1061        DiagnosticFactTag::AcceptedSchemaFingerprintLow,
1062        DiagnosticFactTag::EntityTag,
1063        DiagnosticFactTag::ConstraintId,
1064        DiagnosticFactTag::ConstraintKind,
1065        DiagnosticFactTag::ConstraintContext,
1066    ];
1067    if fact_count < COMMON.len()
1068        || !tags_prefix_matches(fact_count, fact_at, COMMON)
1069        || fact_at(6).1 != DiagnosticConstraintContext::WriteAdmission.raw()
1070    {
1071        return false;
1072    }
1073
1074    let constraint_kind = fact_at(5).1;
1075    if DiagnosticConstraintKind::known(constraint_kind).is_none() {
1076        return false;
1077    }
1078    let mut index = COMMON.len();
1079    if index < fact_count && fact_at(index).0 == DiagnosticFactTag::MutationOperation.raw() {
1080        index += 1;
1081        if index < fact_count && fact_at(index).0 == DiagnosticFactTag::BatchPosition.raw() {
1082            index += 1;
1083        }
1084    }
1085
1086    let path_len = fact_count - index;
1087    if path_len == 0 {
1088        return !allow_targeted_path
1089            || constraint_kind != DiagnosticConstraintKind::TargetedRule.raw();
1090    }
1091    allow_targeted_path
1092        && constraint_kind == DiagnosticConstraintKind::TargetedRule.raw()
1093        && path_len <= 64
1094        && (index..fact_count).all(|position| {
1095            DiagnosticFactTag::known(fact_at(position).0).is_some_and(is_value_path_tag)
1096        })
1097}
1098
1099fn tags_match(
1100    fact_count: usize,
1101    fact_at: &impl Fn(usize) -> (u8, u64),
1102    expected: &[DiagnosticFactTag],
1103) -> bool {
1104    fact_count == expected.len() && tags_prefix_matches(fact_count, fact_at, expected)
1105}
1106
1107fn tags_prefix_matches(
1108    fact_count: usize,
1109    fact_at: &impl Fn(usize) -> (u8, u64),
1110    expected: &[DiagnosticFactTag],
1111) -> bool {
1112    fact_count >= expected.len()
1113        && expected
1114            .iter()
1115            .enumerate()
1116            .all(|(index, tag)| fact_at(index).0 == tag.raw())
1117}
1118
1119const fn is_value_path_tag(tag: DiagnosticFactTag) -> bool {
1120    matches!(
1121        tag,
1122        DiagnosticFactTag::RootField
1123            | DiagnosticFactTag::RecordMember
1124            | DiagnosticFactTag::TupleElement
1125            | DiagnosticFactTag::Newtype
1126            | DiagnosticFactTag::EnumVariant
1127            | DiagnosticFactTag::ListElement
1128            | DiagnosticFactTag::SetElement
1129            | DiagnosticFactTag::MapEntryKey
1130            | DiagnosticFactTag::MapEntryValue
1131    )
1132}
1133
1134const fn diagnostic_fact_value_is_valid(tag: DiagnosticFactTag, value: u64) -> bool {
1135    match tag {
1136        DiagnosticFactTag::AcceptedSchemaFingerprintMethod
1137        | DiagnosticFactTag::ExpectedMemoryId
1138        | DiagnosticFactTag::ActualMemoryId => value <= u8::MAX as u64,
1139        DiagnosticFactTag::ConstraintId
1140        | DiagnosticFactTag::FieldId
1141        | DiagnosticFactTag::IndexId
1142        | DiagnosticFactTag::RelationId
1143        | DiagnosticFactTag::BatchPosition
1144        | DiagnosticFactTag::FirstBatchPosition
1145        | DiagnosticFactTag::DuplicateBatchPosition
1146        | DiagnosticFactTag::RowLayout
1147        | DiagnosticFactTag::HistoryFloor
1148        | DiagnosticFactTag::CurrentLayout
1149        | DiagnosticFactTag::RootField
1150        | DiagnosticFactTag::Newtype
1151        | DiagnosticFactTag::ListElement
1152        | DiagnosticFactTag::SetElement
1153        | DiagnosticFactTag::MapEntryKey
1154        | DiagnosticFactTag::MapEntryValue => value <= u32::MAX as u64,
1155        DiagnosticFactTag::ConstraintKind => DiagnosticConstraintKind::known(value).is_some(),
1156        DiagnosticFactTag::BacklogResource => DiagnosticBacklogResource::known(value).is_some(),
1157        DiagnosticFactTag::ConstraintContext => DiagnosticConstraintContext::known(value).is_some(),
1158        DiagnosticFactTag::TypeFamily => DiagnosticTypeFamily::known(value).is_some(),
1159        DiagnosticFactTag::FunctionKind => DiagnosticFunctionKind::known(value).is_some(),
1160        DiagnosticFactTag::OperatorKind => DiagnosticOperatorKind::known(value).is_some(),
1161        DiagnosticFactTag::AggregateKind => DiagnosticAggregateKind::known(value).is_some(),
1162        DiagnosticFactTag::ComponentKind => DiagnosticComponentKind::known(value).is_some(),
1163        DiagnosticFactTag::DecodeReason => DiagnosticDecodeReason::known(value).is_some(),
1164        DiagnosticFactTag::BudgetResource => {
1165            DiagnosticExecutionBudgetResource::known(value).is_some()
1166        }
1167        DiagnosticFactTag::ExecutionBudgetScope => {
1168            DiagnosticExecutionBudgetScope::known(value).is_some()
1169        }
1170        DiagnosticFactTag::ExecutionLane => DiagnosticExecutionLane::known(value).is_some(),
1171        DiagnosticFactTag::MutationOperation => DiagnosticMutationOperation::known(value).is_some(),
1172        _ => true,
1173    }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178    use super::{
1179        DiagnosticAggregateKind, DiagnosticBacklogResource, DiagnosticComponentKind,
1180        DiagnosticConstraintContext, DiagnosticConstraintKind, DiagnosticDecodeReason,
1181        DiagnosticExecutionBudgetResource, DiagnosticExecutionBudgetScope, DiagnosticExecutionLane,
1182        DiagnosticFactSchemaMismatch, DiagnosticFactTag, DiagnosticFunctionKind,
1183        DiagnosticMutationOperation, DiagnosticOperatorKind, DiagnosticTypeFamily,
1184        ORDERED_FACT_TAGS, pack_u32_pair, unpack_u32_pair, validate_known_diagnostic_fact_schema,
1185        validate_raw_diagnostic_fact_schema,
1186    };
1187    use crate::ErrorCode;
1188
1189    #[test]
1190    fn fact_tag_registry_is_fixed_unique_and_contiguous() {
1191        for (index, tag) in ORDERED_FACT_TAGS.iter().copied().enumerate() {
1192            let expected = u8::try_from(index + 1).expect("fact-tag index fits u8");
1193            assert_eq!(tag.raw(), expected);
1194            assert_eq!(DiagnosticFactTag::known(expected), Some(tag));
1195        }
1196
1197        assert_eq!(DiagnosticFactTag::known(0), None);
1198        assert_eq!(DiagnosticFactTag::known(96), None);
1199        assert_eq!(DiagnosticFactTag::known(u8::MAX), None);
1200    }
1201
1202    #[test]
1203    fn execution_budget_fact_value_registries_are_fixed() {
1204        assert_eq!(DiagnosticBacklogResource::Batches.raw(), 1);
1205        assert_eq!(DiagnosticBacklogResource::Records.raw(), 2);
1206        assert_eq!(DiagnosticBacklogResource::EncodedBytes.raw(), 3);
1207        assert_eq!(DiagnosticBacklogResource::known(4), None);
1208
1209        for (index, resource) in DiagnosticExecutionBudgetResource::ALL
1210            .iter()
1211            .copied()
1212            .enumerate()
1213        {
1214            let expected = u64::try_from(index + 1).expect("resource index fits u64");
1215            assert_eq!(resource.raw(), expected);
1216            assert_eq!(
1217                DiagnosticExecutionBudgetResource::known(expected),
1218                Some(resource)
1219            );
1220        }
1221        assert_eq!(DiagnosticExecutionBudgetResource::known(0), None);
1222        assert_eq!(DiagnosticExecutionBudgetResource::known(21), None);
1223
1224        assert_eq!(DiagnosticExecutionBudgetScope::Execution.raw(), 1);
1225        assert_eq!(DiagnosticExecutionBudgetScope::Request.raw(), 2);
1226        assert_eq!(DiagnosticExecutionBudgetScope::known(3), None);
1227
1228        assert_eq!(DiagnosticExecutionLane::PublicRead.raw(), 1);
1229        assert_eq!(DiagnosticExecutionLane::TrustedRead.raw(), 2);
1230        assert_eq!(DiagnosticExecutionLane::Diagnostic.raw(), 3);
1231        assert_eq!(DiagnosticExecutionLane::Mutation.raw(), 4);
1232        assert_eq!(DiagnosticExecutionLane::Recovery.raw(), 5);
1233        assert_eq!(DiagnosticExecutionLane::known(6), None);
1234    }
1235
1236    #[test]
1237    fn accepted_identity_pair_packing_is_exact() {
1238        for pair in [
1239            (0, 0),
1240            (1, 2),
1241            (u32::MAX, 0),
1242            (0, u32::MAX),
1243            (u32::MAX, u32::MAX),
1244        ] {
1245            assert_eq!(unpack_u32_pair(pack_u32_pair(pair.0, pair.1)), pair);
1246        }
1247    }
1248
1249    #[test]
1250    fn constraint_fact_value_registries_are_fixed() {
1251        assert_eq!(DiagnosticConstraintKind::Check.raw(), 1);
1252        assert_eq!(DiagnosticConstraintKind::NotNull.raw(), 2);
1253        assert_eq!(DiagnosticConstraintKind::Relation.raw(), 3);
1254        assert_eq!(DiagnosticConstraintKind::TargetedRule.raw(), 4);
1255        assert_eq!(DiagnosticConstraintKind::Unique.raw(), 5);
1256        assert_eq!(DiagnosticConstraintKind::known(0), None);
1257        assert_eq!(DiagnosticConstraintKind::known(6), None);
1258
1259        assert_eq!(DiagnosticConstraintContext::Integrity.raw(), 1);
1260        assert_eq!(DiagnosticConstraintContext::MigrationValidation.raw(), 2);
1261        assert_eq!(DiagnosticConstraintContext::WriteAdmission.raw(), 3);
1262        assert_eq!(DiagnosticConstraintContext::known(0), None);
1263        assert_eq!(DiagnosticConstraintContext::known(4), None);
1264    }
1265
1266    #[test]
1267    fn component_kind_registry_is_fixed_and_numeric() {
1268        let kinds = [
1269            DiagnosticComponentKind::CommitDataKey,
1270            DiagnosticComponentKind::IndexKey,
1271            DiagnosticComponentKind::IndexKeyComponent,
1272            DiagnosticComponentKind::RelationTargetPrimaryKey,
1273        ];
1274
1275        for (index, kind) in kinds.iter().copied().enumerate() {
1276            let expected = (index + 1) as u64;
1277            assert_eq!(kind.raw(), expected);
1278            assert_eq!(DiagnosticComponentKind::known(expected), Some(kind));
1279            assert_eq!(format!("{kind:?}"), expected.to_string());
1280        }
1281        assert_eq!(DiagnosticComponentKind::known(0), None);
1282        assert_eq!(DiagnosticComponentKind::known(5), None);
1283    }
1284
1285    #[test]
1286    fn decode_reason_registry_is_fixed_and_numeric() {
1287        let reasons = [
1288            DiagnosticDecodeReason::CursorEmpty,
1289            DiagnosticDecodeReason::CursorTooLong,
1290            DiagnosticDecodeReason::CursorOddLength,
1291            DiagnosticDecodeReason::CursorInvalidHex,
1292            DiagnosticDecodeReason::CursorGroupedDirectionMismatch,
1293            DiagnosticDecodeReason::CursorTokenEncode,
1294            DiagnosticDecodeReason::CursorTokenDecode,
1295            DiagnosticDecodeReason::RecoveryMarkerMagic,
1296            DiagnosticDecodeReason::RecoveryMarkerChecksum,
1297            DiagnosticDecodeReason::RecoveryMarkerState,
1298        ];
1299
1300        for (index, reason) in reasons.iter().copied().enumerate() {
1301            let expected = (index + 1) as u64;
1302            assert_eq!(reason.raw(), expected);
1303            assert_eq!(DiagnosticDecodeReason::known(expected), Some(reason));
1304            assert_eq!(format!("{reason:?}"), expected.to_string());
1305        }
1306
1307        assert_eq!(DiagnosticDecodeReason::known(0), None);
1308        assert_eq!(DiagnosticDecodeReason::known(11), None);
1309    }
1310
1311    #[test]
1312    fn mutation_operation_registry_is_fixed_and_numeric() {
1313        let operations = [
1314            DiagnosticMutationOperation::Insert,
1315            DiagnosticMutationOperation::Replace,
1316            DiagnosticMutationOperation::Update,
1317            DiagnosticMutationOperation::Delete,
1318        ];
1319
1320        for (index, operation) in operations.iter().copied().enumerate() {
1321            let expected = (index + 1) as u64;
1322            assert_eq!(operation.raw(), expected);
1323            assert_eq!(
1324                DiagnosticMutationOperation::known(expected),
1325                Some(operation)
1326            );
1327            assert_eq!(format!("{operation:?}"), expected.to_string());
1328        }
1329
1330        assert_eq!(DiagnosticMutationOperation::known(0), None);
1331        assert_eq!(DiagnosticMutationOperation::known(5), None);
1332    }
1333
1334    #[test]
1335    fn query_kind_registries_are_fixed_contiguous_and_numeric() {
1336        for raw in 1..=9 {
1337            let value = DiagnosticTypeFamily::known(raw).expect("type family should be known");
1338            assert_eq!(value.raw(), raw);
1339            assert_eq!(format!("{value:?}"), raw.to_string());
1340        }
1341        assert_eq!(DiagnosticTypeFamily::known(0), None);
1342        assert_eq!(DiagnosticTypeFamily::known(10), None);
1343
1344        for raw in 1..=39 {
1345            let value = DiagnosticFunctionKind::known(raw).expect("function kind should be known");
1346            assert_eq!(value.raw(), raw);
1347            assert_eq!(format!("{value:?}"), raw.to_string());
1348        }
1349        assert_eq!(DiagnosticFunctionKind::known(0), None);
1350        assert_eq!(DiagnosticFunctionKind::known(40), None);
1351
1352        for raw in 1..=18 {
1353            let value = DiagnosticOperatorKind::known(raw).expect("operator kind should be known");
1354            assert_eq!(value.raw(), raw);
1355            assert_eq!(format!("{value:?}"), raw.to_string());
1356        }
1357        assert_eq!(DiagnosticOperatorKind::known(0), None);
1358        assert_eq!(DiagnosticOperatorKind::known(19), None);
1359
1360        for raw in 1..=8 {
1361            let value =
1362                DiagnosticAggregateKind::known(raw).expect("aggregate kind should be known");
1363            assert_eq!(value.raw(), raw);
1364            assert_eq!(format!("{value:?}"), raw.to_string());
1365        }
1366        assert_eq!(DiagnosticAggregateKind::known(0), None);
1367        assert_eq!(DiagnosticAggregateKind::known(9), None);
1368    }
1369
1370    #[test]
1371    fn per_code_schema_rejects_missing_disallowed_and_noncanonical_tags() {
1372        let valid = [
1373            (DiagnosticFactTag::ActualCount, 5),
1374            (DiagnosticFactTag::Limit, 4),
1375        ];
1376        assert_eq!(
1377            validate_known_diagnostic_fact_schema(
1378                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1379                &valid,
1380            ),
1381            Ok(())
1382        );
1383        assert_eq!(
1384            validate_known_diagnostic_fact_schema(
1385                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1386                &valid[..1],
1387            ),
1388            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1389        );
1390        assert_eq!(
1391            validate_known_diagnostic_fact_schema(
1392                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1393                &[valid[1], valid[0]],
1394            ),
1395            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1396        );
1397        assert_eq!(
1398            validate_known_diagnostic_fact_schema(ErrorCode::QUERY_VALIDATE, &valid),
1399            Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded)
1400        );
1401
1402        assert_eq!(
1403            validate_known_diagnostic_fact_schema(
1404                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_COMMIT_WORK_EXCEEDED,
1405                &valid,
1406            ),
1407            Ok(())
1408        );
1409        assert_eq!(
1410            validate_known_diagnostic_fact_schema(
1411                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_COMMIT_WORK_EXCEEDED,
1412                &valid[1..],
1413            ),
1414            Ok(())
1415        );
1416    }
1417
1418    #[test]
1419    fn execution_budget_schema_requires_complete_typed_attribution() {
1420        let valid = [
1421            (
1422                DiagnosticFactTag::BudgetResource,
1423                DiagnosticExecutionBudgetResource::StoredBytesRead.raw(),
1424            ),
1425            (DiagnosticFactTag::Limit, 4_096),
1426            (DiagnosticFactTag::Actual, 4_097),
1427            (
1428                DiagnosticFactTag::ExecutionBudgetScope,
1429                DiagnosticExecutionBudgetScope::Request.raw(),
1430            ),
1431            (
1432                DiagnosticFactTag::ExecutionLane,
1433                DiagnosticExecutionLane::TrustedRead.raw(),
1434            ),
1435            (DiagnosticFactTag::QueryShapeFingerprintPrefix, 17),
1436        ];
1437        assert_eq!(
1438            validate_known_diagnostic_fact_schema(
1439                ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1440                &valid,
1441            ),
1442            Ok(())
1443        );
1444        assert_eq!(
1445            validate_known_diagnostic_fact_schema(
1446                ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1447                &valid[..5],
1448            ),
1449            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1450        );
1451
1452        let mut invalid_resource = valid;
1453        invalid_resource[0].1 = 0;
1454        assert_eq!(
1455            validate_known_diagnostic_fact_schema(
1456                ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1457                &invalid_resource,
1458            ),
1459            Err(DiagnosticFactSchemaMismatch::InvalidValue)
1460        );
1461    }
1462
1463    #[test]
1464    fn raw_schema_keeps_unknown_context_numeric_but_marks_it_invalid() {
1465        assert_eq!(
1466            validate_raw_diagnostic_fact_schema(
1467                ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR,
1468                &[(u8::MAX, 17)],
1469            ),
1470            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1471        );
1472        assert_eq!(
1473            validate_raw_diagnostic_fact_schema(
1474                ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR,
1475                &[(DiagnosticFactTag::DecodeReason.raw(), u64::MAX)],
1476            ),
1477            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1478        );
1479    }
1480
1481    #[test]
1482    fn constraint_schema_enforces_authority_operation_and_bounded_path_suffix() {
1483        let mut targeted = vec![
1484            (DiagnosticFactTag::AcceptedSchemaFingerprintMethod, 1),
1485            (DiagnosticFactTag::AcceptedSchemaFingerprintHigh, 2),
1486            (DiagnosticFactTag::AcceptedSchemaFingerprintLow, 3),
1487            (DiagnosticFactTag::EntityTag, 17),
1488            (DiagnosticFactTag::ConstraintId, 4),
1489            (
1490                DiagnosticFactTag::ConstraintKind,
1491                DiagnosticConstraintKind::TargetedRule.raw(),
1492            ),
1493            (
1494                DiagnosticFactTag::ConstraintContext,
1495                DiagnosticConstraintContext::WriteAdmission.raw(),
1496            ),
1497            (
1498                DiagnosticFactTag::MutationOperation,
1499                DiagnosticMutationOperation::Insert.raw(),
1500            ),
1501            (DiagnosticFactTag::BatchPosition, 0),
1502        ];
1503        targeted.extend((0..64).map(|index| (DiagnosticFactTag::ListElement, index)));
1504        assert_eq!(targeted.len(), 73);
1505        assert_eq!(
1506            validate_known_diagnostic_fact_schema(
1507                ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1508                targeted.as_slice(),
1509            ),
1510            Ok(())
1511        );
1512
1513        let mut overlong = targeted.clone();
1514        overlong.push((DiagnosticFactTag::ListElement, 64));
1515        assert_eq!(
1516            validate_known_diagnostic_fact_schema(
1517                ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1518                overlong.as_slice(),
1519            ),
1520            Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded)
1521        );
1522
1523        let mut non_targeted_path = targeted;
1524        non_targeted_path[5].1 = DiagnosticConstraintKind::Unique.raw();
1525        assert_eq!(
1526            validate_known_diagnostic_fact_schema(
1527                ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1528                non_targeted_path.as_slice(),
1529            ),
1530            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1531        );
1532    }
1533
1534    #[test]
1535    fn schema_enforces_global_ceiling_before_per_code_ceiling() {
1536        let facts = vec![(DiagnosticFactTag::ActualCount.raw(), 0); 81];
1537        assert_eq!(
1538            validate_raw_diagnostic_fact_schema(ErrorCode::QUERY_PLAN, facts.as_slice()),
1539            Err(DiagnosticFactSchemaMismatch::GlobalMaximumExceeded)
1540        );
1541    }
1542}