1use std::fmt;
8
9use crate::ErrorCode;
10
11pub const MAX_PUBLIC_DIAGNOSTIC_FACTS: usize = 80;
13
14macro_rules! define_fact_tag_registry {
15 ($($name:ident = $raw:literal;)+) => {
16 #[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 #[must_use]
28 pub const fn raw(self) -> u8 {
29 match self {
30 $(Self::$name => $raw,)+
31 }
32 }
33
34 #[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
51define_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#[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#[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 #[must_use]
197 pub const fn raw(self) -> u64 {
198 match self {
199 $(Self::$variant => $raw,)+
200 }
201 }
202
203 #[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 pub enum DiagnosticBacklogResource {
224 Batches = 1;
225 Records = 2;
226 EncodedBytes = 3;
227 }
228}
229
230define_numeric_fact_value_registry! {
231 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 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 pub enum DiagnosticExecutionBudgetScope {
285 Execution = 1;
286 Request = 2;
287 }
288}
289
290define_numeric_fact_value_registry! {
291 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 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 pub enum DiagnosticConstraintContext {
315 Integrity = 1;
316 MigrationValidation = 2;
317 WriteAdmission = 3;
318 }
319}
320
321define_numeric_fact_value_registry! {
322 pub enum DiagnosticComponentKind {
324 CommitDataKey = 1;
325 IndexKey = 2;
326 IndexKeyComponent = 3;
327 RelationTargetPrimaryKey = 4;
328 }
329}
330
331define_numeric_fact_value_registry! {
332 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 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 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 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 #[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 #[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 #[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 #[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#[must_use]
511pub const fn pack_u32_pair(high: u32, low: u32) -> u64 {
512 (high as u64) << 32 | low as u64
513}
514
515#[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
529pub enum DiagnosticFactSchemaMismatch {
530 GlobalMaximumExceeded,
532 CodeMaximumExceeded,
534 InvalidSequence,
536 InvalidValue,
538}
539
540pub 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
554pub 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 271 | 272 => tags_match(
710 fact_count,
711 &fact_at,
712 &[DiagnosticFactTag::Limit, DiagnosticFactTag::Actual],
713 ),
714 226 => tags_match(
715 fact_count,
716 &fact_at,
717 &[
718 DiagnosticFactTag::BatchPosition,
719 DiagnosticFactTag::ExpectedEntityTag,
720 DiagnosticFactTag::ActualEntityTag,
721 ],
722 ),
723 227 => tags_match(
724 fact_count,
725 &fact_at,
726 &[
727 DiagnosticFactTag::EntityTag,
728 DiagnosticFactTag::FirstBatchPosition,
729 DiagnosticFactTag::DuplicateBatchPosition,
730 ],
731 ),
732 _ => fact_count == 0,
733 };
734 if !valid_sequence {
735 return Err(DiagnosticFactSchemaMismatch::InvalidSequence);
736 }
737
738 for index in 0..fact_count {
739 let (raw_tag, value) = fact_at(index);
740 let Some(tag) = DiagnosticFactTag::known(raw_tag) else {
741 return Err(DiagnosticFactSchemaMismatch::InvalidSequence);
742 };
743 if !diagnostic_fact_value_is_valid(tag, value) {
744 return Err(DiagnosticFactSchemaMismatch::InvalidValue);
745 }
746 }
747 Ok(())
748}
749
750const fn diagnostic_fact_maximum(code: ErrorCode) -> usize {
751 match code.raw() {
752 5 | 15 | 17 | 186 | 187 | 220 | 226 | 227 | 253 => 3,
753 133 | 134 | 158 | 159 | 164 | 222 => 1,
754 18 | 20 | 130 | 166 | 167 | 169 | 190 | 191 | 192 | 194 | 223 | 224 | 225 | 248 | 249
755 | 250 | 251 | 262 | 264 | 271 | 272 => 2,
756 3 | 19 | 23 => 5,
757 22 | 252 => 6,
758 185 | 221 | 263 => 4,
759 210 => 73,
760 212 => 9,
761 _ => 0,
762 }
763}
764
765#[expect(
766 clippy::too_many_lines,
767 reason = "the query-plan E-code deliberately owns several exact finite fact sequences"
768)]
769fn query_plan_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
770 fact_count == 0
771 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::TermIndex])
772 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ComponentIndex])
773 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::GroupIndex])
774 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ClauseIndex])
775 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::AggregateIndex])
776 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::AggregateKind])
777 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ProjectionIndex])
778 || tags_match(
779 fact_count,
780 fact_at,
781 &[
782 DiagnosticFactTag::FirstTermIndex,
783 DiagnosticFactTag::DuplicateTermIndex,
784 ],
785 )
786 || tags_match(
787 fact_count,
788 fact_at,
789 &[
790 DiagnosticFactTag::ClauseIndex,
791 DiagnosticFactTag::OperatorKind,
792 ],
793 )
794 || tags_match(
795 fact_count,
796 fact_at,
797 &[
798 DiagnosticFactTag::AggregateIndex,
799 DiagnosticFactTag::AggregateKind,
800 ],
801 )
802 || tags_match(
803 fact_count,
804 fact_at,
805 &[
806 DiagnosticFactTag::AggregateKind,
807 DiagnosticFactTag::TypeFamily,
808 ],
809 )
810 || tags_match(
811 fact_count,
812 fact_at,
813 &[
814 DiagnosticFactTag::OperatorKind,
815 DiagnosticFactTag::TypeFamily,
816 ],
817 )
818 || tags_match(
819 fact_count,
820 fact_at,
821 &[
822 DiagnosticFactTag::BranchIndex,
823 DiagnosticFactTag::TypeFamily,
824 ],
825 )
826 || tags_match(
827 fact_count,
828 fact_at,
829 &[DiagnosticFactTag::TypeFamily, DiagnosticFactTag::TypeFamily],
830 )
831 || tags_match(
832 fact_count,
833 fact_at,
834 &[
835 DiagnosticFactTag::ClauseIndex,
836 DiagnosticFactTag::AggregateIndex,
837 DiagnosticFactTag::ActualCount,
838 ],
839 )
840 || tags_match(
841 fact_count,
842 fact_at,
843 &[
844 DiagnosticFactTag::FunctionKind,
845 DiagnosticFactTag::ExpectedArity,
846 DiagnosticFactTag::ActualArity,
847 ],
848 )
849 || tags_match(
850 fact_count,
851 fact_at,
852 &[
853 DiagnosticFactTag::FunctionKind,
854 DiagnosticFactTag::ArgumentIndex,
855 DiagnosticFactTag::TypeFamily,
856 ],
857 )
858 || tags_match(
859 fact_count,
860 fact_at,
861 &[
862 DiagnosticFactTag::OperatorKind,
863 DiagnosticFactTag::TypeFamily,
864 DiagnosticFactTag::TypeFamily,
865 ],
866 )
867 || tags_match(
868 fact_count,
869 fact_at,
870 &[
871 DiagnosticFactTag::BranchIndex,
872 DiagnosticFactTag::TypeFamily,
873 DiagnosticFactTag::TypeFamily,
874 ],
875 )
876 || tags_match(
877 fact_count,
878 fact_at,
879 &[
880 DiagnosticFactTag::TypeFamily,
881 DiagnosticFactTag::BranchIndex,
882 DiagnosticFactTag::TypeFamily,
883 ],
884 )
885 || tags_match(
886 fact_count,
887 fact_at,
888 &[
889 DiagnosticFactTag::BranchIndex,
890 DiagnosticFactTag::TypeFamily,
891 DiagnosticFactTag::BranchIndex,
892 DiagnosticFactTag::TypeFamily,
893 ],
894 )
895 || tags_match(
896 fact_count,
897 fact_at,
898 &[
899 DiagnosticFactTag::FunctionKind,
900 DiagnosticFactTag::ArgumentIndex,
901 DiagnosticFactTag::TypeFamily,
902 DiagnosticFactTag::ArgumentIndex,
903 DiagnosticFactTag::TypeFamily,
904 ],
905 )
906}
907
908fn cursor_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
909 if fact_count == 0 {
910 return true;
911 }
912 if tags_match(fact_count, fact_at, &[DiagnosticFactTag::DecodeReason]) {
913 return matches!(fact_at(0).1, 1 | 3 | 5 | 6 | 7);
914 }
915 if tags_match(
916 fact_count,
917 fact_at,
918 &[
919 DiagnosticFactTag::ActualLength,
920 DiagnosticFactTag::Maximum,
921 DiagnosticFactTag::DecodeReason,
922 ],
923 ) {
924 return fact_at(2).1 == DiagnosticDecodeReason::CursorTooLong.raw();
925 }
926 if tags_match(
927 fact_count,
928 fact_at,
929 &[
930 DiagnosticFactTag::ComponentIndex,
931 DiagnosticFactTag::DecodeReason,
932 ],
933 ) {
934 return matches!(fact_at(1).1, 4 | 6 | 7);
935 }
936 tags_match(
937 fact_count,
938 fact_at,
939 &[
940 DiagnosticFactTag::ExpectedSignaturePrefix,
941 DiagnosticFactTag::ActualSignaturePrefix,
942 ],
943 ) || tags_match(
944 fact_count,
945 fact_at,
946 &[
947 DiagnosticFactTag::ExpectedOffset,
948 DiagnosticFactTag::ActualOffset,
949 ],
950 )
951}
952
953fn store_corruption_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
954 fact_count == 0
955 || (tags_match(
956 fact_count,
957 fact_at,
958 &[
959 DiagnosticFactTag::ComponentKind,
960 DiagnosticFactTag::ActualLength,
961 DiagnosticFactTag::Limit,
962 ],
963 ) && fact_at(0).1 == DiagnosticComponentKind::CommitDataKey.raw())
964 || tags_match(
965 fact_count,
966 fact_at,
967 &[
968 DiagnosticFactTag::ExpectedEntityTag,
969 DiagnosticFactTag::ActualEntityTag,
970 ],
971 )
972}
973
974fn runtime_corruption_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
975 store_corruption_schema(fact_count, fact_at)
976 || (tags_match(fact_count, fact_at, &[DiagnosticFactTag::DecodeReason])
977 && matches!(fact_at(0).1, 8..=10))
978}
979
980fn incompatible_format_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
981 fact_count == 0
982 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ExpectedVersion])
983 || tags_match(
984 fact_count,
985 fact_at,
986 &[
987 DiagnosticFactTag::ExpectedVersion,
988 DiagnosticFactTag::ActualVersion,
989 ],
990 )
991}
992
993fn runtime_invariant_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
994 fact_count == 0
995 || (tags_match(
996 fact_count,
997 fact_at,
998 &[
999 DiagnosticFactTag::EntityTag,
1000 DiagnosticFactTag::PhysicalGeneration,
1001 DiagnosticFactTag::ComponentKind,
1002 DiagnosticFactTag::ActualArity,
1003 DiagnosticFactTag::Maximum,
1004 ],
1005 ) && fact_at(2).1 == DiagnosticComponentKind::IndexKey.raw())
1006}
1007
1008fn runtime_conflict_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
1009 fact_count == 0
1010 || tags_match(fact_count, fact_at, &[DiagnosticFactTag::ExpectedRevision])
1011 || tags_match(
1012 fact_count,
1013 fact_at,
1014 &[
1015 DiagnosticFactTag::ExpectedRevision,
1016 DiagnosticFactTag::CurrentRevision,
1017 ],
1018 )
1019}
1020
1021fn runtime_unsupported_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
1022 fact_count == 0
1023 || (tags_match(
1024 fact_count,
1025 fact_at,
1026 &[
1027 DiagnosticFactTag::EntityTag,
1028 DiagnosticFactTag::PhysicalGeneration,
1029 DiagnosticFactTag::ComponentIndex,
1030 DiagnosticFactTag::ComponentKind,
1031 DiagnosticFactTag::ActualLength,
1032 DiagnosticFactTag::Limit,
1033 ],
1034 ) && fact_at(3).1 == DiagnosticComponentKind::IndexKeyComponent.raw())
1035}
1036
1037fn runtime_internal_schema(fact_count: usize, fact_at: &impl Fn(usize) -> (u8, u64)) -> bool {
1038 if fact_count >= 2
1041 && fact_at(0).0 == DiagnosticFactTag::EntityTag.raw()
1042 && fact_at(1).0 == DiagnosticFactTag::RelationId.raw()
1043 {
1044 return runtime_internal_detail_schema(fact_count - 2, &|index| fact_at(index + 2));
1045 }
1046 runtime_internal_detail_schema(fact_count, fact_at)
1047}
1048
1049fn runtime_internal_detail_schema(
1050 fact_count: usize,
1051 fact_at: &impl Fn(usize) -> (u8, u64),
1052) -> bool {
1053 fact_count == 0
1054 || tags_match(
1055 fact_count,
1056 fact_at,
1057 &[
1058 DiagnosticFactTag::ExpectedMemoryId,
1059 DiagnosticFactTag::ActualMemoryId,
1060 ],
1061 )
1062 || (tags_match(
1063 fact_count,
1064 fact_at,
1065 &[
1066 DiagnosticFactTag::ComponentKind,
1067 DiagnosticFactTag::ExpectedArity,
1068 DiagnosticFactTag::ActualArity,
1069 ],
1070 ) && fact_at(0).1 == DiagnosticComponentKind::RelationTargetPrimaryKey.raw())
1071}
1072
1073fn constraint_schema(
1074 fact_count: usize,
1075 fact_at: &impl Fn(usize) -> (u8, u64),
1076 allow_targeted_path: bool,
1077) -> bool {
1078 const COMMON: &[DiagnosticFactTag] = &[
1079 DiagnosticFactTag::AcceptedSchemaFingerprintMethod,
1080 DiagnosticFactTag::AcceptedSchemaFingerprintHigh,
1081 DiagnosticFactTag::AcceptedSchemaFingerprintLow,
1082 DiagnosticFactTag::EntityTag,
1083 DiagnosticFactTag::ConstraintId,
1084 DiagnosticFactTag::ConstraintKind,
1085 DiagnosticFactTag::ConstraintContext,
1086 ];
1087 if fact_count < COMMON.len()
1088 || !tags_prefix_matches(fact_count, fact_at, COMMON)
1089 || fact_at(6).1 != DiagnosticConstraintContext::WriteAdmission.raw()
1090 {
1091 return false;
1092 }
1093
1094 let constraint_kind = fact_at(5).1;
1095 if DiagnosticConstraintKind::known(constraint_kind).is_none() {
1096 return false;
1097 }
1098 let mut index = COMMON.len();
1099 if index < fact_count && fact_at(index).0 == DiagnosticFactTag::MutationOperation.raw() {
1100 index += 1;
1101 if index < fact_count && fact_at(index).0 == DiagnosticFactTag::BatchPosition.raw() {
1102 index += 1;
1103 }
1104 }
1105
1106 let path_len = fact_count - index;
1107 if path_len == 0 {
1108 return !allow_targeted_path
1109 || constraint_kind != DiagnosticConstraintKind::TargetedRule.raw();
1110 }
1111 allow_targeted_path
1112 && constraint_kind == DiagnosticConstraintKind::TargetedRule.raw()
1113 && path_len <= 64
1114 && (index..fact_count).all(|position| {
1115 DiagnosticFactTag::known(fact_at(position).0).is_some_and(is_value_path_tag)
1116 })
1117}
1118
1119fn tags_match(
1120 fact_count: usize,
1121 fact_at: &impl Fn(usize) -> (u8, u64),
1122 expected: &[DiagnosticFactTag],
1123) -> bool {
1124 fact_count == expected.len() && tags_prefix_matches(fact_count, fact_at, expected)
1125}
1126
1127fn tags_prefix_matches(
1128 fact_count: usize,
1129 fact_at: &impl Fn(usize) -> (u8, u64),
1130 expected: &[DiagnosticFactTag],
1131) -> bool {
1132 fact_count >= expected.len()
1133 && expected
1134 .iter()
1135 .enumerate()
1136 .all(|(index, tag)| fact_at(index).0 == tag.raw())
1137}
1138
1139const fn is_value_path_tag(tag: DiagnosticFactTag) -> bool {
1140 matches!(
1141 tag,
1142 DiagnosticFactTag::RootField
1143 | DiagnosticFactTag::RecordMember
1144 | DiagnosticFactTag::TupleElement
1145 | DiagnosticFactTag::Newtype
1146 | DiagnosticFactTag::EnumVariant
1147 | DiagnosticFactTag::ListElement
1148 | DiagnosticFactTag::SetElement
1149 | DiagnosticFactTag::MapEntryKey
1150 | DiagnosticFactTag::MapEntryValue
1151 )
1152}
1153
1154const fn diagnostic_fact_value_is_valid(tag: DiagnosticFactTag, value: u64) -> bool {
1155 match tag {
1156 DiagnosticFactTag::AcceptedSchemaFingerprintMethod
1157 | DiagnosticFactTag::ExpectedMemoryId
1158 | DiagnosticFactTag::ActualMemoryId => value <= u8::MAX as u64,
1159 DiagnosticFactTag::ConstraintId
1160 | DiagnosticFactTag::FieldId
1161 | DiagnosticFactTag::IndexId
1162 | DiagnosticFactTag::RelationId
1163 | DiagnosticFactTag::BatchPosition
1164 | DiagnosticFactTag::FirstBatchPosition
1165 | DiagnosticFactTag::DuplicateBatchPosition
1166 | DiagnosticFactTag::RowLayout
1167 | DiagnosticFactTag::HistoryFloor
1168 | DiagnosticFactTag::CurrentLayout
1169 | DiagnosticFactTag::RootField
1170 | DiagnosticFactTag::Newtype
1171 | DiagnosticFactTag::ListElement
1172 | DiagnosticFactTag::SetElement
1173 | DiagnosticFactTag::MapEntryKey
1174 | DiagnosticFactTag::MapEntryValue => value <= u32::MAX as u64,
1175 DiagnosticFactTag::ConstraintKind => DiagnosticConstraintKind::known(value).is_some(),
1176 DiagnosticFactTag::BacklogResource => DiagnosticBacklogResource::known(value).is_some(),
1177 DiagnosticFactTag::ConstraintContext => DiagnosticConstraintContext::known(value).is_some(),
1178 DiagnosticFactTag::TypeFamily => DiagnosticTypeFamily::known(value).is_some(),
1179 DiagnosticFactTag::FunctionKind => DiagnosticFunctionKind::known(value).is_some(),
1180 DiagnosticFactTag::OperatorKind => DiagnosticOperatorKind::known(value).is_some(),
1181 DiagnosticFactTag::AggregateKind => DiagnosticAggregateKind::known(value).is_some(),
1182 DiagnosticFactTag::ComponentKind => DiagnosticComponentKind::known(value).is_some(),
1183 DiagnosticFactTag::DecodeReason => DiagnosticDecodeReason::known(value).is_some(),
1184 DiagnosticFactTag::BudgetResource => {
1185 DiagnosticExecutionBudgetResource::known(value).is_some()
1186 }
1187 DiagnosticFactTag::ExecutionBudgetScope => {
1188 DiagnosticExecutionBudgetScope::known(value).is_some()
1189 }
1190 DiagnosticFactTag::ExecutionLane => DiagnosticExecutionLane::known(value).is_some(),
1191 DiagnosticFactTag::MutationOperation => DiagnosticMutationOperation::known(value).is_some(),
1192 _ => true,
1193 }
1194}
1195
1196#[cfg(test)]
1197mod tests {
1198 use super::{
1199 DiagnosticAggregateKind, DiagnosticBacklogResource, DiagnosticComponentKind,
1200 DiagnosticConstraintContext, DiagnosticConstraintKind, DiagnosticDecodeReason,
1201 DiagnosticExecutionBudgetResource, DiagnosticExecutionBudgetScope, DiagnosticExecutionLane,
1202 DiagnosticFactSchemaMismatch, DiagnosticFactTag, DiagnosticFunctionKind,
1203 DiagnosticMutationOperation, DiagnosticOperatorKind, DiagnosticTypeFamily,
1204 ORDERED_FACT_TAGS, pack_u32_pair, unpack_u32_pair, validate_known_diagnostic_fact_schema,
1205 validate_raw_diagnostic_fact_schema,
1206 };
1207 use crate::ErrorCode;
1208
1209 #[test]
1210 fn fact_tag_registry_is_fixed_unique_and_contiguous() {
1211 for (index, tag) in ORDERED_FACT_TAGS.iter().copied().enumerate() {
1212 let expected = u8::try_from(index + 1).expect("fact-tag index fits u8");
1213 assert_eq!(tag.raw(), expected);
1214 assert_eq!(DiagnosticFactTag::known(expected), Some(tag));
1215 }
1216
1217 assert_eq!(DiagnosticFactTag::known(0), None);
1218 assert_eq!(DiagnosticFactTag::known(96), None);
1219 assert_eq!(DiagnosticFactTag::known(u8::MAX), None);
1220 }
1221
1222 #[test]
1223 fn execution_budget_fact_value_registries_are_fixed() {
1224 assert_eq!(DiagnosticBacklogResource::Batches.raw(), 1);
1225 assert_eq!(DiagnosticBacklogResource::Records.raw(), 2);
1226 assert_eq!(DiagnosticBacklogResource::EncodedBytes.raw(), 3);
1227 assert_eq!(DiagnosticBacklogResource::known(4), None);
1228
1229 for (index, resource) in DiagnosticExecutionBudgetResource::ALL
1230 .iter()
1231 .copied()
1232 .enumerate()
1233 {
1234 let expected = u64::try_from(index + 1).expect("resource index fits u64");
1235 assert_eq!(resource.raw(), expected);
1236 assert_eq!(
1237 DiagnosticExecutionBudgetResource::known(expected),
1238 Some(resource)
1239 );
1240 }
1241 assert_eq!(DiagnosticExecutionBudgetResource::known(0), None);
1242 assert_eq!(DiagnosticExecutionBudgetResource::known(21), None);
1243
1244 assert_eq!(DiagnosticExecutionBudgetScope::Execution.raw(), 1);
1245 assert_eq!(DiagnosticExecutionBudgetScope::Request.raw(), 2);
1246 assert_eq!(DiagnosticExecutionBudgetScope::known(3), None);
1247
1248 assert_eq!(DiagnosticExecutionLane::PublicRead.raw(), 1);
1249 assert_eq!(DiagnosticExecutionLane::TrustedRead.raw(), 2);
1250 assert_eq!(DiagnosticExecutionLane::Diagnostic.raw(), 3);
1251 assert_eq!(DiagnosticExecutionLane::Mutation.raw(), 4);
1252 assert_eq!(DiagnosticExecutionLane::Recovery.raw(), 5);
1253 assert_eq!(DiagnosticExecutionLane::known(6), None);
1254 }
1255
1256 #[test]
1257 fn accepted_identity_pair_packing_is_exact() {
1258 for pair in [
1259 (0, 0),
1260 (1, 2),
1261 (u32::MAX, 0),
1262 (0, u32::MAX),
1263 (u32::MAX, u32::MAX),
1264 ] {
1265 assert_eq!(unpack_u32_pair(pack_u32_pair(pair.0, pair.1)), pair);
1266 }
1267 }
1268
1269 #[test]
1270 fn constraint_fact_value_registries_are_fixed() {
1271 assert_eq!(DiagnosticConstraintKind::Check.raw(), 1);
1272 assert_eq!(DiagnosticConstraintKind::NotNull.raw(), 2);
1273 assert_eq!(DiagnosticConstraintKind::Relation.raw(), 3);
1274 assert_eq!(DiagnosticConstraintKind::TargetedRule.raw(), 4);
1275 assert_eq!(DiagnosticConstraintKind::Unique.raw(), 5);
1276 assert_eq!(DiagnosticConstraintKind::known(0), None);
1277 assert_eq!(DiagnosticConstraintKind::known(6), None);
1278
1279 assert_eq!(DiagnosticConstraintContext::Integrity.raw(), 1);
1280 assert_eq!(DiagnosticConstraintContext::MigrationValidation.raw(), 2);
1281 assert_eq!(DiagnosticConstraintContext::WriteAdmission.raw(), 3);
1282 assert_eq!(DiagnosticConstraintContext::known(0), None);
1283 assert_eq!(DiagnosticConstraintContext::known(4), None);
1284 }
1285
1286 #[test]
1287 fn component_kind_registry_is_fixed_and_numeric() {
1288 let kinds = [
1289 DiagnosticComponentKind::CommitDataKey,
1290 DiagnosticComponentKind::IndexKey,
1291 DiagnosticComponentKind::IndexKeyComponent,
1292 DiagnosticComponentKind::RelationTargetPrimaryKey,
1293 ];
1294
1295 for (index, kind) in kinds.iter().copied().enumerate() {
1296 let expected = (index + 1) as u64;
1297 assert_eq!(kind.raw(), expected);
1298 assert_eq!(DiagnosticComponentKind::known(expected), Some(kind));
1299 assert_eq!(format!("{kind:?}"), expected.to_string());
1300 }
1301 assert_eq!(DiagnosticComponentKind::known(0), None);
1302 assert_eq!(DiagnosticComponentKind::known(5), None);
1303 }
1304
1305 #[test]
1306 fn decode_reason_registry_is_fixed_and_numeric() {
1307 let reasons = [
1308 DiagnosticDecodeReason::CursorEmpty,
1309 DiagnosticDecodeReason::CursorTooLong,
1310 DiagnosticDecodeReason::CursorOddLength,
1311 DiagnosticDecodeReason::CursorInvalidHex,
1312 DiagnosticDecodeReason::CursorGroupedDirectionMismatch,
1313 DiagnosticDecodeReason::CursorTokenEncode,
1314 DiagnosticDecodeReason::CursorTokenDecode,
1315 DiagnosticDecodeReason::RecoveryMarkerMagic,
1316 DiagnosticDecodeReason::RecoveryMarkerChecksum,
1317 DiagnosticDecodeReason::RecoveryMarkerState,
1318 ];
1319
1320 for (index, reason) in reasons.iter().copied().enumerate() {
1321 let expected = (index + 1) as u64;
1322 assert_eq!(reason.raw(), expected);
1323 assert_eq!(DiagnosticDecodeReason::known(expected), Some(reason));
1324 assert_eq!(format!("{reason:?}"), expected.to_string());
1325 }
1326
1327 assert_eq!(DiagnosticDecodeReason::known(0), None);
1328 assert_eq!(DiagnosticDecodeReason::known(11), None);
1329 }
1330
1331 #[test]
1332 fn mutation_operation_registry_is_fixed_and_numeric() {
1333 let operations = [
1334 DiagnosticMutationOperation::Insert,
1335 DiagnosticMutationOperation::Replace,
1336 DiagnosticMutationOperation::Update,
1337 DiagnosticMutationOperation::Delete,
1338 ];
1339
1340 for (index, operation) in operations.iter().copied().enumerate() {
1341 let expected = (index + 1) as u64;
1342 assert_eq!(operation.raw(), expected);
1343 assert_eq!(
1344 DiagnosticMutationOperation::known(expected),
1345 Some(operation)
1346 );
1347 assert_eq!(format!("{operation:?}"), expected.to_string());
1348 }
1349
1350 assert_eq!(DiagnosticMutationOperation::known(0), None);
1351 assert_eq!(DiagnosticMutationOperation::known(5), None);
1352 }
1353
1354 #[test]
1355 fn query_kind_registries_are_fixed_contiguous_and_numeric() {
1356 for raw in 1..=9 {
1357 let value = DiagnosticTypeFamily::known(raw).expect("type family should be known");
1358 assert_eq!(value.raw(), raw);
1359 assert_eq!(format!("{value:?}"), raw.to_string());
1360 }
1361 assert_eq!(DiagnosticTypeFamily::known(0), None);
1362 assert_eq!(DiagnosticTypeFamily::known(10), None);
1363
1364 for raw in 1..=39 {
1365 let value = DiagnosticFunctionKind::known(raw).expect("function kind should be known");
1366 assert_eq!(value.raw(), raw);
1367 assert_eq!(format!("{value:?}"), raw.to_string());
1368 }
1369 assert_eq!(DiagnosticFunctionKind::known(0), None);
1370 assert_eq!(DiagnosticFunctionKind::known(40), None);
1371
1372 for raw in 1..=18 {
1373 let value = DiagnosticOperatorKind::known(raw).expect("operator kind should be known");
1374 assert_eq!(value.raw(), raw);
1375 assert_eq!(format!("{value:?}"), raw.to_string());
1376 }
1377 assert_eq!(DiagnosticOperatorKind::known(0), None);
1378 assert_eq!(DiagnosticOperatorKind::known(19), None);
1379
1380 for raw in 1..=8 {
1381 let value =
1382 DiagnosticAggregateKind::known(raw).expect("aggregate kind should be known");
1383 assert_eq!(value.raw(), raw);
1384 assert_eq!(format!("{value:?}"), raw.to_string());
1385 }
1386 assert_eq!(DiagnosticAggregateKind::known(0), None);
1387 assert_eq!(DiagnosticAggregateKind::known(9), None);
1388 }
1389
1390 #[test]
1391 fn per_code_schema_rejects_missing_disallowed_and_noncanonical_tags() {
1392 let valid = [
1393 (DiagnosticFactTag::ActualCount, 5),
1394 (DiagnosticFactTag::Limit, 4),
1395 ];
1396 assert_eq!(
1397 validate_known_diagnostic_fact_schema(
1398 ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1399 &valid,
1400 ),
1401 Ok(())
1402 );
1403 assert_eq!(
1404 validate_known_diagnostic_fact_schema(
1405 ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1406 &valid[..1],
1407 ),
1408 Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1409 );
1410 assert_eq!(
1411 validate_known_diagnostic_fact_schema(
1412 ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_TOO_MANY_ITEMS,
1413 &[valid[1], valid[0]],
1414 ),
1415 Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1416 );
1417 assert_eq!(
1418 validate_known_diagnostic_fact_schema(ErrorCode::QUERY_VALIDATE, &valid),
1419 Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded)
1420 );
1421
1422 assert_eq!(
1423 validate_known_diagnostic_fact_schema(
1424 ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_COMMIT_WORK_EXCEEDED,
1425 &valid,
1426 ),
1427 Ok(())
1428 );
1429 assert_eq!(
1430 validate_known_diagnostic_fact_schema(
1431 ErrorCode::RUNTIME_BOUNDARY_MUTATION_BATCH_COMMIT_WORK_EXCEEDED,
1432 &valid[1..],
1433 ),
1434 Ok(())
1435 );
1436 }
1437
1438 #[test]
1439 fn execution_budget_schema_requires_complete_typed_attribution() {
1440 let valid = [
1441 (
1442 DiagnosticFactTag::BudgetResource,
1443 DiagnosticExecutionBudgetResource::StoredBytesRead.raw(),
1444 ),
1445 (DiagnosticFactTag::Limit, 4_096),
1446 (DiagnosticFactTag::Actual, 4_097),
1447 (
1448 DiagnosticFactTag::ExecutionBudgetScope,
1449 DiagnosticExecutionBudgetScope::Request.raw(),
1450 ),
1451 (
1452 DiagnosticFactTag::ExecutionLane,
1453 DiagnosticExecutionLane::TrustedRead.raw(),
1454 ),
1455 (DiagnosticFactTag::QueryShapeFingerprintPrefix, 17),
1456 ];
1457 assert_eq!(
1458 validate_known_diagnostic_fact_schema(
1459 ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1460 &valid,
1461 ),
1462 Ok(())
1463 );
1464 assert_eq!(
1465 validate_known_diagnostic_fact_schema(
1466 ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1467 &valid[..5],
1468 ),
1469 Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1470 );
1471
1472 let mut invalid_resource = valid;
1473 invalid_resource[0].1 = 0;
1474 assert_eq!(
1475 validate_known_diagnostic_fact_schema(
1476 ErrorCode::RUNTIME_BOUNDARY_EXECUTION_BUDGET_EXCEEDED,
1477 &invalid_resource,
1478 ),
1479 Err(DiagnosticFactSchemaMismatch::InvalidValue)
1480 );
1481 }
1482
1483 #[test]
1484 fn raw_schema_keeps_unknown_context_numeric_but_marks_it_invalid() {
1485 assert_eq!(
1486 validate_raw_diagnostic_fact_schema(
1487 ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR,
1488 &[(u8::MAX, 17)],
1489 ),
1490 Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1491 );
1492 assert_eq!(
1493 validate_raw_diagnostic_fact_schema(
1494 ErrorCode::QUERY_INVALID_CONTINUATION_CURSOR,
1495 &[(DiagnosticFactTag::DecodeReason.raw(), u64::MAX)],
1496 ),
1497 Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1498 );
1499 }
1500
1501 #[test]
1502 fn constraint_schema_enforces_authority_operation_and_bounded_path_suffix() {
1503 let mut targeted = vec![
1504 (DiagnosticFactTag::AcceptedSchemaFingerprintMethod, 1),
1505 (DiagnosticFactTag::AcceptedSchemaFingerprintHigh, 2),
1506 (DiagnosticFactTag::AcceptedSchemaFingerprintLow, 3),
1507 (DiagnosticFactTag::EntityTag, 17),
1508 (DiagnosticFactTag::ConstraintId, 4),
1509 (
1510 DiagnosticFactTag::ConstraintKind,
1511 DiagnosticConstraintKind::TargetedRule.raw(),
1512 ),
1513 (
1514 DiagnosticFactTag::ConstraintContext,
1515 DiagnosticConstraintContext::WriteAdmission.raw(),
1516 ),
1517 (
1518 DiagnosticFactTag::MutationOperation,
1519 DiagnosticMutationOperation::Insert.raw(),
1520 ),
1521 (DiagnosticFactTag::BatchPosition, 0),
1522 ];
1523 targeted.extend((0..64).map(|index| (DiagnosticFactTag::ListElement, index)));
1524 assert_eq!(targeted.len(), 73);
1525 assert_eq!(
1526 validate_known_diagnostic_fact_schema(
1527 ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1528 targeted.as_slice(),
1529 ),
1530 Ok(())
1531 );
1532
1533 let mut overlong = targeted.clone();
1534 overlong.push((DiagnosticFactTag::ListElement, 64));
1535 assert_eq!(
1536 validate_known_diagnostic_fact_schema(
1537 ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1538 overlong.as_slice(),
1539 ),
1540 Err(DiagnosticFactSchemaMismatch::CodeMaximumExceeded)
1541 );
1542
1543 let mut non_targeted_path = targeted;
1544 non_targeted_path[5].1 = DiagnosticConstraintKind::Unique.raw();
1545 assert_eq!(
1546 validate_known_diagnostic_fact_schema(
1547 ErrorCode::RUNTIME_BOUNDARY_CONSTRAINT_VIOLATION,
1548 non_targeted_path.as_slice(),
1549 ),
1550 Err(DiagnosticFactSchemaMismatch::InvalidSequence)
1551 );
1552 }
1553
1554 #[test]
1555 fn schema_enforces_global_ceiling_before_per_code_ceiling() {
1556 let facts = vec![(DiagnosticFactTag::ActualCount.raw(), 0); 81];
1557 assert_eq!(
1558 validate_raw_diagnostic_fact_schema(ErrorCode::QUERY_PLAN, facts.as_slice()),
1559 Err(DiagnosticFactSchemaMismatch::GlobalMaximumExceeded)
1560 );
1561 }
1562}