riffdb-types 0.1.0

First-party RiffDB runtime crate (riffdb-types)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
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
//! Versioned, domain-separated SHA-256 and HMAC-SHA-256 digests.

use std::fmt;

use hmac::{Hmac, KeyInit, Mac};
use sha2::{Digest, Sha256};

use crate::{
    AdapterConformanceManifestHash, ApplicationExportManifestHash, ApplicationExportPageHash,
    ApplicationExportReceiptHash, ApplicationInstallationPlanHash,
    ApplicationInstallationReceiptHash, ApplicationLockHash, ApplicationManifestHash,
    ApplicationPortabilityManifestHash, ApplicationReimportReceiptHash,
    ApplicationRoleDefinitionHash, ApplicationRoleHash, ApplicationSourceHash, CanonicalInputHash,
    CanonicalValueHash, CapabilityTokenDigest, ColumnarDefinitionSemanticsHashV1,
    ColumnarProjectionSpecHashV1, ConflictKeyHash, ContractBundleHash, ContractMigrationInputHash,
    ContractMigrationJournalHash, ContractMigrationValidationDigest, ContractPlanRootHash,
    DigestKey, DigestKeyId, EntityKeyHash, EntityRecordHash, EntityTransitionHash,
    EventConsumerIdentityHash, EventHash, GeneratedArtifactHash, MigrationBundleHash,
    MigrationSourceHash, OfflineMaintenanceInputHash, PartitionKeyHash,
    PartitionSetObservationHash, PlanHash, ProjectionApplyHash, ProjectionPlanHash,
    ProjectionProviderDescriptorHash, QueryModuleHash, QueryParameterHash, QueryPlanHash,
    QuerySourceHash, ReactiveModuleHash, ReactiveOperationHash, ReactiveSourceHash,
    ScheduledAttemptHash, SchemaHash, SourceHash,
};

/// Hash framing and algorithm scheme defined by ADR-0011.
pub const DIGEST_SCHEME_V1: u8 = 0x01;

const HASH_PREFIX: &[u8] = b"RIFFDB-HASH\0";
const HMAC_PREFIX: &[u8] = b"RIFFDB-HMAC\0";

/// An unkeyed SHA-256 domain from the accepted central registry.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum HashDomain {
    /// Canonical value content.
    CanonicalValue,
    /// Canonical contract source.
    Source,
    /// Exact migration source document.
    MigrationSource,
    /// Canonical contract bundle.
    ContractBundle,
    /// Canonical compiled migration bundle.
    MigrationBundle,
    /// Executable command plan.
    Plan,
    /// Validated projection plan.
    ProjectionPlan,
    /// Canonical sealed projection-provider descriptor.
    ProjectionProviderDescriptor,
    /// Closed RiffQL query access program.
    QueryPlan,
    /// Ordered selected partition/index/provider epoch observations.
    PartitionSetObservation,
    /// Canonical immutable query module.
    QueryModule,
    /// Exact reactive source document.
    ReactiveSource,
    /// Canonical reactive operation plan.
    ReactiveOperation,
    /// Canonical immutable reactive module.
    ReactiveModule,
    /// Exact durable event consumer identity.
    EventConsumerIdentity,
    /// Canonical application manifest.
    ApplicationManifest,
    /// Author-owned symbolic application source manifest.
    ApplicationSource,
    /// Compiler-owned exact application lock.
    ApplicationLock,
    /// Compiler-generated application artifact.
    GeneratedArtifact,
    /// Exact tenant-unbound application role definition.
    ApplicationRoleDefinition,
    /// Canonical compiled application role.
    ApplicationRole,
    /// Exact RiffQL source document.
    QuerySource,
    /// Canonical name-addressed RiffQL parameter set.
    QueryParameters,
    /// Ordered semantic plan set for one contract bundle.
    ContractPlanRoot,
    /// Canonical command input.
    CommandInput,
    /// Durable event content.
    Event,
    /// Complete canonical entity-record preimage.
    EntityRecord,
    /// One canonical committed entity transition.
    EntityTransition,
    /// Canonical entity key.
    EntityKey,
    /// Canonical conflict key.
    ConflictKey,
    /// Canonical logical partition key.
    PartitionKey,
    /// Generated schema content.
    Schema,
    /// One complete checked projection apply request.
    ProjectionApply,
    /// One checked offline-maintenance semantic input.
    OfflineMaintenanceInput,
    /// One checked contract-migration semantic input.
    ContractMigrationInput,
    /// One canonical contract-migration journal state.
    ContractMigrationJournal,
    /// One complete staged contract-migration validation.
    ContractMigrationValidation,
    /// One bounded command-batch source, item, or checkpoint document.
    CommandBatch,
    /// Generated contextual-reaction idempotency.
    ContextualReaction,
    /// Opaque MCP reactive-resource wakeup generation.
    ReactiveWakeup,
    /// One bounded scheduled workflow attempt.
    ScheduledAttempt,
    /// One canonical application installation plan.
    ApplicationInstallationPlan,
    /// One canonical terminal installation receipt.
    ApplicationInstallationReceipt,
    /// One canonical adapter conformance manifest.
    AdapterConformanceManifest,
    /// One canonical page of symbolic application-export records.
    ApplicationExportPage,
    /// One canonical symbolic application-export manifest.
    ApplicationExportManifest,
    /// One terminal symbolic application-export receipt.
    ApplicationExportReceipt,
    /// One opaque checkpoint cursor for a symbolic application export.
    ApplicationExportCursor,
    /// Immutable export genesis and ordered page-ledger prefix (ADR-0232).
    ApplicationExportLedger,
    /// One adapter-owned compiled reimport mapping manifest.
    ApplicationPortabilityManifest,
    /// One terminal application reimport reconciliation receipt.
    ApplicationReimportReceipt,
    /// One complete exact-result provider activation checkpoint.
    ExactResultCheckpoint,
    /// One schema-bound columnar definition or complete projection specification.
    ColumnarProjectionSpec,
    /// Canonical independently evaluated authoritative projection source rows.
    ProjectionSourceRows,
    /// Immutable authoritative projection replay-source descriptor.
    ProjectionSourceDescriptor,
    /// Captured authoritative projection source origin commitment.
    ProjectionSourceOrigin,
    /// Per-row canonical copy progress of one immutable replay-source candidate.
    ProjectionSourceCopyProgress,
}

impl HashDomain {
    /// Every registered unkeyed domain, for compatibility and collision checks.
    pub const ALL: [Self; 57] = [
        Self::CanonicalValue,
        Self::Source,
        Self::MigrationSource,
        Self::ContractBundle,
        Self::MigrationBundle,
        Self::Plan,
        Self::ProjectionPlan,
        Self::ProjectionProviderDescriptor,
        Self::QueryPlan,
        Self::PartitionSetObservation,
        Self::QueryModule,
        Self::ReactiveSource,
        Self::ReactiveOperation,
        Self::ReactiveModule,
        Self::EventConsumerIdentity,
        Self::ApplicationManifest,
        Self::ApplicationSource,
        Self::ApplicationLock,
        Self::GeneratedArtifact,
        Self::ApplicationRoleDefinition,
        Self::ApplicationRole,
        Self::QuerySource,
        Self::QueryParameters,
        Self::ContractPlanRoot,
        Self::CommandInput,
        Self::Event,
        Self::EntityRecord,
        Self::EntityTransition,
        Self::EntityKey,
        Self::ConflictKey,
        Self::PartitionKey,
        Self::Schema,
        Self::ProjectionApply,
        Self::OfflineMaintenanceInput,
        Self::ContractMigrationInput,
        Self::ContractMigrationJournal,
        Self::ContractMigrationValidation,
        Self::CommandBatch,
        Self::ContextualReaction,
        Self::ReactiveWakeup,
        Self::ScheduledAttempt,
        Self::ApplicationInstallationPlan,
        Self::ApplicationInstallationReceipt,
        Self::AdapterConformanceManifest,
        Self::ApplicationExportPage,
        Self::ApplicationExportManifest,
        Self::ApplicationExportReceipt,
        Self::ApplicationExportCursor,
        Self::ApplicationExportLedger,
        Self::ApplicationPortabilityManifest,
        Self::ApplicationReimportReceipt,
        Self::ExactResultCheckpoint,
        Self::ColumnarProjectionSpec,
        Self::ProjectionSourceRows,
        Self::ProjectionSourceDescriptor,
        Self::ProjectionSourceOrigin,
        Self::ProjectionSourceCopyProgress,
    ];

    /// Returns the immutable ASCII v1 domain label.
    pub const fn label(self) -> &'static str {
        match self {
            Self::CanonicalValue => "riffdb.canonical-value/v1",
            Self::Source => "riffdb.source/v1",
            Self::MigrationSource => "riffdb.migration-source/v1",
            Self::ContractBundle => "riffdb.contract-bundle/v1",
            Self::MigrationBundle => "riffdb.migration-bundle/v1",
            Self::Plan => "riffdb.plan/v1",
            Self::ProjectionPlan => "riffdb.projection-plan/v1",
            Self::ProjectionProviderDescriptor => "riffdb.projection-provider-descriptor/v1",
            Self::QueryPlan => "riffdb.query-plan/v1",
            Self::PartitionSetObservation => "riffdb.partition-set-observation/v1",
            Self::QueryModule => "riffdb.query-module/v1",
            Self::ReactiveSource => "riffdb.reactive-source/v1",
            Self::ReactiveOperation => "riffdb.reactive-operation/v1",
            Self::ReactiveModule => "riffdb.reactive-module/v1",
            Self::EventConsumerIdentity => "riffdb.event-consumer-identity/v1",
            Self::ApplicationManifest => "riffdb.application-manifest/v1",
            Self::ApplicationSource => "riffdb.application-source/v1",
            Self::ApplicationLock => "riffdb.application-lock/v1",
            Self::GeneratedArtifact => "riffdb.generated-artifact/v1",
            Self::ApplicationRoleDefinition => "riffdb.application-role-definition/v1",
            Self::ApplicationRole => "riffdb.application-role/v1",
            Self::QuerySource => "riffdb.query-source/v1",
            Self::QueryParameters => "riffdb.query-parameters/v1",
            Self::ContractPlanRoot => "riffdb.contract-plan-root/v1",
            Self::CommandInput => "riffdb.command-input/v1",
            Self::Event => "riffdb.event/v1",
            Self::EntityRecord => "riffdb.entity-record/v1",
            Self::EntityTransition => "riffdb.entity-transition/v1",
            Self::EntityKey => "riffdb.entity-key/v1",
            Self::ConflictKey => "riffdb.conflict-key/v1",
            Self::PartitionKey => "riffdb.partition-key/v1",
            Self::Schema => "riffdb.schema/v1",
            Self::ProjectionApply => "riffdb.projection-apply/v1",
            Self::OfflineMaintenanceInput => "riffdb.offline-maintenance-input/v1",
            Self::ContractMigrationInput => "riffdb.contract-migration-input/v1",
            Self::ContractMigrationJournal => "riffdb.contract-migration-journal/v1",
            Self::ContractMigrationValidation => "riffdb.contract-migration-validation/v1",
            Self::CommandBatch => "riffdb.command-batch/v1",
            Self::ContextualReaction => "riffdb.contextual-reaction/v1",
            Self::ReactiveWakeup => "riffdb.reactive-wakeup/v1",
            Self::ScheduledAttempt => "riffdb.scheduled-attempt/v1",
            Self::ApplicationInstallationPlan => "riffdb.application-installation-plan/v1",
            Self::ApplicationInstallationReceipt => "riffdb.application-installation-receipt/v1",
            Self::AdapterConformanceManifest => "riffdb.adapter-conformance-manifest/v1",
            Self::ApplicationExportPage => "riffdb.application-export-page/v1",
            Self::ApplicationExportManifest => "riffdb.application-export-manifest/v1",
            Self::ApplicationExportReceipt => "riffdb.application-export-receipt/v1",
            Self::ApplicationExportCursor => "riffdb.application-export-cursor/v1",
            Self::ApplicationExportLedger => "riffdb.application-export-ledger/v1",
            Self::ApplicationPortabilityManifest => "riffdb.application-portability-manifest/v1",
            Self::ApplicationReimportReceipt => "riffdb.application-reimport-receipt/v1",
            Self::ExactResultCheckpoint => "riffdb.exact-result-checkpoint/v1",
            Self::ColumnarProjectionSpec => "riffdb.columnar-projection-spec/v1",
            Self::ProjectionSourceRows => "riffdb.projection-source-rows/v1",
            Self::ProjectionSourceDescriptor => "riffdb.projection-source-descriptor/v1",
            Self::ProjectionSourceOrigin => "riffdb.projection-source-origin/v1",
            Self::ProjectionSourceCopyProgress => "riffdb.projection-source-copy-progress/v1",
        }
    }
}

/// A keyed HMAC-SHA-256 domain from the accepted central registry.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum KeyedHashDomain {
    /// Caller-provided idempotency key lookup.
    IdempotencyKey,
    /// Decoded opaque capability-token lookup.
    CapabilityToken,
    /// Server-sealed contextual causation token.
    ContextualCausation,
}

impl KeyedHashDomain {
    /// Every registered keyed domain, for compatibility and collision checks.
    pub const ALL: [Self; 3] = [
        Self::IdempotencyKey,
        Self::CapabilityToken,
        Self::ContextualCausation,
    ];

    /// Returns the immutable ASCII v1 domain label.
    pub const fn label(self) -> &'static str {
        match self {
            Self::IdempotencyKey => "riffdb.idempotency-key/v1",
            Self::CapabilityToken => "riffdb.capability-token/v1",
            Self::ContextualCausation => "riffdb.contextual-causation/v1",
        }
    }
}

/// A versioned unkeyed content digest.
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ContentDigest {
    scheme: u8,
    domain: HashDomain,
    bytes: [u8; 32],
}

impl ContentDigest {
    const fn new(domain: HashDomain, bytes: [u8; 32]) -> Self {
        Self {
            scheme: DIGEST_SCHEME_V1,
            domain,
            bytes,
        }
    }

    /// Reconstructs a supported stored digest representation.
    ///
    /// This checks the scheme only. It does not verify a preimage, publication,
    /// source ancestry, or authority. Callers must check the expected domain and
    /// independently verify the authoritative bytes before using the digest.
    #[must_use]
    pub const fn from_stored_parts(
        scheme: u8,
        domain: HashDomain,
        bytes: [u8; 32],
    ) -> Option<Self> {
        if scheme != DIGEST_SCHEME_V1 {
            return None;
        }
        Some(Self::new(domain, bytes))
    }

    /// Returns the hash scheme version.
    pub const fn scheme(self) -> u8 {
        self.scheme
    }

    /// Returns the immutable semantic domain used to calculate the digest.
    pub const fn domain(self) -> HashDomain {
        self.domain
    }

    /// Returns the 32 digest bytes.
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.bytes
    }
}

impl fmt::Debug for ContentDigest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ContentDigest")
            .field("scheme", &self.scheme)
            .field("domain", &self.domain)
            .field("bytes", &HexDigest(&self.bytes))
            .finish()
    }
}

/// A versioned keyed digest that records the selected key ID without exposing
/// key material.
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct KeyedDigest {
    scheme: u8,
    key_id: DigestKeyId,
    bytes: [u8; 32],
}

impl KeyedDigest {
    /// Constructs a v1 keyed digest from its key ID and digest bytes.
    pub const fn new(key_id: DigestKeyId, bytes: [u8; 32]) -> Self {
        Self {
            scheme: DIGEST_SCHEME_V1,
            key_id,
            bytes,
        }
    }

    /// Returns the HMAC scheme version.
    pub const fn scheme(self) -> u8 {
        self.scheme
    }

    /// Returns the non-secret digest-key identifier.
    pub const fn key_id(self) -> DigestKeyId {
        self.key_id
    }

    /// Returns the 32 digest bytes.
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.bytes
    }
}

impl fmt::Debug for KeyedDigest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("KeyedDigest")
            .field("scheme", &self.scheme)
            .field("key_id", &self.key_id)
            .field("bytes", &"[REDACTED]")
            .finish()
    }
}

/// Computes a domain-separated v1 SHA-256 content digest.
pub fn hash(domain: HashDomain, payload: &[u8]) -> ContentDigest {
    let mut hasher = Sha256::new();
    write_frame(&mut hasher, HASH_PREFIX, domain.label(), payload);
    ContentDigest::new(domain, hasher.finalize().into())
}

/// A streamed payload did not match its declared v1 frame length.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HashLengthMismatch;

impl fmt::Display for HashLengthMismatch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("content hash payload length mismatch")
    }
}

impl std::error::Error for HashLengthMismatch {}

/// Constant-space v1 content hashing with an exact, checked payload length.
///
/// The length precedes the payload in the immutable v1 framing. Callers must
/// measure and stream the same immutable input. Excess input poisons the
/// hasher; neither incomplete nor poisoned input can produce a digest.
pub struct ContentHasher {
    hasher: Sha256,
    domain: HashDomain,
    remaining: Option<u64>,
}

impl fmt::Debug for ContentHasher {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ContentHasher([REDACTED])")
    }
}

impl ContentHasher {
    /// Starts an exact-length, domain-separated SHA-256 v1 frame.
    #[must_use]
    pub fn new(domain: HashDomain, payload_length: u64) -> Self {
        let mut hasher = Sha256::new();
        write_frame_header(&mut hasher, HASH_PREFIX, domain.label(), payload_length);
        Self {
            hasher,
            domain,
            remaining: Some(payload_length),
        }
    }

    /// Adds bytes without buffering them, refusing and poisoning excess input.
    pub fn update(&mut self, payload: &[u8]) -> Result<(), HashLengthMismatch> {
        self.remaining = self.remaining.and_then(|remaining| {
            u64::try_from(payload.len())
                .ok()
                .and_then(|length| remaining.checked_sub(length))
        });
        if self.remaining.is_none() {
            return Err(HashLengthMismatch);
        }
        Digest::update(&mut self.hasher, payload);
        Ok(())
    }

    /// Finishes only after exactly the declared number of bytes was supplied.
    pub fn finish(self) -> Result<ContentDigest, HashLengthMismatch> {
        if self.remaining != Some(0) {
            return Err(HashLengthMismatch);
        }
        Ok(ContentDigest::new(
            self.domain,
            self.hasher.finalize().into(),
        ))
    }
}

/// Hashes one bounded command-batch source, item, or checkpoint document.
#[must_use]
pub fn hash_command_batch_document(payload: &[u8]) -> ContentDigest {
    hash(HashDomain::CommandBatch, payload)
}

macro_rules! typed_hash_function {
    ($(#[$meta:meta])* $name:ident, $domain:ident, $output:ident) => {
        $(#[$meta])*
        #[must_use]
        pub fn $name(payload: &[u8]) -> $output {
            $output::from_bytes(*hash(HashDomain::$domain, payload).as_bytes())
        }
    };
}

typed_hash_function!(
    /// Hashes a canonical value document in its immutable v1 domain.
    hash_canonical_value,
    CanonicalValue,
    CanonicalValueHash
);

typed_hash_function!(
    /// Hashes one purpose-framed canonical columnar definition-semantics document.
    hash_columnar_definition_semantics,
    ColumnarProjectionSpec,
    ColumnarDefinitionSemanticsHashV1
);
typed_hash_function!(
    /// Hashes one purpose-framed complete schema-bound columnar specification.
    hash_columnar_projection_spec,
    ColumnarProjectionSpec,
    ColumnarProjectionSpecHashV1
);
typed_hash_function!(
    /// Hashes canonical contract source in its immutable v1 domain.
    hash_source,
    Source,
    SourceHash
);
typed_hash_function!(
    /// Hashes one exact migration source document in its immutable v1 domain.
    hash_migration_source,
    MigrationSource,
    MigrationSourceHash
);
typed_hash_function!(
    /// Hashes an immutable contract bundle in its v1 domain.
    hash_contract_bundle,
    ContractBundle,
    ContractBundleHash
);
typed_hash_function!(
    /// Hashes one canonical compiled migration bundle in its immutable v1 domain.
    hash_migration_bundle,
    MigrationBundle,
    MigrationBundleHash
);
typed_hash_function!(
    /// Hashes an executable command plan in its immutable v1 domain.
    hash_plan,
    Plan,
    PlanHash
);
typed_hash_function!(
    /// Hashes a validated projection plan in its immutable v1 domain.
    hash_projection_plan,
    ProjectionPlan,
    ProjectionPlanHash
);
typed_hash_function!(
    /// Hashes a canonical sealed projection-provider descriptor.
    hash_projection_provider_descriptor,
    ProjectionProviderDescriptor,
    ProjectionProviderDescriptorHash
);
typed_hash_function!(
    /// Hashes a closed RiffQL query access program in its immutable v1 domain.
    hash_query_plan,
    QueryPlan,
    QueryPlanHash
);
typed_hash_function!(
    /// Hashes ordered bounded partition/index/provider epoch observations.
    hash_partition_set_observation,
    PartitionSetObservation,
    PartitionSetObservationHash
);
typed_hash_function!(
    /// Hashes a canonical immutable query module in its immutable v1 domain.
    hash_query_module,
    QueryModule,
    QueryModuleHash
);
typed_hash_function!(
    /// Hashes one exact reactive source document.
    hash_reactive_source,
    ReactiveSource,
    ReactiveSourceHash
);
typed_hash_function!(
    /// Hashes one canonical reactive operation plan.
    hash_reactive_operation,
    ReactiveOperation,
    ReactiveOperationHash
);
typed_hash_function!(
    /// Hashes one canonical immutable reactive module.
    hash_reactive_module,
    ReactiveModule,
    ReactiveModuleHash
);
typed_hash_function!(
    /// Hashes one exact durable event consumer identity.
    hash_event_consumer_identity,
    EventConsumerIdentity,
    EventConsumerIdentityHash
);
typed_hash_function!(
    /// Hashes one canonical bounded scheduled workflow attempt.
    hash_scheduled_attempt,
    ScheduledAttempt,
    ScheduledAttemptHash
);
typed_hash_function!(
    /// Hashes one canonical exact application installation plan.
    hash_application_installation_plan,
    ApplicationInstallationPlan,
    ApplicationInstallationPlanHash
);
typed_hash_function!(
    /// Hashes one canonical terminal application installation receipt.
    hash_application_installation_receipt,
    ApplicationInstallationReceipt,
    ApplicationInstallationReceiptHash
);
typed_hash_function!(
    /// Hashes one canonical adapter conformance manifest.
    hash_adapter_conformance_manifest,
    AdapterConformanceManifest,
    AdapterConformanceManifestHash
);
typed_hash_function!(
    /// Hashes one canonical symbolic application-export page.
    hash_application_export_page,
    ApplicationExportPage,
    ApplicationExportPageHash
);
typed_hash_function!(
    /// Hashes one canonical symbolic application-export manifest.
    hash_application_export_manifest,
    ApplicationExportManifest,
    ApplicationExportManifestHash
);
typed_hash_function!(
    /// Hashes one terminal symbolic application-export receipt.
    hash_application_export_receipt,
    ApplicationExportReceipt,
    ApplicationExportReceiptHash
);
typed_hash_function!(
    /// Hashes one adapter-owned compiled reimport mapping manifest.
    hash_application_portability_manifest,
    ApplicationPortabilityManifest,
    ApplicationPortabilityManifestHash
);
typed_hash_function!(
    /// Hashes one terminal application reimport reconciliation receipt.
    hash_application_reimport_receipt,
    ApplicationReimportReceipt,
    ApplicationReimportReceiptHash
);
typed_hash_function!(
    /// Hashes one canonical application manifest in its immutable v1 domain.
    hash_application_manifest,
    ApplicationManifest,
    ApplicationManifestHash
);
typed_hash_function!(
    /// Hashes one canonical symbolic application source manifest.
    hash_application_source,
    ApplicationSource,
    ApplicationSourceHash
);
typed_hash_function!(
    /// Hashes one canonical compiler-owned application lock.
    hash_application_lock,
    ApplicationLock,
    ApplicationLockHash
);
typed_hash_function!(
    /// Hashes one compiler-generated application artifact.
    hash_generated_artifact,
    GeneratedArtifact,
    GeneratedArtifactHash
);
typed_hash_function!(
    /// Hashes one exact tenant-unbound application role definition.
    hash_application_role_definition,
    ApplicationRoleDefinition,
    ApplicationRoleDefinitionHash
);
typed_hash_function!(
    /// Hashes one canonical compiled application role in its immutable v1 domain.
    hash_application_role,
    ApplicationRole,
    ApplicationRoleHash
);
typed_hash_function!(
    /// Hashes one exact RiffQL source document in its immutable v1 domain.
    hash_query_source,
    QuerySource,
    QuerySourceHash
);
typed_hash_function!(
    /// Hashes one canonical name-addressed RiffQL parameter set.
    hash_query_parameters,
    QueryParameters,
    QueryParameterHash
);
typed_hash_function!(
    /// Hashes an ordered contract semantic-plan set in its immutable v1 domain.
    hash_contract_plan_root,
    ContractPlanRoot,
    ContractPlanRootHash
);
typed_hash_function!(
    /// Hashes canonical command input in its immutable v1 domain.
    hash_command_input,
    CommandInput,
    CanonicalInputHash
);
typed_hash_function!(
    /// Hashes canonical event content in its immutable v1 domain.
    hash_event,
    Event,
    EventHash
);
typed_hash_function!(
    /// Hashes a complete canonical entity-record preimage in its immutable v1 domain.
    hash_entity_record,
    EntityRecord,
    EntityRecordHash
);
typed_hash_function!(
    /// Hashes one canonical committed entity transition in its immutable v1 domain.
    hash_entity_transition,
    EntityTransition,
    EntityTransitionHash
);
typed_hash_function!(
    /// Hashes canonical entity-key bytes in their immutable v1 domain.
    hash_entity_key,
    EntityKey,
    EntityKeyHash
);
typed_hash_function!(
    /// Hashes canonical conflict-key bytes in their immutable v1 domain.
    hash_conflict_key,
    ConflictKey,
    ConflictKeyHash
);
typed_hash_function!(
    /// Hashes canonical partition-key bytes in their immutable v1 domain.
    hash_partition_key,
    PartitionKey,
    PartitionKeyHash
);
typed_hash_function!(
    /// Hashes generated schema content in its immutable v1 domain.
    hash_schema,
    Schema,
    SchemaHash
);
typed_hash_function!(
    /// Hashes the canonical bytes of a complete checked projection apply request.
    ///
    /// This primitive performs domain separation only. The storage API owns the
    /// semantic request validation and canonical preimage construction.
    hash_projection_apply,
    ProjectionApply,
    ProjectionApplyHash
);
typed_hash_function!(
    /// Hashes one canonical offline-maintenance semantic input.
    hash_offline_maintenance_input,
    OfflineMaintenanceInput,
    OfflineMaintenanceInputHash
);
typed_hash_function!(
    /// Hashes one canonical contract-migration semantic input.
    hash_contract_migration_input,
    ContractMigrationInput,
    ContractMigrationInputHash
);
typed_hash_function!(
    /// Hashes one canonical contract-migration journal state.
    hash_contract_migration_journal,
    ContractMigrationJournal,
    ContractMigrationJournalHash
);
typed_hash_function!(
    /// Hashes one complete staged contract-migration validation report.
    hash_contract_migration_validation,
    ContractMigrationValidation,
    ContractMigrationValidationDigest
);

/// Computes a domain-separated v1 HMAC-SHA-256 lookup digest.
pub fn keyed_hash(
    domain: KeyedHashDomain,
    key_id: DigestKeyId,
    key: &DigestKey,
    payload: &[u8],
) -> KeyedDigest {
    keyed_hash_secret(domain, key_id, key.expose_secret(), payload)
}

/// Computes a domain-separated v1 HMAC-SHA-256 lookup digest from borrowed
/// secret key bytes.
pub fn keyed_hash_secret(
    domain: KeyedHashDomain,
    key_id: DigestKeyId,
    key_bytes: &[u8; 32],
    payload: &[u8],
) -> KeyedDigest {
    let mut mac = Hmac::<Sha256>::new_from_slice(key_bytes)
        .expect("HMAC-SHA-256 accepts keys of every length");
    write_frame(&mut mac, HMAC_PREFIX, domain.label(), payload);
    KeyedDigest::new(key_id, mac.finalize().into_bytes().into())
}

/// Computes the v1 capability-token lookup digest from exactly 32 decoded raw
/// token bytes.
#[must_use]
pub fn hash_capability_token(
    key_id: DigestKeyId,
    key: &DigestKey,
    raw_token: &[u8; 32],
) -> CapabilityTokenDigest {
    hash_capability_token_secret(key_id, key.expose_secret(), raw_token)
}

/// Computes the v1 capability-token lookup digest from borrowed secret key
/// bytes and exactly 32 decoded raw token bytes.
#[must_use]
pub fn hash_capability_token_secret(
    key_id: DigestKeyId,
    key_bytes: &[u8; 32],
    raw_token: &[u8; 32],
) -> CapabilityTokenDigest {
    let digest = keyed_hash_secret(
        KeyedHashDomain::CapabilityToken,
        key_id,
        key_bytes,
        raw_token,
    );
    CapabilityTokenDigest::from_hmac_bytes(key_id, *digest.as_bytes())
}

fn write_frame<T: sha2::digest::Update>(
    target: &mut T,
    prefix: &[u8],
    domain: &str,
    payload: &[u8],
) {
    write_frame_header(target, prefix, domain, payload.len() as u64);
    target.update(payload);
}

fn write_frame_header<T: sha2::digest::Update>(
    target: &mut T,
    prefix: &[u8],
    domain: &str,
    payload_length: u64,
) {
    let domain = domain.as_bytes();
    debug_assert!(u16::try_from(domain.len()).is_ok());
    let domain_length = domain.len() as u16;
    target.update(prefix);
    target.update(&[DIGEST_SCHEME_V1]);
    target.update(&domain_length.to_be_bytes());
    target.update(domain);
    target.update(&payload_length.to_be_bytes());
}

struct HexDigest<'a>(&'a [u8; 32]);

impl fmt::Debug for HexDigest<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            write!(formatter, "{byte:02x}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::*;

    #[test]
    // req: REP-002
    fn streaming_hash_preserves_v1_framing_across_chunk_boundaries() {
        let payload: Vec<u8> = (0..=255).cycle().take(1025).collect();
        for domain in HashDomain::ALL {
            for length in [0, 1, 55, 56, 63, 64, 65, 1025] {
                for chunk_size in [1, 7, 64, 129] {
                    let mut streamed = ContentHasher::new(domain, length as u64);
                    for chunk in payload[..length].chunks(chunk_size) {
                        streamed.update(chunk).expect("within declared length");
                    }
                    assert_eq!(
                        streamed.finish().expect("complete"),
                        hash(domain, &payload[..length])
                    );
                }
            }
        }
    }

    #[test]
    // req: REP-002
    fn streaming_hash_refuses_short_extra_and_poisoned_input() {
        let mut short = ContentHasher::new(HashDomain::Schema, 2);
        short.update(b"a").expect("prefix");
        assert_eq!(short.finish(), Err(HashLengthMismatch));
        let mut extra = ContentHasher::new(HashDomain::Schema, 1);
        assert_eq!(extra.update(b"secret"), Err(HashLengthMismatch));
        assert_eq!(extra.update(b"a"), Err(HashLengthMismatch));
        assert_eq!(extra.finish(), Err(HashLengthMismatch));
        let mut complete = ContentHasher::new(HashDomain::Schema, 1);
        complete.update(b"a").expect("complete");
        assert_eq!(complete.update(b"b"), Err(HashLengthMismatch));
        assert_eq!(complete.finish(), Err(HashLengthMismatch));
        assert_eq!(
            ContentHasher::new(HashDomain::Schema, u64::MAX).finish(),
            Err(HashLengthMismatch)
        );
    }

    #[test]
    fn domain_registry_has_no_duplicate_labels() {
        let mut labels = BTreeSet::new();
        for domain in HashDomain::ALL {
            assert!(labels.insert(domain.label()));
        }
        for domain in KeyedHashDomain::ALL {
            assert!(labels.insert(domain.label()));
        }
    }

    #[test]
    fn identical_payloads_are_separated_by_domain() {
        let values = HashDomain::ALL
            .map(|domain| hash(domain, b"same payload"))
            .into_iter()
            .collect::<BTreeSet<_>>();
        assert_eq!(values.len(), HashDomain::ALL.len());
    }

    #[test]
    fn content_digest_retains_its_domain() {
        for domain in HashDomain::ALL {
            assert_eq!(hash(domain, b"payload").domain(), domain);
        }
    }
}