wyrd-spec 0.1.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::error::derive::WyrdError;

/// Public Bifrost error variants exchanged across HTTP, MCP, and the Python SDK.
#[derive(
    Clone,
    Debug,
    PartialEq,
    Eq,
    Error,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
    WyrdError,
    strum::EnumCount,
)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "variant", content = "data", rename_all = "snake_case")]
pub enum BifrostError {
    /// This server has no ready local Oracle role.
    #[error("Oracle role unavailable")]
    #[wyrd_error(
        code = "WYRD_VALA_503_ORACLE_ROLE_UNAVAILABLE",
        status = 503,
        title = "Oracle role unavailable",
        remediation = "Retry through an Oracle-ready query endpoint."
    )]
    OracleRoleUnavailable,

    /// No running query is visible for the authenticated tenant and request.
    #[error("running query not found")]
    #[wyrd_error(
        code = "WYRD_VALA_404_RUNNING_QUERY_NOT_FOUND",
        status = 404,
        title = "Running query not found",
        remediation = "Verify the request identity or list currently running queries for the authenticated tenant."
    )]
    RunningQueryNotFound,

    /// Current Oracle owners reported contradictory lifecycle authority.
    #[error("running query ownership conflict")]
    #[wyrd_error(
        code = "WYRD_VALA_409_RUNNING_QUERY_CONFLICT",
        status = 409,
        title = "Running query ownership conflict",
        remediation = "Do not retry cancellation automatically; investigate the contradictory Oracle owners."
    )]
    RunningQueryConflict,

    /// At least one current-ready Oracle could not answer lifecycle control.
    #[error("running query control unavailable")]
    #[wyrd_error(
        code = "WYRD_VALA_503_RUNNING_QUERY_CONTROL_UNAVAILABLE",
        status = 503,
        title = "Running query control unavailable",
        remediation = "Restore every current-ready Oracle lifecycle endpoint before retrying the logical operation."
    )]
    RunningQueryControlUnavailable,

    /// This server has no WAL-ready local Scribe role.
    #[error("Scribe role unavailable")]
    #[wyrd_error(
        code = "WYRD_VALA_503_SCRIBE_ROLE_UNAVAILABLE",
        status = 503,
        title = "Scribe role unavailable",
        remediation = "Retry ingest through a WAL-ready Scribe endpoint."
    )]
    ScribeRoleUnavailable,

    /// Query admission capacity was unavailable.
    #[error("query admission rejected")]
    #[wyrd_error(
        code = "WYRD_VALA_429_QUERY_ADMISSION_REJECTED",
        status = 429,
        title = "Query admission rejected",
        remediation = "Retry after the supplied bounded delay or reduce demand."
    )]
    QueryAdmissionRejected,

    /// Every waiting place in this pod's Oracle query queue is taken.
    ///
    /// Retryable overload: the query was refused immediately and holds no
    /// place, so a retry after capacity returns can succeed.
    #[error("query queue full")]
    #[wyrd_error(
        code = "WYRD_VALA_429_QUERY_QUEUE_FULL",
        status = 429,
        title = "Query queue full",
        remediation = "Retry after capacity becomes available."
    )]
    QueryQueueFull,

    /// An admitted query could not obtain the execution memory it needed.
    ///
    /// Not retryable as-is: the query failed inside its own ceiling and the
    /// shared Bifrost cap, so an unchanged retry meets the same limit.
    #[error("query resources exhausted")]
    #[wyrd_error(
        code = "WYRD_VALA_503_QUERY_RESOURCES_EXHAUSTED",
        status = 503,
        title = "Query resources exhausted",
        remediation = "Narrow the query or add capacity; retrying unchanged will not succeed."
    )]
    QueryResourcesExhausted,

    /// One indivisible query memory request exceeds its governing ceiling.
    #[error("query memory request too large")]
    #[wyrd_error(
        code = "WYRD_VALA_422_QUERY_MEMORY_REQUEST_TOO_LARGE",
        status = 422,
        title = "Query memory request too large",
        remediation = "Reduce the requested range or query memory footprint; retrying unchanged will not succeed."
    )]
    QueryMemoryRequestTooLarge,

    /// A required published query source could not be pinned or read.
    #[error("query visibility unavailable")]
    #[wyrd_error(
        code = "WYRD_VALA_503_QUERY_VISIBILITY_UNAVAILABLE",
        status = 503,
        title = "Query visibility unavailable",
        remediation = "Retry when the published query source is available."
    )]
    QueryVisibilityUnavailable,

    /// A row violated the authenticated tenant boundary.
    #[error("query tenant invariant violated")]
    #[wyrd_error(
        code = "WYRD_VALA_500_QUERY_TENANT_INVARIANT",
        status = 500,
        title = "Query tenant invariant violated",
        remediation = "Stop and investigate tenant isolation; never retry as caller input."
    )]
    QueryTenantInvariant,

    /// Cross-tier rows with one identity contained inconsistent values.
    #[error("query reconciliation invariant violated")]
    #[wyrd_error(
        code = "WYRD_VALA_500_QUERY_RECONCILIATION_INVARIANT",
        status = 500,
        title = "Query reconciliation invariant violated",
        remediation = "Stop and investigate cross-tier row corruption."
    )]
    QueryReconciliationInvariant,

    /// A peer credential, fence, or replay check failed.
    #[error("query peer security validation failed")]
    #[wyrd_error(
        code = "WYRD_VALA_403_QUERY_PEER_SECURITY",
        status = 403,
        title = "Query peer security validation failed",
        remediation = "Reject the peer attempt and investigate credential/fence/replay state."
    )]
    QueryPeerSecurity,

    /// A query stream violated the closed frame protocol.
    #[error("query stream protocol violation")]
    #[wyrd_error(
        code = "WYRD_VALA_502_QUERY_STREAM_PROTOCOL",
        status = 502,
        title = "Query stream protocol violation",
        remediation = "Discard partial output and retry through a healthy server."
    )]
    QueryStreamProtocol,

    /// A query stream ended without a terminal frame.
    #[error("query stream incomplete")]
    #[wyrd_error(
        code = "WYRD_VALA_502_QUERY_STREAM_INCOMPLETE",
        status = 502,
        title = "Query stream incomplete",
        remediation = "Discard partial output; retry because no terminal was observed."
    )]
    QueryStreamIncomplete,

    /// Query execution failed after the public stream began.
    #[error("query execution failed")]
    #[wyrd_error(
        code = "WYRD_VALA_500_QUERY_EXECUTION_FAILED",
        status = 500,
        title = "Query execution failed",
        remediation = "Inspect the scrubbed terminal error and server diagnostics before retrying."
    )]
    QueryExecutionFailed,

    /// The ingest authentication credentials were missing or rejected.
    #[error("ingest authentication failed: {message}")]
    #[wyrd_error(
        code = "WYRD_VALA_401_INGEST_AUTH",
        status = 401,
        title = "Ingest authentication failed",
        remediation = "Provide a valid Wyrd access token with permission to write the target ingest surface."
    )]
    IngestAuthentication {
        /// Human-readable authentication failure detail.
        message: String,
    },

    /// The ingest request violated the native protocol contract.
    #[error("ingest request validation failed: {message}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_INGEST_PROTO",
        status = 400,
        title = "Invalid ingest request",
        remediation = "Fix the ingest request fields and retry with a valid Wyrd ingest payload."
    )]
    IngestProtocol {
        /// Human-readable protocol validation detail.
        message: String,
    },

    /// A Bifrost schema, or a row value measured against it, failed to map.
    #[error("schema parse failed: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_SCHEMA_PARSE",
        status = 400,
        title = "Bifrost schema parse failed",
        remediation = "Correct the column type or the row value so it satisfies the table's declared DataTypeSpec; declare a Variant field for open data."
    )]
    SchemaParse {
        /// Human-readable schema or value validation detail.
        detail: String,
    },

    /// A Variant input value, or `parse_json` query text, is not valid JSON or
    /// not a valid Variant encoding.
    #[error("invalid Variant JSON in field {field} row {row} at {path}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_VARIANT_INVALID_JSON",
        status = 400,
        title = "Invalid Variant JSON",
        remediation = "Supply valid JSON text or a valid arrow.parquet.variant value for the Variant field; use try_parse_json in SQL to map invalid text to null."
    )]
    VariantInvalidJson {
        /// Logical field (or SQL function) whose value failed to convert.
        field: String,
        /// Zero-based input row of the failing value.
        row: u64,
        /// RFC 6901 JSON Pointer to the failing value inside the row value.
        path: String,
    },

    /// A JSON number fits no Variant numeric type.
    #[error("Variant {numeric_kind} value out of range in field {field} row {row} at {path}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_VARIANT_NUMERIC_OUT_OF_RANGE",
        status = 400,
        title = "Variant numeric value out of range",
        remediation = "Send integers within the signed 64-bit or Variant decimal range, or send the number as a string."
    )]
    VariantNumericOutOfRange {
        /// Logical field whose value failed to convert.
        field: String,
        /// Zero-based input row of the failing value.
        row: u64,
        /// RFC 6901 JSON Pointer to the failing number inside the row value.
        path: String,
        /// Numeric family that could not hold the value, such as `integer`.
        numeric_kind: String,
    },

    /// A Variant value nests deeper than the fixed Variant depth limit.
    #[error(
        "Variant value in field {field} row {row} nests {depth} levels, limit {limit} at {path}"
    )]
    #[wyrd_error(
        code = "WYRD_VALA_400_VARIANT_TOO_DEEP",
        status = 400,
        title = "Variant value too deep",
        remediation = "Flatten the value so it nests at most 64 levels, counting the root container as one."
    )]
    VariantTooDeep {
        /// Logical field whose value is too deep.
        field: String,
        /// Zero-based input row of the failing value.
        row: u64,
        /// RFC 6901 JSON Pointer to the first container past the limit.
        path: String,
        /// Depth reached at `path`, counting the root container as one.
        depth: u32,
        /// Fixed maximum Variant depth.
        limit: u32,
    },

    /// A Variant value encodes to more bytes than the fixed Variant size limit.
    #[error("Variant value in field {field} row {row} encodes {bytes} bytes, limit {limit}")]
    #[wyrd_error(
        code = "WYRD_VALA_413_VARIANT_TOO_LARGE",
        status = 413,
        title = "Variant value too large",
        remediation = "Keep each Variant value at most 8388608 encoded bytes (metadata plus value); split large payloads across rows."
    )]
    VariantTooLarge {
        /// Logical field whose value is too large.
        field: String,
        /// Zero-based input row of the failing value.
        row: u64,
        /// Canonical encoded Variant bytes, metadata plus value.
        bytes: u64,
        /// Fixed maximum encoded Variant bytes.
        limit: u64,
    },

    /// A write row names a key the table does not declare.
    #[error("undeclared field {field} in row {row}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_BIFROST_UNDECLARED_FIELD",
        status = 400,
        title = "Undeclared Bifrost field",
        remediation = "Remove the key or declare it on the table; store open data in a Variant field."
    )]
    UndeclaredField {
        /// Key the table does not declare.
        field: String,
        /// Zero-based input row that carried the key.
        row: u64,
    },

    /// A table field uses a type Bifrost cannot store, or a write supplies a
    /// type that does not match the declared field.
    #[error("unsupported type {data_type} for field {field}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_BIFROST_UNSUPPORTED_TYPE",
        status = 400,
        title = "Unsupported Bifrost type",
        remediation = "Use a supported Bifrost column type; store open data in a Variant field."
    )]
    UnsupportedType {
        /// Field whose type is unsupported.
        field: String,
        /// Rendered Arrow or declared type that was refused.
        data_type: String,
    },

    /// A user-supplied schema field uses a reserved system column name.
    #[error("reserved system column: {column}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_BIFROST_RESERVED_COLUMN",
        status = 400,
        title = "Reserved system column name",
        remediation = "Rename the column — run_id, card_uid, principal_id, wyrd_request_id, and wyrd_ingested_at are reserved."
    )]
    ReservedColumn {
        /// The reserved column name that was supplied.
        column: String,
    },

    /// A caller attempted to write a server-managed built-in table.
    #[error("write to reserved built-in table denied: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_403_BIFROST_RESERVED_BUILTIN_WRITE",
        status = 403,
        title = "Reserved built-in write denied",
        remediation = "Write through the supported observation or audit API instead of directly targeting a reserved built-in table."
    )]
    ReservedBuiltinWriteDenied {
        /// Fully-qualified table name that was refused.
        table: String,
    },

    /// A physical table schema is missing the required tenant isolation column.
    #[error("table missing data_tenant_id managed column: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_BIFROST_TENANT_ISOLATION_COLUMN_MISSING",
        status = 400,
        title = "Tenant isolation column missing",
        remediation = "Add the server-managed data_tenant_id Utf8 column to the physical table schema."
    )]
    TenantIsolationColumnMissing {
        /// Fully-qualified table name that is missing the tenant column.
        table: String,
    },

    /// No tenant binding was present when attempting an OLAP write or query.
    #[error("no tenant binding for OLAP operation")]
    #[wyrd_error(
        code = "WYRD_VALA_403_BIFROST_TENANT_BINDING_MISSING",
        status = 403,
        title = "No tenant binding for OLAP operation",
        remediation = "Acquire a TenantConn for a valid tenant before writing or querying Bifrost tables."
    )]
    TenantBindingMissing,

    /// The Card the caller attributed a write or call to is not within the
    /// authenticated principal's card scope, so it is refused.
    ///
    /// Gateway calls and observation writes share this denial; the caller
    /// already holds the `card_ref` or `card_uid` it sent.
    #[error("Card outside principal card scope")]
    #[wyrd_error(
        code = "WYRD_VALA_403_BIFROST_CARD_SCOPE",
        status = 403,
        title = "Card outside principal card scope",
        remediation = "Attribute the write or call to a Card the authenticated principal is authorized to tag, or add the target Card to the Service card's components."
    )]
    CardScopeDenied,

    /// A card reference could not be resolved to a tenant-local card UID.
    #[error("card_ref cannot be resolved: {card_ref}")]
    #[wyrd_error(
        code = "WYRD_VALA_403_CARD_UNRESOLVED",
        status = 403,
        title = "Card reference unresolved",
        remediation = "Use a card_ref that resolves to a registered card in the current tenant."
    )]
    CardUnresolved {
        /// Canonical card reference that could not be resolved.
        card_ref: String,
    },

    /// The authenticated subject/actor pair could not be stamped onto the ingest row.
    #[error("sub_principal_id and act_principal_id cannot be stamped for authenticated write")]
    #[wyrd_error(
        code = "WYRD_VALA_401_PRINCIPAL_UNRESOLVED",
        status = 401,
        title = "Ingest principal unresolved",
        remediation = "Authenticate with a token containing a valid principal identity and retry."
    )]
    PrincipalUnresolved,

    /// The requested Bifrost table does not exist in the catalog.
    #[error("bifrost table not found: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_404_BIFROST_TABLE_NOT_FOUND",
        status = 404,
        title = "Bifrost table not found",
        remediation = "Create the table via the catalog API before writing or querying."
    )]
    TableNotFound {
        /// Fully-qualified table name that was not found.
        table: String,
    },

    /// The Arrow schema fingerprint does not match the registered table schema.
    #[error("schema fingerprint mismatch for table: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_BIFROST_FINGERPRINT_MISMATCH",
        status = 409,
        title = "Schema fingerprint mismatch",
        remediation = "The Arrow schema does not match the registered table schema. Evolve the schema explicitly."
    )]
    FingerprintMismatch {
        /// Fully-qualified table name whose schema does not match.
        table: String,
    },

    /// A concurrent writer committed to the same table at the same time.
    #[error("concurrent commit conflict for table: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_BIFROST_COMMIT_CONFLICT",
        status = 409,
        title = "Concurrent OLAP commit conflict",
        remediation = "Retry the write — another writer committed to the same table concurrently."
    )]
    CommitConflict {
        /// Fully-qualified table name where the conflict occurred.
        table: String,
    },

    /// A batch with this ID was previously attempted but failed permanently.
    #[error("duplicate failed batch: {batch_id}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_BIFROST_DUPLICATE_FAILED_BATCH",
        status = 409,
        title = "Duplicate batch previously failed",
        remediation = "This batch_id was committed but the write failed. Use a new batch_id to retry."
    )]
    DuplicateFailedBatch {
        /// The idempotency batch ID that previously failed.
        batch_id: String,
    },

    /// The tail-fetch request targets a `(node_id, writer_epoch)` that does not
    /// match this Scribe's current writer stream (pod was replaced or restarted).
    #[error("live-tail stream mismatch: requested={requested}, actual={actual}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_STREAM_MISMATCH",
        status = 409,
        title = "Live-tail stream identity mismatch",
        remediation = "Refresh the Scribe stream identity from the cluster catalog and retry the tail-fetch against the current writer stream."
    )]
    StreamMismatch {
        /// The stream identity the caller requested (e.g. "node:epoch").
        requested: String,
        /// The stream identity this Scribe actually owns.
        actual: String,
    },

    /// Registered catalog metadata is inconsistent with the actual catalog state.
    #[error("catalog metadata inconsistency: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_500_BIFROST_METADATA_MISMATCH",
        status = 500,
        title = "Bifrost table metadata mismatch",
        remediation = "Investigate table metadata integrity; possible mid-flight schema-evolution race."
    )]
    MetadataMismatch {
        /// Human-readable description of the inconsistency.
        detail: String,
    },

    /// The OLAP catalog database is unreachable.
    #[error("OLAP catalog unreachable: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_503_BIFROST_CATALOG_UNREACHABLE",
        status = 503,
        title = "OLAP catalog unreachable",
        remediation = "Check the catalog database connection and retry."
    )]
    CatalogUnreachable {
        /// Underlying connectivity error detail.
        detail: String,
    },

    /// The OLAP object storage backend is unreachable.
    #[error("OLAP object storage unreachable: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_503_BIFROST_STORAGE_UNREACHABLE",
        status = 503,
        title = "OLAP object storage unreachable",
        remediation = "Check the object storage configuration and credentials, then retry."
    )]
    StorageUnreachable {
        /// Underlying connectivity error detail.
        detail: String,
    },

    /// The Bifrost writer actor for this table is not running.
    #[error("writer unavailable for table: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_503_BIFROST_WRITER_UNAVAILABLE",
        status = 503,
        title = "Bifrost writer unavailable",
        remediation = "The writer actor for this table is not running. Restart the write operation."
    )]
    WriterUnavailable {
        /// Fully-qualified table name whose writer is unavailable.
        table: String,
    },

    /// The submitted query SQL was not valid or not a supported `SELECT`.
    #[error("invalid or unsupported query SQL: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_QUERY_INVALID_SQL",
        status = 400,
        title = "Invalid or unsupported query SQL",
        remediation = "Submit a single SELECT statement; DDL/DML and unsupported constructs are rejected."
    )]
    QueryInvalidSql {
        /// Human-readable parse/validation detail.
        detail: String,
    },

    /// The query exceeded the configured execution time budget.
    #[error("query execution timed out")]
    #[wyrd_error(
        code = "WYRD_VALA_504_QUERY_TIMEOUT",
        status = 504,
        title = "Query execution timed out",
        remediation = "Narrow the query by adding filters or reducing scanned partitions."
    )]
    QueryTimeout,

    /// The query result exceeded the configured size limit.
    #[error("query result too large")]
    #[wyrd_error(
        code = "WYRD_VALA_413_QUERY_RESULT_TOO_LARGE",
        status = 413,
        title = "Query result too large",
        remediation = "Add a LIMIT or narrower filters for large result sets."
    )]
    QueryResultTooLarge,

    /// A client attempted a Bifrost write with no table bound as its target.
    ///
    /// Client-raised rather than server-raised: the SDK refuses the row before
    /// it can be routed anywhere. The metadata still lives in this catalog
    /// because it crosses the Rust, Python, and TypeScript boundaries, and a
    /// second hand-written copy per SDK is how the four fields drift apart.
    #[error("no active Bifrost table")]
    #[wyrd_error(
        code = "WYRD_VALA_412_NO_ACTIVE_TABLE",
        status = 412,
        title = "No active Bifrost table",
        remediation = "Bind a table with use_table or use_table_by_name before inserting rows."
    )]
    NoActiveTable,

    /// The decompressed canonical ingest payload exceeded the Scribe limit.
    ///
    /// Both bounds are public data: `bytes` is what the server measured and
    /// `limit` is the ceiling it actually enforced for this request. The limit
    /// is configured rather than universal, so callers must read it from the
    /// problem document instead of assuming a fixed transport ceiling.
    #[error("ingest payload too large: {bytes} bytes exceeds the {limit} byte limit")]
    #[wyrd_error(
        code = "WYRD_VALA_413_PAYLOAD_TOO_LARGE",
        status = 413,
        title = "Ingest payload too large",
        remediation = "Reduce the request below the enforced limit reported in this problem and retry."
    )]
    PayloadTooLarge {
        /// Server-measured canonical transport bytes.
        bytes: usize,
        /// Canonical transport byte ceiling enforced for this request.
        limit: usize,
    },

    /// An unexpected internal Bifrost failure occurred.
    #[error("internal bifrost failure: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_500_BIFROST_INTERNAL",
        status = 500,
        title = "Internal Bifrost failure",
        remediation = "Check server logs for details and contact support if the issue persists."
    )]
    Internal {
        /// Human-readable detail about the internal failure.
        detail: String,
    },

    /// A pre-declared domain table's schema fingerprint does not match the
    /// registered fingerprint — schema evolution happened without a coordinated
    /// migration. Operator action required.
    #[error("domain table schema fingerprint drift: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_500_SCHEMA_DRIFT",
        status = 500,
        title = "Domain table schema fingerprint drift",
        remediation = "A domain table schema changed without a coordinated migration. Restore the previous schema or run the migration runbook."
    )]
    SchemaDrift {
        /// Human-readable detail naming the table and the drift.
        detail: String,
    },

    /// A pre-declared domain table's physical Iceberg schema does not match the
    /// declared schema despite the fingerprint saying clean.
    #[error("domain table physical schema drift: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_500_PHYSICAL_DRIFT",
        status = 500,
        title = "Domain table physical schema drift",
        remediation = "The Iceberg table physical schema drifted from the declared schema. Run the repair runbook."
    )]
    PhysicalDrift {
        /// Human-readable detail naming the table and the drift.
        detail: String,
    },

    /// A pre-declared domain table's control row is present but the Iceberg
    /// table is missing — the table was dropped or is otherwise unreachable.
    #[error("domain table Iceberg table missing: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_500_ICEBERG_MISSING",
        status = 500,
        title = "Domain table Iceberg table missing",
        remediation = "The Iceberg table for a pre-declared domain table is missing. Run the restore runbook."
    )]
    IcebergMissing {
        /// Human-readable detail naming the affected table.
        detail: String,
    },

    /// The write-path redaction pass failed on a sensitive-payload table.
    /// The commit was refused; no raw secrets were written.
    #[error("write-path redaction failed: {0}")]
    #[wyrd_error(
        code = "WYRD_VALA_500_REDACTION_FAILED",
        status = 500,
        title = "Write-path redaction failed",
        remediation = "The redaction classifier failed on this batch. Retry; if it persists, check the classifier installation."
    )]
    RedactionFailed(String),

    /// The requested trace id was not found within the queried window.
    #[error("trace not found: {trace_id}")]
    #[wyrd_error(
        code = "WYRD_VALA_404_TRACE_NOT_FOUND",
        status = 404,
        title = "Trace not found",
        remediation = "Confirm the trace_id and that it falls within the queried time window."
    )]
    TraceNotFound {
        /// Trace id that was not found.
        trace_id: String,
    },

    /// A query was submitted without a time window.
    #[error("query time window required")]
    #[wyrd_error(
        code = "WYRD_VALA_400_WINDOW_REQUIRED",
        status = 400,
        title = "Query time window required",
        remediation = "Supply `since` and/or `until` on the query request."
    )]
    WindowRequired,

    /// A query filter value was invalid.
    #[error("query filter invalid: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_FILTER_INVALID",
        status = 400,
        title = "Query filter invalid",
        remediation = "Correct the filter value; see the error detail for the offending field."
    )]
    FilterInvalid {
        /// Description of the offending filter.
        detail: String,
    },

    /// The supplied page token failed verification.
    #[error("page token invalid")]
    #[wyrd_error(
        code = "WYRD_VALA_400_PAGE_TOKEN_INVALID",
        status = 400,
        title = "Page token invalid",
        remediation = "Restart the query from page 1 without a page_token."
    )]
    PageTokenInvalid,

    /// The Iceberg snapshot pinned by the page token has expired.
    #[error("page snapshot expired")]
    #[wyrd_error(
        code = "WYRD_VALA_410_PAGE_SNAPSHOT_EXPIRED",
        status = 410,
        title = "Page snapshot expired",
        remediation = "restart the query from page 1"
    )]
    PageSnapshotExpired,

    /// The principal lacks query permission for the table.
    #[error("query forbidden")]
    #[wyrd_error(
        code = "WYRD_VALA_403_QUERY_FORBIDDEN",
        status = 403,
        title = "Query forbidden",
        remediation = "The principal lacks bifrost_query:read for this table."
    )]
    QueryForbidden,

    /// The ingest writer's local buffer is full; the caller must retry.
    ///
    /// This is **local buffer backpressure only** — the per-physical-table
    /// coordinator's bounded channel is saturated. It does NOT indicate a
    /// partial success: no row from this request was written. Callers should
    /// back off and retry the full request.
    ///
    /// The OTLP ingest path maps overload to HTTP `429` and gRPC
    /// `RESOURCE_EXHAUSTED`, never to `partial_success`; no rows from the
    /// request are written.
    #[error("ingest writer busy: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_429_INGEST_BUSY",
        status = 429,
        title = "Ingest writer busy",
        remediation = "The per-table ingest buffer is full. Back off and retry the full request — no rows were written."
    )]
    IngestBusy {
        /// Fully-qualified table name whose writer buffer is saturated.
        table: String,
    },

    /// The WAL disk is full and cannot accept additional writes.
    ///
    /// This is a capacity error at the Scribe WAL layer. The operator must expand
    /// WAL storage capacity or trigger a seal to free space. No rows from this
    /// request were written.
    #[error("WAL disk full")]
    #[wyrd_error(
        code = "WYRD_VALA_507_WAL_DISK_FULL",
        status = 507,
        title = "WAL disk full",
        remediation = "The Scribe WAL disk is at capacity. Expand storage or wait for seal to free space, then retry."
    )]
    WalDiskFull,

    /// The OTLP request body was malformed and could not be decoded.
    ///
    /// Covers both protobuf decode failures and JSON parse errors on the
    /// OTLP/HTTP path. The request must be fixed before retrying — no rows
    /// were written and no retry will succeed with the same payload.
    #[error("OTLP request body malformed for table {table}: {detail}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_OTLP_REQUEST_MALFORMED",
        status = 400,
        title = "OTLP request body malformed",
        remediation = "The OTLP request body could not be decoded. Verify the Content-Type matches the encoding (application/x-protobuf or application/json) and that the payload is a valid OTLP ExportRequest."
    )]
    OtlpRequestMalformed {
        /// Fully-qualified table name the request was targeting.
        table: String,
        /// Human-readable decode error detail.
        detail: String,
    },

    /// A register request declared a physical layout Bifrost cannot canonicalize.
    ///
    /// The fault is reported before any SQL transaction, Iceberg call, or audit
    /// append, so no durable state changed. The triple
    /// (`field`, `violation`, `column`) names the exact declaration at fault.
    #[error("invalid physical layout for table {table}: {field:?}/{violation:?}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_BIFROST_INVALID_PHYSICAL_LAYOUT",
        status = 400,
        title = "Invalid Bifrost physical layout",
        remediation = "Declare hour or day granularity, an optional non-null timestamp time column, at most four unique schema columns as sort keys, and supported sort/null values."
    )]
    InvalidPhysicalLayout {
        /// Canonical `<namespace>.<name>` of the table being registered.
        table: String,
        /// Declaration slot that failed validation.
        field: PhysicalLayoutField,
        /// Why the declaration in `field` is not acceptable.
        violation: PhysicalLayoutViolation,
        /// Offending bounded schema/layout identifier when the fault names one.
        column: Option<String>,
    },

    /// A register retry supplied a valid layout that differs from the layout the
    /// table is already registered with.
    ///
    /// Fingerprint equality is checked first, so this variant means the schema
    /// matched and only the canonical physical layout diverged. Nothing was
    /// mutated.
    #[error("physical layout mismatch for table: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_BIFROST_LAYOUT_MISMATCH",
        status = 409,
        title = "Bifrost physical layout mismatch",
        remediation = "Retry with the table's registered physical layout or register a different table."
    )]
    PhysicalLayoutMismatch {
        /// Canonical `<namespace>.<name>` of the conflicting table.
        table: String,
    },

    /// A register call supplied a compaction file target Forge could not honor.
    ///
    /// The target must be representable on the server, safe under Forge's
    /// oversized-file arithmetic, above the default small-file threshold, and
    /// at least the table's row-group target. Reported before any durable
    /// state changes.
    #[error("invalid compaction target file size {bytes} for table {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_400_BIFROST_INVALID_COMPACTION_TARGET",
        status = 400,
        title = "Invalid Bifrost compaction target",
        remediation = "Omit compaction_target_file_size_bytes to follow the deployment default, or supply at least 134217728 bytes."
    )]
    InvalidCompactionTarget {
        /// Canonical `<namespace>.<name>` of the table being registered.
        table: String,
        /// The rejected byte count.
        bytes: u64,
    },

    /// A register retry supplied a compaction file target that differs from
    /// the table's existing explicit target, or supplied one for a table that
    /// follows the deployment default.
    #[error("compaction target mismatch for table: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_BIFROST_COMPACTION_TARGET_MISMATCH",
        status = 409,
        title = "Bifrost compaction target mismatch",
        remediation = "Retry with the table's registered compaction target, omit it, or register a different table."
    )]
    CompactionTargetMismatch {
        /// Canonical `<namespace>.<name>` of the conflicting table.
        table: String,
    },

    /// A register retry supplied a compaction type that differs from the
    /// table's existing explicit type, or supplied one for a table that
    /// compacts with the default `small-files` type without declaring it.
    #[error("compaction type mismatch for table: {table}")]
    #[wyrd_error(
        code = "WYRD_VALA_409_BIFROST_COMPACTION_TYPE_MISMATCH",
        status = 409,
        title = "Bifrost compaction type mismatch",
        remediation = "Retry with the table's registered compaction type, omit it, or register a different table."
    )]
    CompactionTypeMismatch {
        /// Canonical `<namespace>.<name>` of the conflicting table.
        table: String,
    },
}

/// Declaration slot named by [`BifrostError::InvalidPhysicalLayout`].
///
/// Each variant maps one-to-one onto a field of the public
/// `PhysicalLayoutWire` request shape so a client can point at the exact
/// declaration it must correct.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum PhysicalLayoutField {
    /// The `partition` object itself, including its required presence.
    Partition,
    /// The partition's `granularity` token.
    Granularity,
    /// An entry of `sort_keys`, identified by its `column`.
    SortKey,
    /// A sort key's `direction` token.
    SortDirection,
    /// A sort key's `null_order` token.
    NullOrder,
    /// An entry of `bloom_columns`.
    BloomColumn,
    /// The `time_column` the table partitions and sorts on.
    TimeColumn,
}

/// Why the declaration named by [`PhysicalLayoutField`] was rejected.
///
/// The set is closed so SDKs can branch on it without parsing prose; no backend
/// or parser message crosses the public boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum PhysicalLayoutViolation {
    /// A required declaration was absent.
    Missing,
    /// The same identifier was declared more than once in one list.
    Duplicate,
    /// More sort keys were declared than the layout contract admits.
    TooManyKeys,
    /// The declaration referenced a name absent from the physical schema.
    UnknownColumn,
    /// The column exists but cannot serve this declaration slot.
    UnsupportedColumn,
    /// The token is outside the closed set this slot accepts.
    UnsupportedValue,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every declaration slot in the public layout contract, in declaration order.
    const ALL_FIELDS: [PhysicalLayoutField; 7] = [
        PhysicalLayoutField::Partition,
        PhysicalLayoutField::Granularity,
        PhysicalLayoutField::TimeColumn,
        PhysicalLayoutField::SortKey,
        PhysicalLayoutField::SortDirection,
        PhysicalLayoutField::NullOrder,
        PhysicalLayoutField::BloomColumn,
    ];

    /// Every rejection class in the public layout contract, in declaration order.
    const ALL_VIOLATIONS: [PhysicalLayoutViolation; 6] = [
        PhysicalLayoutViolation::Missing,
        PhysicalLayoutViolation::Duplicate,
        PhysicalLayoutViolation::TooManyKeys,
        PhysicalLayoutViolation::UnknownColumn,
        PhysicalLayoutViolation::UnsupportedColumn,
        PhysicalLayoutViolation::UnsupportedValue,
    ];

    /// Pins the generated code/status of both layout errors and proves every
    /// `(field, violation)` pair survives a public serde round trip carrying only
    /// bounded identifiers.
    #[test]
    fn physical_layout_error_contract() {
        let mismatch = BifrostError::PhysicalLayoutMismatch {
            table: "obs.events".to_owned(),
        };
        assert_eq!(mismatch.code(), "WYRD_VALA_409_BIFROST_LAYOUT_MISMATCH");
        assert_eq!(mismatch.status(), 409);

        for field in ALL_FIELDS {
            for violation in ALL_VIOLATIONS {
                for column in [None, Some("start_time_unix_nano".to_owned())] {
                    let error = BifrostError::InvalidPhysicalLayout {
                        table: "obs.events".to_owned(),
                        field,
                        violation,
                        column: column.clone(),
                    };
                    assert_eq!(
                        error.code(),
                        "WYRD_VALA_400_BIFROST_INVALID_PHYSICAL_LAYOUT"
                    );
                    assert_eq!(error.status(), 400);

                    let json = serde_json::to_string(&error).expect("layout error serializes");
                    let restored: BifrostError =
                        serde_json::from_str(&json).expect("layout error deserializes");
                    assert_eq!(restored, error);
                    assert!(
                        !json.contains("panic") && json.len() < 512,
                        "public layout error must stay bounded: {json}"
                    );
                }
            }
        }
    }

    /// Proves the ingest payload ceiling is carried as structured data rather than
    /// being frozen into prose: the enforced `limit` travels beside the measured
    /// `bytes` through the public catalog projection, so a caller reading only the
    /// problem document can compute how far over the configured ceiling it went.
    ///
    /// # Panics
    ///
    /// Panics when the code, status, structured details, or remediation drift from
    /// the durable public contract.
    #[test]
    fn payload_too_large_reports_the_enforced_limit() {
        let error = BifrostError::PayloadTooLarge {
            bytes: 41_943_040,
            limit: 8_388_608,
        };
        assert_eq!(error.code(), "WYRD_VALA_413_PAYLOAD_TOO_LARGE");
        assert_eq!(error.status(), 413);

        let details = serde_json::to_value(&error).expect("payload error serializes");
        assert_eq!(
            details["data"]["bytes"], 41_943_040,
            "measured transport bytes must survive the public projection: {details}"
        );
        assert_eq!(
            details["data"]["limit"], 8_388_608,
            "the enforced ceiling must survive the public projection: {details}"
        );

        let remediation = error.remediation();
        assert!(
            !remediation.contains("32 MiB"),
            "remediation must not assert a fixed ceiling that contradicts the \
             supplied limit: {remediation}"
        );
        assert!(
            remediation.contains("limit"),
            "remediation must point the caller at the supplied limit: {remediation}"
        );
    }

    /// Confirms the closed token vocabulary is snake_case on the wire so SDKs can
    /// branch on the exact strings the generated schemas publish.
    #[test]
    fn physical_layout_tokens_are_snake_case() {
        assert_eq!(
            serde_json::to_string(&PhysicalLayoutViolation::TooManyKeys)
                .expect("violation serializes"),
            "\"too_many_keys\""
        );
        assert_eq!(
            serde_json::to_string(&PhysicalLayoutField::SortDirection).expect("field serializes"),
            "\"sort_direction\""
        );
    }
}