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 | 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 | 23 => 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    // Accepted relation compilation adds source identity ahead of the existing
1034    // bounded cause facts; identity must not hide or relax the cause schema.
1035    if fact_count >= 2
1036        && fact_at(0).0 == DiagnosticFactTag::EntityTag.raw()
1037        && fact_at(1).0 == DiagnosticFactTag::RelationId.raw()
1038    {
1039        return runtime_internal_detail_schema(fact_count - 2, &|index| fact_at(index + 2));
1040    }
1041    runtime_internal_detail_schema(fact_count, fact_at)
1042}
1043
1044fn runtime_internal_detail_schema(
1045    fact_count: usize,
1046    fact_at: &impl Fn(usize) -> (u8, u64),
1047) -> bool {
1048    fact_count == 0
1049        || tags_match(
1050            fact_count,
1051            fact_at,
1052            &[
1053                DiagnosticFactTag::ExpectedMemoryId,
1054                DiagnosticFactTag::ActualMemoryId,
1055            ],
1056        )
1057        || (tags_match(
1058            fact_count,
1059            fact_at,
1060            &[
1061                DiagnosticFactTag::ComponentKind,
1062                DiagnosticFactTag::ExpectedArity,
1063                DiagnosticFactTag::ActualArity,
1064            ],
1065        ) && fact_at(0).1 == DiagnosticComponentKind::RelationTargetPrimaryKey.raw())
1066}
1067
1068fn constraint_schema(
1069    fact_count: usize,
1070    fact_at: &impl Fn(usize) -> (u8, u64),
1071    allow_targeted_path: bool,
1072) -> bool {
1073    const COMMON: &[DiagnosticFactTag] = &[
1074        DiagnosticFactTag::AcceptedSchemaFingerprintMethod,
1075        DiagnosticFactTag::AcceptedSchemaFingerprintHigh,
1076        DiagnosticFactTag::AcceptedSchemaFingerprintLow,
1077        DiagnosticFactTag::EntityTag,
1078        DiagnosticFactTag::ConstraintId,
1079        DiagnosticFactTag::ConstraintKind,
1080        DiagnosticFactTag::ConstraintContext,
1081    ];
1082    if fact_count < COMMON.len()
1083        || !tags_prefix_matches(fact_count, fact_at, COMMON)
1084        || fact_at(6).1 != DiagnosticConstraintContext::WriteAdmission.raw()
1085    {
1086        return false;
1087    }
1088
1089    let constraint_kind = fact_at(5).1;
1090    if DiagnosticConstraintKind::known(constraint_kind).is_none() {
1091        return false;
1092    }
1093    let mut index = COMMON.len();
1094    if index < fact_count && fact_at(index).0 == DiagnosticFactTag::MutationOperation.raw() {
1095        index += 1;
1096        if index < fact_count && fact_at(index).0 == DiagnosticFactTag::BatchPosition.raw() {
1097            index += 1;
1098        }
1099    }
1100
1101    let path_len = fact_count - index;
1102    if path_len == 0 {
1103        return !allow_targeted_path
1104            || constraint_kind != DiagnosticConstraintKind::TargetedRule.raw();
1105    }
1106    allow_targeted_path
1107        && constraint_kind == DiagnosticConstraintKind::TargetedRule.raw()
1108        && path_len <= 64
1109        && (index..fact_count).all(|position| {
1110            DiagnosticFactTag::known(fact_at(position).0).is_some_and(is_value_path_tag)
1111        })
1112}
1113
1114fn tags_match(
1115    fact_count: usize,
1116    fact_at: &impl Fn(usize) -> (u8, u64),
1117    expected: &[DiagnosticFactTag],
1118) -> bool {
1119    fact_count == expected.len() && tags_prefix_matches(fact_count, fact_at, expected)
1120}
1121
1122fn tags_prefix_matches(
1123    fact_count: usize,
1124    fact_at: &impl Fn(usize) -> (u8, u64),
1125    expected: &[DiagnosticFactTag],
1126) -> bool {
1127    fact_count >= expected.len()
1128        && expected
1129            .iter()
1130            .enumerate()
1131            .all(|(index, tag)| fact_at(index).0 == tag.raw())
1132}
1133
1134const fn is_value_path_tag(tag: DiagnosticFactTag) -> bool {
1135    matches!(
1136        tag,
1137        DiagnosticFactTag::RootField
1138            | DiagnosticFactTag::RecordMember
1139            | DiagnosticFactTag::TupleElement
1140            | DiagnosticFactTag::Newtype
1141            | DiagnosticFactTag::EnumVariant
1142            | DiagnosticFactTag::ListElement
1143            | DiagnosticFactTag::SetElement
1144            | DiagnosticFactTag::MapEntryKey
1145            | DiagnosticFactTag::MapEntryValue
1146    )
1147}
1148
1149const fn diagnostic_fact_value_is_valid(tag: DiagnosticFactTag, value: u64) -> bool {
1150    match tag {
1151        DiagnosticFactTag::AcceptedSchemaFingerprintMethod
1152        | DiagnosticFactTag::ExpectedMemoryId
1153        | DiagnosticFactTag::ActualMemoryId => value <= u8::MAX as u64,
1154        DiagnosticFactTag::ConstraintId
1155        | DiagnosticFactTag::FieldId
1156        | DiagnosticFactTag::IndexId
1157        | DiagnosticFactTag::RelationId
1158        | DiagnosticFactTag::BatchPosition
1159        | DiagnosticFactTag::FirstBatchPosition
1160        | DiagnosticFactTag::DuplicateBatchPosition
1161        | DiagnosticFactTag::RowLayout
1162        | DiagnosticFactTag::HistoryFloor
1163        | DiagnosticFactTag::CurrentLayout
1164        | DiagnosticFactTag::RootField
1165        | DiagnosticFactTag::Newtype
1166        | DiagnosticFactTag::ListElement
1167        | DiagnosticFactTag::SetElement
1168        | DiagnosticFactTag::MapEntryKey
1169        | DiagnosticFactTag::MapEntryValue => value <= u32::MAX as u64,
1170        DiagnosticFactTag::ConstraintKind => DiagnosticConstraintKind::known(value).is_some(),
1171        DiagnosticFactTag::BacklogResource => DiagnosticBacklogResource::known(value).is_some(),
1172        DiagnosticFactTag::ConstraintContext => DiagnosticConstraintContext::known(value).is_some(),
1173        DiagnosticFactTag::TypeFamily => DiagnosticTypeFamily::known(value).is_some(),
1174        DiagnosticFactTag::FunctionKind => DiagnosticFunctionKind::known(value).is_some(),
1175        DiagnosticFactTag::OperatorKind => DiagnosticOperatorKind::known(value).is_some(),
1176        DiagnosticFactTag::AggregateKind => DiagnosticAggregateKind::known(value).is_some(),
1177        DiagnosticFactTag::ComponentKind => DiagnosticComponentKind::known(value).is_some(),
1178        DiagnosticFactTag::DecodeReason => DiagnosticDecodeReason::known(value).is_some(),
1179        DiagnosticFactTag::BudgetResource => {
1180            DiagnosticExecutionBudgetResource::known(value).is_some()
1181        }
1182        DiagnosticFactTag::ExecutionBudgetScope => {
1183            DiagnosticExecutionBudgetScope::known(value).is_some()
1184        }
1185        DiagnosticFactTag::ExecutionLane => DiagnosticExecutionLane::known(value).is_some(),
1186        DiagnosticFactTag::MutationOperation => DiagnosticMutationOperation::known(value).is_some(),
1187        _ => true,
1188    }
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193    use super::{
1194        DiagnosticAggregateKind, DiagnosticBacklogResource, DiagnosticComponentKind,
1195        DiagnosticConstraintContext, DiagnosticConstraintKind, DiagnosticDecodeReason,
1196        DiagnosticExecutionBudgetResource, DiagnosticExecutionBudgetScope, DiagnosticExecutionLane,
1197        DiagnosticFactSchemaMismatch, DiagnosticFactTag, DiagnosticFunctionKind,
1198        DiagnosticMutationOperation, DiagnosticOperatorKind, DiagnosticTypeFamily,
1199        ORDERED_FACT_TAGS, pack_u32_pair, unpack_u32_pair, validate_known_diagnostic_fact_schema,
1200        validate_raw_diagnostic_fact_schema,
1201    };
1202    use crate::ErrorCode;
1203
1204    #[test]
1205    fn fact_tag_registry_is_fixed_unique_and_contiguous() {
1206        for (index, tag) in ORDERED_FACT_TAGS.iter().copied().enumerate() {
1207            let expected = u8::try_from(index + 1).expect("fact-tag index fits u8");
1208            assert_eq!(tag.raw(), expected);
1209            assert_eq!(DiagnosticFactTag::known(expected), Some(tag));
1210        }
1211
1212        assert_eq!(DiagnosticFactTag::known(0), None);
1213        assert_eq!(DiagnosticFactTag::known(96), None);
1214        assert_eq!(DiagnosticFactTag::known(u8::MAX), None);
1215    }
1216
1217    #[test]
1218    fn execution_budget_fact_value_registries_are_fixed() {
1219        assert_eq!(DiagnosticBacklogResource::Batches.raw(), 1);
1220        assert_eq!(DiagnosticBacklogResource::Records.raw(), 2);
1221        assert_eq!(DiagnosticBacklogResource::EncodedBytes.raw(), 3);
1222        assert_eq!(DiagnosticBacklogResource::known(4), None);
1223
1224        for (index, resource) in DiagnosticExecutionBudgetResource::ALL
1225            .iter()
1226            .copied()
1227            .enumerate()
1228        {
1229            let expected = u64::try_from(index + 1).expect("resource index fits u64");
1230            assert_eq!(resource.raw(), expected);
1231            assert_eq!(
1232                DiagnosticExecutionBudgetResource::known(expected),
1233                Some(resource)
1234            );
1235        }
1236        assert_eq!(DiagnosticExecutionBudgetResource::known(0), None);
1237        assert_eq!(DiagnosticExecutionBudgetResource::known(21), None);
1238
1239        assert_eq!(DiagnosticExecutionBudgetScope::Execution.raw(), 1);
1240        assert_eq!(DiagnosticExecutionBudgetScope::Request.raw(), 2);
1241        assert_eq!(DiagnosticExecutionBudgetScope::known(3), None);
1242
1243        assert_eq!(DiagnosticExecutionLane::PublicRead.raw(), 1);
1244        assert_eq!(DiagnosticExecutionLane::TrustedRead.raw(), 2);
1245        assert_eq!(DiagnosticExecutionLane::Diagnostic.raw(), 3);
1246        assert_eq!(DiagnosticExecutionLane::Mutation.raw(), 4);
1247        assert_eq!(DiagnosticExecutionLane::Recovery.raw(), 5);
1248        assert_eq!(DiagnosticExecutionLane::known(6), None);
1249    }
1250
1251    #[test]
1252    fn accepted_identity_pair_packing_is_exact() {
1253        for pair in [
1254            (0, 0),
1255            (1, 2),
1256            (u32::MAX, 0),
1257            (0, u32::MAX),
1258            (u32::MAX, u32::MAX),
1259        ] {
1260            assert_eq!(unpack_u32_pair(pack_u32_pair(pair.0, pair.1)), pair);
1261        }
1262    }
1263
1264    #[test]
1265    fn constraint_fact_value_registries_are_fixed() {
1266        assert_eq!(DiagnosticConstraintKind::Check.raw(), 1);
1267        assert_eq!(DiagnosticConstraintKind::NotNull.raw(), 2);
1268        assert_eq!(DiagnosticConstraintKind::Relation.raw(), 3);
1269        assert_eq!(DiagnosticConstraintKind::TargetedRule.raw(), 4);
1270        assert_eq!(DiagnosticConstraintKind::Unique.raw(), 5);
1271        assert_eq!(DiagnosticConstraintKind::known(0), None);
1272        assert_eq!(DiagnosticConstraintKind::known(6), None);
1273
1274        assert_eq!(DiagnosticConstraintContext::Integrity.raw(), 1);
1275        assert_eq!(DiagnosticConstraintContext::MigrationValidation.raw(), 2);
1276        assert_eq!(DiagnosticConstraintContext::WriteAdmission.raw(), 3);
1277        assert_eq!(DiagnosticConstraintContext::known(0), None);
1278        assert_eq!(DiagnosticConstraintContext::known(4), None);
1279    }
1280
1281    #[test]
1282    fn component_kind_registry_is_fixed_and_numeric() {
1283        let kinds = [
1284            DiagnosticComponentKind::CommitDataKey,
1285            DiagnosticComponentKind::IndexKey,
1286            DiagnosticComponentKind::IndexKeyComponent,
1287            DiagnosticComponentKind::RelationTargetPrimaryKey,
1288        ];
1289
1290        for (index, kind) in kinds.iter().copied().enumerate() {
1291            let expected = (index + 1) as u64;
1292            assert_eq!(kind.raw(), expected);
1293            assert_eq!(DiagnosticComponentKind::known(expected), Some(kind));
1294            assert_eq!(format!("{kind:?}"), expected.to_string());
1295        }
1296        assert_eq!(DiagnosticComponentKind::known(0), None);
1297        assert_eq!(DiagnosticComponentKind::known(5), None);
1298    }
1299
1300    #[test]
1301    fn decode_reason_registry_is_fixed_and_numeric() {
1302        let reasons = [
1303            DiagnosticDecodeReason::CursorEmpty,
1304            DiagnosticDecodeReason::CursorTooLong,
1305            DiagnosticDecodeReason::CursorOddLength,
1306            DiagnosticDecodeReason::CursorInvalidHex,
1307            DiagnosticDecodeReason::CursorGroupedDirectionMismatch,
1308            DiagnosticDecodeReason::CursorTokenEncode,
1309            DiagnosticDecodeReason::CursorTokenDecode,
1310            DiagnosticDecodeReason::RecoveryMarkerMagic,
1311            DiagnosticDecodeReason::RecoveryMarkerChecksum,
1312            DiagnosticDecodeReason::RecoveryMarkerState,
1313        ];
1314
1315        for (index, reason) in reasons.iter().copied().enumerate() {
1316            let expected = (index + 1) as u64;
1317            assert_eq!(reason.raw(), expected);
1318            assert_eq!(DiagnosticDecodeReason::known(expected), Some(reason));
1319            assert_eq!(format!("{reason:?}"), expected.to_string());
1320        }
1321
1322        assert_eq!(DiagnosticDecodeReason::known(0), None);
1323        assert_eq!(DiagnosticDecodeReason::known(11), None);
1324    }
1325
1326    #[test]
1327    fn mutation_operation_registry_is_fixed_and_numeric() {
1328        let operations = [
1329            DiagnosticMutationOperation::Insert,
1330            DiagnosticMutationOperation::Replace,
1331            DiagnosticMutationOperation::Update,
1332            DiagnosticMutationOperation::Delete,
1333        ];
1334
1335        for (index, operation) in operations.iter().copied().enumerate() {
1336            let expected = (index + 1) as u64;
1337            assert_eq!(operation.raw(), expected);
1338            assert_eq!(
1339                DiagnosticMutationOperation::known(expected),
1340                Some(operation)
1341            );
1342            assert_eq!(format!("{operation:?}"), expected.to_string());
1343        }
1344
1345        assert_eq!(DiagnosticMutationOperation::known(0), None);
1346        assert_eq!(DiagnosticMutationOperation::known(5), None);
1347    }
1348
1349    #[test]
1350    fn query_kind_registries_are_fixed_contiguous_and_numeric() {
1351        for raw in 1..=9 {
1352            let value = DiagnosticTypeFamily::known(raw).expect("type family should be known");
1353            assert_eq!(value.raw(), raw);
1354            assert_eq!(format!("{value:?}"), raw.to_string());
1355        }
1356        assert_eq!(DiagnosticTypeFamily::known(0), None);
1357        assert_eq!(DiagnosticTypeFamily::known(10), None);
1358
1359        for raw in 1..=39 {
1360            let value = DiagnosticFunctionKind::known(raw).expect("function kind should be known");
1361            assert_eq!(value.raw(), raw);
1362            assert_eq!(format!("{value:?}"), raw.to_string());
1363        }
1364        assert_eq!(DiagnosticFunctionKind::known(0), None);
1365        assert_eq!(DiagnosticFunctionKind::known(40), None);
1366
1367        for raw in 1..=18 {
1368            let value = DiagnosticOperatorKind::known(raw).expect("operator kind should be known");
1369            assert_eq!(value.raw(), raw);
1370            assert_eq!(format!("{value:?}"), raw.to_string());
1371        }
1372        assert_eq!(DiagnosticOperatorKind::known(0), None);
1373        assert_eq!(DiagnosticOperatorKind::known(19), None);
1374
1375        for raw in 1..=8 {
1376            let value =
1377                DiagnosticAggregateKind::known(raw).expect("aggregate kind should be known");
1378            assert_eq!(value.raw(), raw);
1379            assert_eq!(format!("{value:?}"), raw.to_string());
1380        }
1381        assert_eq!(DiagnosticAggregateKind::known(0), None);
1382        assert_eq!(DiagnosticAggregateKind::known(9), None);
1383    }
1384
1385    #[test]
1386    fn per_code_schema_rejects_missing_disallowed_and_noncanonical_tags() {
1387        let valid = [
1388            (DiagnosticFactTag::ActualCount, 5),
1389            (DiagnosticFactTag::Limit, 4),
1390        ];
1391        assert_eq!(
1392            validate_known_diagnostic_fact_schema(
1393                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1394                &valid,
1395            ),
1396            Ok(())
1397        );
1398        assert_eq!(
1399            validate_known_diagnostic_fact_schema(
1400                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1401                &valid[..1],
1402            ),
1403            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1404        );
1405        assert_eq!(
1406            validate_known_diagnostic_fact_schema(
1407                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1408                &[valid[1], valid[0]],
1409            ),
1410            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1411        );
1412        assert_eq!(
1413            validate_known_diagnostic_fact_schema(ErrorCode::QUERY_VALIDATE, &valid),
1414            Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded)
1415        );
1416
1417        assert_eq!(
1418            validate_known_diagnostic_fact_schema(
1419                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_COMMIT_WORK_EXCEEDED,
1420                &valid,
1421            ),
1422            Ok(())
1423        );
1424        assert_eq!(
1425            validate_known_diagnostic_fact_schema(
1426                ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_COMMIT_WORK_EXCEEDED,
1427                &valid[1..],
1428            ),
1429            Ok(())
1430        );
1431    }
1432
1433    #[test]
1434    fn execution_budget_schema_requires_complete_typed_attribution() {
1435        let valid = [
1436            (
1437                DiagnosticFactTag::BudgetResource,
1438                DiagnosticExecutionBudgetResource::StoredBytesRead.raw(),
1439            ),
1440            (DiagnosticFactTag::Limit, 4_096),
1441            (DiagnosticFactTag::Actual, 4_097),
1442            (
1443                DiagnosticFactTag::ExecutionBudgetScope,
1444                DiagnosticExecutionBudgetScope::Request.raw(),
1445            ),
1446            (
1447                DiagnosticFactTag::ExecutionLane,
1448                DiagnosticExecutionLane::TrustedRead.raw(),
1449            ),
1450            (DiagnosticFactTag::QueryShapeFingerprintPrefix, 17),
1451        ];
1452        assert_eq!(
1453            validate_known_diagnostic_fact_schema(
1454                ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1455                &valid,
1456            ),
1457            Ok(())
1458        );
1459        assert_eq!(
1460            validate_known_diagnostic_fact_schema(
1461                ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1462                &valid[..5],
1463            ),
1464            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1465        );
1466
1467        let mut invalid_resource = valid;
1468        invalid_resource[0].1 = 0;
1469        assert_eq!(
1470            validate_known_diagnostic_fact_schema(
1471                ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1472                &invalid_resource,
1473            ),
1474            Err(DiagnosticFactSchemaMismatch::InvalidValue)
1475        );
1476    }
1477
1478    #[test]
1479    fn raw_schema_keeps_unknown_context_numeric_but_marks_it_invalid() {
1480        assert_eq!(
1481            validate_raw_diagnostic_fact_schema(
1482                ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR,
1483                &[(u8::MAX, 17)],
1484            ),
1485            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1486        );
1487        assert_eq!(
1488            validate_raw_diagnostic_fact_schema(
1489                ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR,
1490                &[(DiagnosticFactTag::DecodeReason.raw(), u64::MAX)],
1491            ),
1492            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1493        );
1494    }
1495
1496    #[test]
1497    fn constraint_schema_enforces_authority_operation_and_bounded_path_suffix() {
1498        let mut targeted = vec![
1499            (DiagnosticFactTag::AcceptedSchemaFingerprintMethod, 1),
1500            (DiagnosticFactTag::AcceptedSchemaFingerprintHigh, 2),
1501            (DiagnosticFactTag::AcceptedSchemaFingerprintLow, 3),
1502            (DiagnosticFactTag::EntityTag, 17),
1503            (DiagnosticFactTag::ConstraintId, 4),
1504            (
1505                DiagnosticFactTag::ConstraintKind,
1506                DiagnosticConstraintKind::TargetedRule.raw(),
1507            ),
1508            (
1509                DiagnosticFactTag::ConstraintContext,
1510                DiagnosticConstraintContext::WriteAdmission.raw(),
1511            ),
1512            (
1513                DiagnosticFactTag::MutationOperation,
1514                DiagnosticMutationOperation::Insert.raw(),
1515            ),
1516            (DiagnosticFactTag::BatchPosition, 0),
1517        ];
1518        targeted.extend((0..64).map(|index| (DiagnosticFactTag::ListElement, index)));
1519        assert_eq!(targeted.len(), 73);
1520        assert_eq!(
1521            validate_known_diagnostic_fact_schema(
1522                ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1523                targeted.as_slice(),
1524            ),
1525            Ok(())
1526        );
1527
1528        let mut overlong = targeted.clone();
1529        overlong.push((DiagnosticFactTag::ListElement, 64));
1530        assert_eq!(
1531            validate_known_diagnostic_fact_schema(
1532                ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1533                overlong.as_slice(),
1534            ),
1535            Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded)
1536        );
1537
1538        let mut non_targeted_path = targeted;
1539        non_targeted_path[5].1 = DiagnosticConstraintKind::Unique.raw();
1540        assert_eq!(
1541            validate_known_diagnostic_fact_schema(
1542                ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1543                non_targeted_path.as_slice(),
1544            ),
1545            Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1546        );
1547    }
1548
1549    #[test]
1550    fn schema_enforces_global_ceiling_before_per_code_ceiling() {
1551        let facts = vec![(DiagnosticFactTag::ActualCount.raw(), 0); 81];
1552        assert_eq!(
1553            validate_raw_diagnostic_fact_schema(ErrorCode::QUERY_PLAN, facts.as_slice()),
1554            Err(DiagnosticFactSchemaMismatch::GlobalMaximumExceeded)
1555        );
1556    }
1557}