Skip to main content

stateknot_core/
journal.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Integrity-bound, append-only journal envelopes for durable run facts.
5//!
6//! The journal is the ordered source of truth for recovery and event streaming.
7//! Core validates canonical payloads, idempotency identity, sequence continuity,
8//! checksums, and worker provenance. A production store remains responsible for
9//! serializing appends under a locked run head and, for worker writes, checking
10//! the exact current unexpired lease with the database clock in that same
11//! transaction.
12
13use std::{fmt, str::FromStr};
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
17use thiserror::Error;
18
19use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
20use crate::{
21    BoundedJson, BoundedJsonError, CanonicalJson, CanonicalJsonError, Digest, EventId, JsonLimits,
22    RunFence, RunId, RunLease, RunLeaseValidationError, SchemaReference, TenantId, Timestamp,
23};
24
25const MAX_DATABASE_ORDINAL: u64 = i64::MAX as u64;
26const POSITIVE_I64_PATTERN: &str = "^[1-9][0-9]{0,18}$";
27const EVENT_KIND_PATTERN: &str = "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$";
28const INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-journal-intent-v1\0";
29const EVENT_DIGEST_DOMAIN: &[u8] = b"stateknot-journal-event-v1\0";
30
31/// Positive, contiguous event position within one tenant-scoped run journal.
32///
33/// The first record is sequence one. The maximum matches `PostgreSQL` signed
34/// `BIGINT`, and the JSON wire form is a canonical decimal string.
35#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
36pub struct JournalSequence(u64);
37
38impl JournalSequence {
39    /// Sequence of the first event in a run journal.
40    pub const FIRST: Self = Self(1);
41
42    /// Largest sequence representable by the `PostgreSQL` v1 schema.
43    pub const MAX: Self = Self(MAX_DATABASE_ORDINAL);
44
45    /// Constructs a positive `PostgreSQL`-compatible sequence.
46    ///
47    /// # Errors
48    ///
49    /// Returns [`JournalSequenceError::Zero`] for zero and
50    /// [`JournalSequenceError::AboveMaximum`] above signed `BIGINT`.
51    pub const fn new(value: u64) -> Result<Self, JournalSequenceError> {
52        if value == 0 {
53            return Err(JournalSequenceError::Zero);
54        }
55        if value > MAX_DATABASE_ORDINAL {
56            return Err(JournalSequenceError::AboveMaximum);
57        }
58        Ok(Self(value))
59    }
60
61    /// Returns the integer sequence.
62    #[must_use]
63    pub const fn get(self) -> u64 {
64        self.0
65    }
66
67    /// Returns the exact contiguous successor or `None` at the storage limit.
68    #[must_use]
69    pub const fn checked_next(self) -> Option<Self> {
70        if self.0 == MAX_DATABASE_ORDINAL {
71            None
72        } else {
73            Some(Self(self.0 + 1))
74        }
75    }
76}
77
78impl fmt::Display for JournalSequence {
79    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
80        self.0.fmt(formatter)
81    }
82}
83
84impl FromStr for JournalSequence {
85    type Err = JournalSequenceError;
86
87    fn from_str(value: &str) -> Result<Self, Self::Err> {
88        let value = parse_bounded_u64(value, MAX_DATABASE_ORDINAL)
89            .map_err(JournalSequenceError::from_decimal_error)?;
90        Self::new(value)
91    }
92}
93
94impl Serialize for JournalSequence {
95    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
96    where
97        S: Serializer,
98    {
99        serializer.collect_str(self)
100    }
101}
102
103impl<'de> Deserialize<'de> for JournalSequence {
104    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
105    where
106        D: Deserializer<'de>,
107    {
108        deserializer.deserialize_str(JournalSequenceVisitor)
109    }
110}
111
112impl JsonSchema for JournalSequence {
113    fn schema_name() -> std::borrow::Cow<'static, str> {
114        "JournalSequence".into()
115    }
116
117    fn schema_id() -> std::borrow::Cow<'static, str> {
118        concat!(module_path!(), "::JournalSequence").into()
119    }
120
121    fn json_schema(_: &mut SchemaGenerator) -> Schema {
122        json_schema!({
123            "type": "string",
124            "minLength": 1,
125            "maxLength": 19,
126            "pattern": POSITIVE_I64_PATTERN
127        })
128    }
129
130    fn inline_schema() -> bool {
131        true
132    }
133}
134
135struct JournalSequenceVisitor;
136
137impl de::Visitor<'_> for JournalSequenceVisitor {
138    type Value = JournalSequence;
139
140    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
141        formatter.write_str("a canonical positive decimal PostgreSQL BIGINT journal sequence")
142    }
143
144    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
145    where
146        E: de::Error,
147    {
148        value.parse().map_err(E::custom)
149    }
150}
151
152/// Invalid canonical journal sequence.
153#[derive(Clone, Debug, Eq, Error, PartialEq)]
154#[non_exhaustive]
155pub enum JournalSequenceError {
156    /// Sequence zero is outside the one-based journal.
157    #[error("journal sequence must be positive")]
158    Zero,
159
160    /// The sequence exceeded `PostgreSQL` signed `BIGINT`.
161    #[error("journal sequence exceeds the PostgreSQL BIGINT maximum")]
162    AboveMaximum,
163
164    /// The wire value was empty or contained a non-decimal byte.
165    #[error("journal sequence must contain only unsigned ASCII decimal digits")]
166    InvalidFormat,
167
168    /// The wire value contained a leading zero.
169    #[error("journal sequence must use canonical decimal text")]
170    NonCanonical,
171}
172
173impl JournalSequenceError {
174    const fn from_decimal_error(error: UnsignedDecimalError) -> Self {
175        match error {
176            UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
177                Self::InvalidFormat
178            }
179            UnsignedDecimalError::LeadingZero => Self::NonCanonical,
180            UnsignedDecimalError::TooLong { .. } | UnsignedDecimalError::Overflow => {
181                Self::AboveMaximum
182            }
183        }
184    }
185}
186
187/// Stable lower-kebab-case semantic name of a durable event payload.
188#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
189pub struct JournalEventKind(Box<str>);
190
191impl JournalEventKind {
192    /// Maximum UTF-8 byte length of an event kind.
193    pub const MAX_LEN: usize = 96;
194
195    /// Validates and constructs an event kind.
196    ///
197    /// # Errors
198    ///
199    /// Returns [`JournalEventKindError`] unless the value is a non-empty,
200    /// bounded lower-kebab-case ASCII identifier beginning with a letter.
201    pub fn new(value: impl Into<String>) -> Result<Self, JournalEventKindError> {
202        let value = value.into();
203        validate_event_kind(&value)?;
204        Ok(Self(value.into_boxed_str()))
205    }
206
207    /// Returns the stable semantic name.
208    #[must_use]
209    pub fn as_str(&self) -> &str {
210        &self.0
211    }
212}
213
214impl AsRef<str> for JournalEventKind {
215    fn as_ref(&self) -> &str {
216        self.as_str()
217    }
218}
219
220impl fmt::Debug for JournalEventKind {
221    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
222        formatter
223            .debug_tuple("JournalEventKind")
224            .field(&self.as_str())
225            .finish()
226    }
227}
228
229impl fmt::Display for JournalEventKind {
230    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231        formatter.write_str(self.as_str())
232    }
233}
234
235impl FromStr for JournalEventKind {
236    type Err = JournalEventKindError;
237
238    fn from_str(value: &str) -> Result<Self, Self::Err> {
239        Self::new(value)
240    }
241}
242
243impl Serialize for JournalEventKind {
244    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
245    where
246        S: Serializer,
247    {
248        serializer.serialize_str(self.as_str())
249    }
250}
251
252impl<'de> Deserialize<'de> for JournalEventKind {
253    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
254    where
255        D: Deserializer<'de>,
256    {
257        deserializer.deserialize_str(JournalEventKindVisitor)
258    }
259}
260
261impl JsonSchema for JournalEventKind {
262    fn schema_name() -> std::borrow::Cow<'static, str> {
263        "JournalEventKind".into()
264    }
265
266    fn schema_id() -> std::borrow::Cow<'static, str> {
267        concat!(module_path!(), "::JournalEventKind").into()
268    }
269
270    fn json_schema(_: &mut SchemaGenerator) -> Schema {
271        json_schema!({
272            "type": "string",
273            "minLength": 1,
274            "maxLength": 96,
275            "pattern": EVENT_KIND_PATTERN
276        })
277    }
278
279    fn inline_schema() -> bool {
280        true
281    }
282}
283
284struct JournalEventKindVisitor;
285
286impl de::Visitor<'_> for JournalEventKindVisitor {
287    type Value = JournalEventKind;
288
289    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
290        formatter.write_str("a bounded lower-kebab-case journal event kind")
291    }
292
293    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
294    where
295        E: de::Error,
296    {
297        value.parse().map_err(E::custom)
298    }
299}
300
301fn validate_event_kind(value: &str) -> Result<(), JournalEventKindError> {
302    if value.is_empty() {
303        return Err(JournalEventKindError::Empty);
304    }
305    if value.len() > JournalEventKind::MAX_LEN {
306        return Err(JournalEventKindError::TooLong {
307            maximum: JournalEventKind::MAX_LEN,
308            actual: value.len(),
309        });
310    }
311    let bytes = value.as_bytes();
312    if !bytes[0].is_ascii_lowercase() {
313        return Err(JournalEventKindError::InvalidStart);
314    }
315    for (index, byte) in bytes.iter().copied().enumerate() {
316        if !byte.is_ascii_lowercase() && !byte.is_ascii_digit() && byte != b'-' {
317            return Err(JournalEventKindError::InvalidByte { index });
318        }
319        if byte == b'-' && (index + 1 == bytes.len() || (index > 0 && bytes[index - 1] == b'-')) {
320            return Err(JournalEventKindError::NonCanonicalSeparator { index });
321        }
322    }
323    Ok(())
324}
325
326/// Invalid durable event kind.
327#[derive(Clone, Debug, Eq, Error, PartialEq)]
328#[non_exhaustive]
329pub enum JournalEventKindError {
330    /// The event kind was empty.
331    #[error("journal event kind must not be empty")]
332    Empty,
333
334    /// The event kind exceeded its hard byte bound.
335    #[error("journal event kind is {actual} bytes; maximum is {maximum}")]
336    TooLong {
337        /// Maximum accepted byte length.
338        maximum: usize,
339        /// Observed byte length.
340        actual: usize,
341    },
342
343    /// The first byte was not a lowercase ASCII letter.
344    #[error("journal event kind must begin with a lowercase ASCII letter")]
345    InvalidStart,
346
347    /// A byte was outside lowercase ASCII letters, digits, and hyphen.
348    #[error("journal event kind contains an invalid byte at offset {index}")]
349    InvalidByte {
350        /// Zero-based byte offset.
351        index: usize,
352    },
353
354    /// A hyphen was repeated or trailing.
355    #[error("journal event kind contains a non-canonical hyphen at offset {index}")]
356    NonCanonicalSeparator {
357        /// Zero-based byte offset.
358        index: usize,
359    },
360}
361
362/// Schema-bound durable event payload whose checksum uses RFC 8785 bytes.
363///
364/// The stable payload envelope is exactly `{schema, kind, data}`. Construction
365/// validates the complete envelope under [`JsonLimits::MAXIMUM`] and caches its
366/// RFC 8785 SHA-256 checksum. Schema evaluation itself is performed by the
367/// trusted local registry before this value is admitted.
368#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
369#[serde(deny_unknown_fields)]
370pub struct JournalPayload {
371    schema: SchemaReference,
372    kind: JournalEventKind,
373    data: BoundedJson,
374    #[serde(skip)]
375    #[schemars(skip)]
376    digest: Digest,
377}
378
379impl JournalPayload {
380    /// Constructs an integrity-ready payload envelope.
381    ///
382    /// # Errors
383    ///
384    /// Returns [`JournalPayloadError`] if the complete envelope exceeds core
385    /// bounds, cannot be serialized, or contains a non-interoperable JSON
386    /// integer for RFC 8785 canonicalization.
387    pub fn new(
388        schema: SchemaReference,
389        kind: JournalEventKind,
390        data: BoundedJson,
391    ) -> Result<Self, JournalPayloadError> {
392        let canonical = canonical_payload(&schema, &kind, &data)?;
393        Ok(Self {
394            schema,
395            kind,
396            data,
397            digest: canonical.digest(),
398        })
399    }
400
401    /// Returns the pinned payload schema.
402    #[must_use]
403    pub const fn schema(&self) -> &SchemaReference {
404        &self.schema
405    }
406
407    /// Returns the semantic event kind.
408    #[must_use]
409    pub const fn kind(&self) -> &JournalEventKind {
410        &self.kind
411    }
412
413    /// Returns the bounded event data without permitting mutation.
414    #[must_use]
415    pub const fn data(&self) -> &BoundedJson {
416        &self.data
417    }
418
419    /// Returns SHA-256 over the exact RFC 8785 payload envelope bytes.
420    #[must_use]
421    pub const fn digest(&self) -> Digest {
422        self.digest
423    }
424
425    /// Reproduces the exact RFC 8785 payload envelope bytes for durable storage.
426    ///
427    /// # Errors
428    ///
429    /// Fails closed if canonicalization unexpectedly no longer reproduces the
430    /// already validated envelope.
431    pub fn canonical_json(&self) -> Result<CanonicalJson, JournalPayloadError> {
432        let canonical = canonical_payload(&self.schema, &self.kind, &self.data)?;
433        if canonical.digest() != self.digest {
434            return Err(JournalPayloadError::DigestChanged);
435        }
436        Ok(canonical)
437    }
438}
439
440impl fmt::Debug for JournalPayload {
441    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
442        formatter
443            .debug_struct("JournalPayload")
444            .field("schema", &self.schema)
445            .field("kind", &self.kind)
446            .field("data_stats", &self.data.stats())
447            .field("digest", &self.digest)
448            .finish_non_exhaustive()
449    }
450}
451
452impl<'de> Deserialize<'de> for JournalPayload {
453    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
454    where
455        D: Deserializer<'de>,
456    {
457        #[derive(Deserialize)]
458        #[serde(deny_unknown_fields)]
459        struct Wire {
460            schema: SchemaReference,
461            kind: JournalEventKind,
462            data: BoundedJson,
463        }
464
465        let wire = Wire::deserialize(deserializer)?;
466        Self::new(wire.schema, wire.kind, wire.data).map_err(de::Error::custom)
467    }
468}
469
470#[derive(Serialize)]
471struct PayloadEnvelope<'a> {
472    schema: &'a SchemaReference,
473    kind: &'a JournalEventKind,
474    data: &'a BoundedJson,
475}
476
477fn canonical_payload(
478    schema: &SchemaReference,
479    kind: &JournalEventKind,
480    data: &BoundedJson,
481) -> Result<CanonicalJson, JournalPayloadError> {
482    let value = serde_json::to_value(PayloadEnvelope { schema, kind, data })
483        .map_err(|_| JournalPayloadError::EnvelopeSerialization)?;
484    let bounded = BoundedJson::try_from_value_with_limits(value, JsonLimits::MAXIMUM)
485        .map_err(JournalPayloadError::envelope_bounds)?;
486    CanonicalJson::new(&bounded).map_err(JournalPayloadError::canonical)
487}
488
489/// Invalid canonical durable event payload.
490#[derive(Clone, Debug, Eq, Error, PartialEq)]
491#[non_exhaustive]
492pub enum JournalPayloadError {
493    /// Typed envelope serialization failed before canonicalization.
494    #[error("journal payload envelope serialization failed")]
495    EnvelopeSerialization,
496
497    /// The complete schema/kind/data envelope exceeded core JSON bounds.
498    #[error("journal payload envelope violates JSON bounds: {source}")]
499    EnvelopeBounds {
500        /// Underlying bounded JSON failure.
501        #[source]
502        source: BoundedJsonError,
503    },
504
505    /// RFC 8785 canonicalization failed closed.
506    #[error("journal payload canonicalization failed: {source}")]
507    Canonical {
508        /// Underlying canonical JSON failure.
509        #[source]
510        source: CanonicalJsonError,
511    },
512
513    /// Recomputed canonical bytes no longer matched the admitted checksum.
514    #[error("journal payload canonical digest changed after validation")]
515    DigestChanged,
516}
517
518impl JournalPayloadError {
519    const fn envelope_bounds(source: BoundedJsonError) -> Self {
520        Self::EnvelopeBounds { source }
521    }
522
523    const fn canonical(source: CanonicalJsonError) -> Self {
524        Self::Canonical { source }
525    }
526}
527
528/// Trusted runtime origin assigned to one journal append.
529///
530/// `ControlPlane` is available only to the trusted API/scheduler transaction
531/// path; it is not a privilege a remote or worker request can self-declare.
532/// Worker writes carry the exact token that the store must fence atomically.
533#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
534#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
535pub enum JournalEventSource {
536    /// Trusted API, scheduler, recovery, or migration control path.
537    ControlPlane,
538    /// Physical worker attempt holding a run lease.
539    Worker {
540        /// Exact run-scoped fencing token.
541        fence: RunFence,
542    },
543}
544
545impl JournalEventSource {
546    /// Constructs a trusted control-plane source marker.
547    #[must_use]
548    pub const fn control_plane() -> Self {
549        Self::ControlPlane
550    }
551
552    /// Constructs a worker source marker.
553    #[must_use]
554    pub const fn worker(fence: RunFence) -> Self {
555        Self::Worker { fence }
556    }
557
558    /// Returns the worker fence, if this event originates from an attempt.
559    #[must_use]
560    pub const fn worker_fence(&self) -> Option<&RunFence> {
561        match self {
562            Self::Worker { fence } => Some(fence),
563            Self::ControlPlane => None,
564        }
565    }
566}
567
568/// Stable idempotent request to append one semantic event.
569///
570/// Retrying the same `EventId` is successful only when every intent field and
571/// its digest match the existing event. Reusing an ID with different content is
572/// a conflict, never last-write-wins behavior.
573#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
574#[serde(deny_unknown_fields)]
575pub struct JournalEventIntent {
576    tenant_id: TenantId,
577    run_id: RunId,
578    event_id: EventId,
579    source: JournalEventSource,
580    payload: JournalPayload,
581    intent_digest: Digest,
582}
583
584impl JournalEventIntent {
585    /// Constructs a control-plane event intent.
586    ///
587    /// # Errors
588    ///
589    /// Returns [`JournalIntentError::Integrity`] if the small typed digest
590    /// preimage unexpectedly cannot be canonicalized.
591    pub fn control_plane(
592        tenant_id: TenantId,
593        run_id: RunId,
594        event_id: EventId,
595        payload: JournalPayload,
596    ) -> Result<Self, JournalIntentError> {
597        Self::from_parts(
598            tenant_id,
599            run_id,
600            event_id,
601            JournalEventSource::ControlPlane,
602            payload,
603        )
604    }
605
606    /// Constructs a worker event intent bound to its run-scoped fence.
607    ///
608    /// # Errors
609    ///
610    /// Returns [`JournalIntentError`] if the fence crosses the supplied tenant
611    /// or run, or the digest preimage cannot be canonicalized.
612    pub fn worker(
613        tenant_id: TenantId,
614        run_id: RunId,
615        event_id: EventId,
616        fence: RunFence,
617        payload: JournalPayload,
618    ) -> Result<Self, JournalIntentError> {
619        Self::from_parts(
620            tenant_id,
621            run_id,
622            event_id,
623            JournalEventSource::worker(fence),
624            payload,
625        )
626    }
627
628    /// Returns the tenant boundary.
629    #[must_use]
630    pub const fn tenant_id(&self) -> &TenantId {
631        &self.tenant_id
632    }
633
634    /// Returns the run journal identity.
635    #[must_use]
636    pub const fn run_id(&self) -> RunId {
637        self.run_id
638    }
639
640    /// Returns the stable idempotency identity.
641    #[must_use]
642    pub const fn event_id(&self) -> EventId {
643        self.event_id
644    }
645
646    /// Returns the trusted source marker.
647    #[must_use]
648    pub const fn source(&self) -> &JournalEventSource {
649        &self.source
650    }
651
652    /// Returns the schema-bound payload.
653    #[must_use]
654    pub const fn payload(&self) -> &JournalPayload {
655        &self.payload
656    }
657
658    /// Returns the domain-separated digest of the complete append intent.
659    #[must_use]
660    pub const fn intent_digest(&self) -> Digest {
661        self.intent_digest
662    }
663
664    fn from_parts(
665        tenant_id: TenantId,
666        run_id: RunId,
667        event_id: EventId,
668        source: JournalEventSource,
669        payload: JournalPayload,
670    ) -> Result<Self, JournalIntentError> {
671        validate_source_scope(&tenant_id, run_id, &source)?;
672        let intent_digest =
673            compute_intent_digest(&tenant_id, run_id, event_id, &source, payload.digest())
674                .map_err(JournalIntentError::integrity)?;
675        Ok(Self {
676            tenant_id,
677            run_id,
678            event_id,
679            source,
680            payload,
681            intent_digest,
682        })
683    }
684}
685
686impl fmt::Debug for JournalEventIntent {
687    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
688        formatter
689            .debug_struct("JournalEventIntent")
690            .field("tenant_id", &self.tenant_id)
691            .field("run_id", &self.run_id)
692            .field("event_id", &self.event_id)
693            .field("source", &self.source)
694            .field("payload", &self.payload)
695            .field("intent_digest", &self.intent_digest)
696            .finish_non_exhaustive()
697    }
698}
699
700impl<'de> Deserialize<'de> for JournalEventIntent {
701    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
702    where
703        D: Deserializer<'de>,
704    {
705        #[derive(Deserialize)]
706        #[serde(deny_unknown_fields)]
707        struct Wire {
708            tenant_id: TenantId,
709            run_id: RunId,
710            event_id: EventId,
711            source: JournalEventSource,
712            payload: JournalPayload,
713            intent_digest: Digest,
714        }
715
716        let wire = Wire::deserialize(deserializer)?;
717        let intent = Self::from_parts(
718            wire.tenant_id,
719            wire.run_id,
720            wire.event_id,
721            wire.source,
722            wire.payload,
723        )
724        .map_err(de::Error::custom)?;
725        if intent.intent_digest != wire.intent_digest {
726            return Err(de::Error::custom(JournalIntentError::IntentDigestMismatch));
727        }
728        Ok(intent)
729    }
730}
731
732fn validate_source_scope(
733    tenant_id: &TenantId,
734    run_id: RunId,
735    source: &JournalEventSource,
736) -> Result<(), JournalIntentError> {
737    if let JournalEventSource::Worker { fence } = source {
738        if fence.tenant_id() != tenant_id {
739            return Err(JournalIntentError::FenceTenantMismatch);
740        }
741        if fence.run_id() != run_id {
742            return Err(JournalIntentError::FenceRunMismatch);
743        }
744    }
745    Ok(())
746}
747
748#[derive(Serialize)]
749struct IntentDigestWire<'a> {
750    tenant_id: &'a TenantId,
751    run_id: RunId,
752    event_id: EventId,
753    source: &'a JournalEventSource,
754    payload_digest: Digest,
755}
756
757fn compute_intent_digest(
758    tenant_id: &TenantId,
759    run_id: RunId,
760    event_id: EventId,
761    source: &JournalEventSource,
762    payload_digest: Digest,
763) -> Result<Digest, JournalIntegrityError> {
764    domain_separated_digest(
765        INTENT_DIGEST_DOMAIN,
766        &IntentDigestWire {
767            tenant_id,
768            run_id,
769            event_id,
770            source,
771            payload_digest,
772        },
773    )
774}
775
776/// Invalid relationship or checksum in an event append intent.
777#[derive(Clone, Debug, Eq, Error, PartialEq)]
778#[non_exhaustive]
779pub enum JournalIntentError {
780    /// A worker fence named another tenant.
781    #[error("journal worker fence crosses the intent tenant boundary")]
782    FenceTenantMismatch,
783
784    /// A worker fence named another run.
785    #[error("journal worker fence does not belong to the intent run")]
786    FenceRunMismatch,
787
788    /// The typed intent digest preimage could not be canonicalized.
789    #[error("journal intent integrity calculation failed: {source}")]
790    Integrity {
791        /// Underlying integrity failure.
792        #[source]
793        source: JournalIntegrityError,
794    },
795
796    /// A serialized intent checksum did not match its fields.
797    #[error("journal intent digest does not match its fields")]
798    IntentDigestMismatch,
799}
800
801impl JournalIntentError {
802    const fn integrity(source: JournalIntegrityError) -> Self {
803        Self::Integrity { source }
804    }
805}
806
807/// Exact committed journal head used for optimistic append comparison.
808#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
809#[serde(deny_unknown_fields)]
810pub struct JournalHead {
811    tenant_id: TenantId,
812    run_id: RunId,
813    sequence: JournalSequence,
814    event_id: EventId,
815    recorded_at: Timestamp,
816    digest: Digest,
817}
818
819impl JournalHead {
820    /// Constructs a head recovered from trusted durable metadata.
821    #[must_use]
822    pub const fn new(
823        tenant_id: TenantId,
824        run_id: RunId,
825        sequence: JournalSequence,
826        event_id: EventId,
827        recorded_at: Timestamp,
828        digest: Digest,
829    ) -> Self {
830        Self {
831            tenant_id,
832            run_id,
833            sequence,
834            event_id,
835            recorded_at,
836            digest,
837        }
838    }
839
840    /// Returns the tenant boundary.
841    #[must_use]
842    pub const fn tenant_id(&self) -> &TenantId {
843        &self.tenant_id
844    }
845
846    /// Returns the run journal identity.
847    #[must_use]
848    pub const fn run_id(&self) -> RunId {
849        self.run_id
850    }
851
852    /// Returns the committed head sequence.
853    #[must_use]
854    pub const fn sequence(&self) -> JournalSequence {
855        self.sequence
856    }
857
858    /// Returns the committed head event identity.
859    #[must_use]
860    pub const fn event_id(&self) -> EventId {
861        self.event_id
862    }
863
864    /// Returns the head's durable clock observation.
865    #[must_use]
866    pub const fn recorded_at(&self) -> Timestamp {
867        self.recorded_at
868    }
869
870    /// Returns the head event checksum.
871    #[must_use]
872    pub const fn digest(&self) -> Digest {
873        self.digest
874    }
875}
876
877/// Optimistic journal precondition supplied with an append request.
878#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
879#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
880pub enum JournalExpectation {
881    /// The run journal must not contain any event.
882    Empty,
883    /// The current durable head must exactly match every supplied field.
884    Exact {
885        /// Previously observed committed head.
886        head: JournalHead,
887    },
888}
889
890impl JournalExpectation {
891    /// Constructs an empty-journal expectation.
892    #[must_use]
893    pub const fn empty() -> Self {
894        Self::Empty
895    }
896
897    /// Constructs an exact-head expectation.
898    #[must_use]
899    pub const fn exact(head: JournalHead) -> Self {
900        Self::Exact { head }
901    }
902
903    /// Returns the exact expected head, if any.
904    #[must_use]
905    pub const fn head(&self) -> Option<&JournalHead> {
906        match self {
907            Self::Empty => None,
908            Self::Exact { head } => Some(head),
909        }
910    }
911}
912
913/// Atomic append request combining an idempotent intent and exact head check.
914///
915/// Store implementations must first look up `(tenant, run, event_id)`. An
916/// identical existing intent is returned idempotently even if the caller's head
917/// is now stale; a conflicting reuse is rejected. Only a new event proceeds to
918/// exact-head and optional lease validation under the locked run row.
919#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
920#[serde(deny_unknown_fields)]
921pub struct JournalAppend {
922    expectation: JournalExpectation,
923    intent: JournalEventIntent,
924}
925
926impl JournalAppend {
927    /// Constructs an append request whose exact head belongs to the same scope.
928    ///
929    /// # Errors
930    ///
931    /// Returns [`JournalAppendError`] if an exact head crosses tenant or run
932    /// boundaries.
933    pub fn new(
934        expectation: JournalExpectation,
935        intent: JournalEventIntent,
936    ) -> Result<Self, JournalAppendError> {
937        if let Some(head) = expectation.head() {
938            if head.tenant_id != intent.tenant_id {
939                return Err(JournalAppendError::HeadTenantMismatch);
940            }
941            if head.run_id != intent.run_id {
942                return Err(JournalAppendError::HeadRunMismatch);
943            }
944        }
945        Ok(Self {
946            expectation,
947            intent,
948        })
949    }
950
951    /// Returns the optimistic head precondition.
952    #[must_use]
953    pub const fn expectation(&self) -> &JournalExpectation {
954        &self.expectation
955    }
956
957    /// Returns the idempotent event intent.
958    #[must_use]
959    pub const fn intent(&self) -> &JournalEventIntent {
960        &self.intent
961    }
962
963    /// Returns the worker fence that must be checked by the store, if any.
964    #[must_use]
965    pub const fn worker_fence(&self) -> Option<&RunFence> {
966        self.intent.source.worker_fence()
967    }
968
969    /// Performs a non-authoritative worker lease preflight.
970    ///
971    /// A production store must repeat this comparison using its current locked
972    /// run row and database clock in the commit transaction.
973    ///
974    /// # Errors
975    ///
976    /// Returns [`JournalAuthorityError::ControlPlaneSource`] for a control-plane
977    /// append or wraps an exact fence/expiry mismatch.
978    pub fn validate_worker_lease(
979        &self,
980        lease: &RunLease,
981        observed_at: Timestamp,
982    ) -> Result<(), JournalAuthorityError> {
983        let fence = self
984            .worker_fence()
985            .ok_or(JournalAuthorityError::ControlPlaneSource)?;
986        lease
987            .validate_write(fence, observed_at)
988            .map_err(JournalAuthorityError::lease)
989    }
990}
991
992impl fmt::Debug for JournalAppend {
993    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
994        formatter
995            .debug_struct("JournalAppend")
996            .field("expectation", &self.expectation)
997            .field("intent", &self.intent)
998            .finish_non_exhaustive()
999    }
1000}
1001
1002impl<'de> Deserialize<'de> for JournalAppend {
1003    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1004    where
1005        D: Deserializer<'de>,
1006    {
1007        #[derive(Deserialize)]
1008        #[serde(deny_unknown_fields)]
1009        struct Wire {
1010            expectation: JournalExpectation,
1011            intent: JournalEventIntent,
1012        }
1013
1014        let wire = Wire::deserialize(deserializer)?;
1015        Self::new(wire.expectation, wire.intent).map_err(de::Error::custom)
1016    }
1017}
1018
1019/// Invalid exact-head scope in an append request.
1020#[derive(Clone, Debug, Eq, Error, PartialEq)]
1021#[non_exhaustive]
1022pub enum JournalAppendError {
1023    /// The expected head crossed a tenant boundary.
1024    #[error("journal expected head crosses the append tenant boundary")]
1025    HeadTenantMismatch,
1026
1027    /// The expected head named a different run.
1028    #[error("journal expected head does not belong to the append run")]
1029    HeadRunMismatch,
1030}
1031
1032/// Rejected worker-authority preflight.
1033#[derive(Clone, Debug, Eq, Error, PartialEq)]
1034#[non_exhaustive]
1035pub enum JournalAuthorityError {
1036    /// The append belongs to a trusted non-worker path.
1037    #[error("control-plane journal append has no worker lease")]
1038    ControlPlaneSource,
1039
1040    /// The current lease rejected the worker token or observation.
1041    #[error("journal worker lease validation failed: {source}")]
1042    Lease {
1043        /// Exact lease validation failure.
1044        #[source]
1045        source: RunLeaseValidationError,
1046    },
1047}
1048
1049impl JournalAuthorityError {
1050    const fn lease(source: RunLeaseValidationError) -> Self {
1051        Self::Lease { source }
1052    }
1053}
1054
1055/// One committed, self-validating record in a run's append-only journal.
1056///
1057/// `digest` is a domain-separated SHA-256 checksum over stable event metadata,
1058/// the full intent checksum, payload checksum, and previous event checksum. It
1059/// detects accidental corruption, omission, and reordering; an unkeyed hash
1060/// chain is not proof against a privileged actor able to rewrite every record.
1061#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1062#[serde(deny_unknown_fields)]
1063pub struct JournalEvent {
1064    tenant_id: TenantId,
1065    run_id: RunId,
1066    sequence: JournalSequence,
1067    event_id: EventId,
1068    recorded_at: Timestamp,
1069    source: JournalEventSource,
1070    payload: JournalPayload,
1071    payload_digest: Digest,
1072    intent_digest: Digest,
1073    #[serde(skip_serializing_if = "Option::is_none")]
1074    previous_digest: Option<Digest>,
1075    digest: Digest,
1076}
1077
1078impl JournalEvent {
1079    /// Restores and verifies an event from durable storage columns.
1080    ///
1081    /// The intent reconstructs and validates tenant, run, event identity,
1082    /// source, payload, payload checksum, and intent checksum. This method then
1083    /// validates sequence/predecessor shape and recomputes the complete event
1084    /// checksum before returning a usable event.
1085    ///
1086    /// A store that persists redundant payload or intent digest columns must
1087    /// compare those columns with `intent` before calling this method.
1088    ///
1089    /// # Errors
1090    ///
1091    /// Returns [`JournalEventError`] when the sequence/predecessor shape or
1092    /// complete event checksum does not match the reconstructed event.
1093    pub fn restore(
1094        intent: JournalEventIntent,
1095        sequence: JournalSequence,
1096        recorded_at: Timestamp,
1097        previous_digest: Option<Digest>,
1098        digest: Digest,
1099    ) -> Result<Self, JournalEventError> {
1100        let payload_digest = intent.payload.digest();
1101        let intent_digest = intent.intent_digest;
1102        let event = Self {
1103            tenant_id: intent.tenant_id,
1104            run_id: intent.run_id,
1105            sequence,
1106            event_id: intent.event_id,
1107            recorded_at,
1108            source: intent.source,
1109            payload: intent.payload,
1110            payload_digest,
1111            intent_digest,
1112            previous_digest,
1113            digest,
1114        };
1115        event.validate()?;
1116        Ok(event)
1117    }
1118
1119    /// Materializes a validated append after the store has won its transaction.
1120    ///
1121    /// `recorded_at` must be the database observation selected while holding the
1122    /// current run row. For a non-empty journal it cannot precede the prior head;
1123    /// a store may clamp a regressing wall clock to the prior durable value while
1124    /// sequence remains the authoritative order.
1125    ///
1126    /// # Errors
1127    ///
1128    /// Returns [`JournalEventError`] for sequence exhaustion, clock regression,
1129    /// or an unexpected integrity serialization failure.
1130    pub fn commit(
1131        append: JournalAppend,
1132        recorded_at: Timestamp,
1133    ) -> Result<Self, JournalEventError> {
1134        let (sequence, previous_digest) = match append.expectation {
1135            JournalExpectation::Empty => (JournalSequence::FIRST, None),
1136            JournalExpectation::Exact { head } => {
1137                if recorded_at < head.recorded_at {
1138                    return Err(JournalEventError::ClockRegression {
1139                        previous: head.recorded_at,
1140                        actual: recorded_at,
1141                    });
1142                }
1143                let sequence = head
1144                    .sequence
1145                    .checked_next()
1146                    .ok_or(JournalEventError::SequenceOverflow)?;
1147                (sequence, Some(head.digest))
1148            }
1149        };
1150
1151        let intent = append.intent;
1152        let payload_digest = intent.payload.digest();
1153        let digest = compute_event_digest(&EventDigestWire {
1154            tenant_id: &intent.tenant_id,
1155            run_id: intent.run_id,
1156            sequence,
1157            event_id: intent.event_id,
1158            recorded_at,
1159            payload_digest,
1160            intent_digest: intent.intent_digest,
1161            previous_digest,
1162        })
1163        .map_err(JournalEventError::integrity)?;
1164        Ok(Self {
1165            tenant_id: intent.tenant_id,
1166            run_id: intent.run_id,
1167            sequence,
1168            event_id: intent.event_id,
1169            recorded_at,
1170            source: intent.source,
1171            payload: intent.payload,
1172            payload_digest,
1173            intent_digest: intent.intent_digest,
1174            previous_digest,
1175            digest,
1176        })
1177    }
1178
1179    /// Returns the tenant boundary.
1180    #[must_use]
1181    pub const fn tenant_id(&self) -> &TenantId {
1182        &self.tenant_id
1183    }
1184
1185    /// Returns the run journal identity.
1186    #[must_use]
1187    pub const fn run_id(&self) -> RunId {
1188        self.run_id
1189    }
1190
1191    /// Returns the one-based contiguous event sequence.
1192    #[must_use]
1193    pub const fn sequence(&self) -> JournalSequence {
1194        self.sequence
1195    }
1196
1197    /// Returns the stable idempotency identity.
1198    #[must_use]
1199    pub const fn event_id(&self) -> EventId {
1200        self.event_id
1201    }
1202
1203    /// Returns the durable database clock observation.
1204    #[must_use]
1205    pub const fn recorded_at(&self) -> Timestamp {
1206        self.recorded_at
1207    }
1208
1209    /// Returns the trusted source marker.
1210    #[must_use]
1211    pub const fn source(&self) -> &JournalEventSource {
1212        &self.source
1213    }
1214
1215    /// Returns the schema-bound payload.
1216    #[must_use]
1217    pub const fn payload(&self) -> &JournalPayload {
1218        &self.payload
1219    }
1220
1221    /// Returns the RFC 8785 payload checksum.
1222    #[must_use]
1223    pub const fn payload_digest(&self) -> Digest {
1224        self.payload_digest
1225    }
1226
1227    /// Returns the domain-separated append-intent checksum.
1228    #[must_use]
1229    pub const fn intent_digest(&self) -> Digest {
1230        self.intent_digest
1231    }
1232
1233    /// Returns the immediately preceding event checksum, if any.
1234    #[must_use]
1235    pub const fn previous_digest(&self) -> Option<Digest> {
1236        self.previous_digest
1237    }
1238
1239    /// Returns this complete event's domain-separated checksum.
1240    #[must_use]
1241    pub const fn digest(&self) -> Digest {
1242        self.digest
1243    }
1244
1245    /// Returns the exact durable head represented by this event.
1246    #[must_use]
1247    pub fn head(&self) -> JournalHead {
1248        JournalHead::new(
1249            self.tenant_id.clone(),
1250            self.run_id,
1251            self.sequence,
1252            self.event_id,
1253            self.recorded_at,
1254            self.digest,
1255        )
1256    }
1257
1258    /// Returns whether an idempotent retry is exactly the committed intent.
1259    #[must_use]
1260    pub fn matches_intent(&self, intent: &JournalEventIntent) -> bool {
1261        self.tenant_id == intent.tenant_id
1262            && self.run_id == intent.run_id
1263            && self.event_id == intent.event_id
1264            && self.source == intent.source
1265            && self.payload == intent.payload
1266            && self.intent_digest == intent.intent_digest
1267    }
1268
1269    fn validate(&self) -> Result<(), JournalEventError> {
1270        if self.sequence == JournalSequence::FIRST {
1271            if self.previous_digest.is_some() {
1272                return Err(JournalEventError::UnexpectedPreviousDigest);
1273            }
1274        } else if self.previous_digest.is_none() {
1275            return Err(JournalEventError::MissingPreviousDigest);
1276        }
1277
1278        if self.payload.digest() != self.payload_digest {
1279            return Err(JournalEventError::PayloadDigestMismatch);
1280        }
1281        validate_source_scope(&self.tenant_id, self.run_id, &self.source)
1282            .map_err(JournalEventError::intent)?;
1283        let expected_intent = compute_intent_digest(
1284            &self.tenant_id,
1285            self.run_id,
1286            self.event_id,
1287            &self.source,
1288            self.payload_digest,
1289        )
1290        .map_err(JournalEventError::integrity)?;
1291        if expected_intent != self.intent_digest {
1292            return Err(JournalEventError::IntentDigestMismatch);
1293        }
1294        let expected_event = compute_event_digest(&EventDigestWire {
1295            tenant_id: &self.tenant_id,
1296            run_id: self.run_id,
1297            sequence: self.sequence,
1298            event_id: self.event_id,
1299            recorded_at: self.recorded_at,
1300            payload_digest: self.payload_digest,
1301            intent_digest: self.intent_digest,
1302            previous_digest: self.previous_digest,
1303        })
1304        .map_err(JournalEventError::integrity)?;
1305        if expected_event != self.digest {
1306            return Err(JournalEventError::EventDigestMismatch);
1307        }
1308        Ok(())
1309    }
1310}
1311
1312impl fmt::Debug for JournalEvent {
1313    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1314        formatter
1315            .debug_struct("JournalEvent")
1316            .field("tenant_id", &self.tenant_id)
1317            .field("run_id", &self.run_id)
1318            .field("sequence", &self.sequence)
1319            .field("event_id", &self.event_id)
1320            .field("recorded_at", &self.recorded_at)
1321            .field("source", &self.source)
1322            .field("payload", &self.payload)
1323            .field("payload_digest", &self.payload_digest)
1324            .field("intent_digest", &self.intent_digest)
1325            .field("previous_digest", &self.previous_digest)
1326            .field("digest", &self.digest)
1327            .finish_non_exhaustive()
1328    }
1329}
1330
1331impl<'de> Deserialize<'de> for JournalEvent {
1332    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1333    where
1334        D: Deserializer<'de>,
1335    {
1336        #[derive(Deserialize)]
1337        #[serde(deny_unknown_fields)]
1338        struct Wire {
1339            tenant_id: TenantId,
1340            run_id: RunId,
1341            sequence: JournalSequence,
1342            event_id: EventId,
1343            recorded_at: Timestamp,
1344            source: JournalEventSource,
1345            payload: JournalPayload,
1346            payload_digest: Digest,
1347            intent_digest: Digest,
1348            previous_digest: Option<Digest>,
1349            digest: Digest,
1350        }
1351
1352        let wire = Wire::deserialize(deserializer)?;
1353        let event = Self {
1354            tenant_id: wire.tenant_id,
1355            run_id: wire.run_id,
1356            sequence: wire.sequence,
1357            event_id: wire.event_id,
1358            recorded_at: wire.recorded_at,
1359            source: wire.source,
1360            payload: wire.payload,
1361            payload_digest: wire.payload_digest,
1362            intent_digest: wire.intent_digest,
1363            previous_digest: wire.previous_digest,
1364            digest: wire.digest,
1365        };
1366        event.validate().map_err(de::Error::custom)?;
1367        Ok(event)
1368    }
1369}
1370
1371#[derive(Serialize)]
1372struct EventDigestWire<'a> {
1373    tenant_id: &'a TenantId,
1374    run_id: RunId,
1375    sequence: JournalSequence,
1376    event_id: EventId,
1377    recorded_at: Timestamp,
1378    payload_digest: Digest,
1379    intent_digest: Digest,
1380    previous_digest: Option<Digest>,
1381}
1382
1383fn compute_event_digest(wire: &EventDigestWire<'_>) -> Result<Digest, JournalIntegrityError> {
1384    domain_separated_digest(EVENT_DIGEST_DOMAIN, wire)
1385}
1386
1387/// Intrinsically invalid journal event or append materialization.
1388#[derive(Clone, Debug, Eq, Error, PartialEq)]
1389#[non_exhaustive]
1390pub enum JournalEventError {
1391    /// No contiguous `PostgreSQL` sequence remains.
1392    #[error("journal sequence overflowed")]
1393    SequenceOverflow,
1394
1395    /// The database clock observation preceded the committed head.
1396    #[error("journal event time {actual} precedes head time {previous}")]
1397    ClockRegression {
1398        /// Previous durable observation.
1399        previous: Timestamp,
1400        /// Rejected event observation.
1401        actual: Timestamp,
1402    },
1403
1404    /// The first sequence improperly named a predecessor.
1405    #[error("first journal event must not contain a previous digest")]
1406    UnexpectedPreviousDigest,
1407
1408    /// A non-first sequence omitted its predecessor checksum.
1409    #[error("non-first journal event must contain a previous digest")]
1410    MissingPreviousDigest,
1411
1412    /// The serialized payload checksum did not match canonical bytes.
1413    #[error("journal payload digest does not match the canonical payload")]
1414    PayloadDigestMismatch,
1415
1416    /// The serialized intent checksum did not match event identity and content.
1417    #[error("journal intent digest does not match the event fields")]
1418    IntentDigestMismatch,
1419
1420    /// The serialized event checksum did not match the record.
1421    #[error("journal event digest does not match the event fields")]
1422    EventDigestMismatch,
1423
1424    /// Worker source scope was invalid.
1425    #[error("journal event source is invalid: {source}")]
1426    Intent {
1427        /// Underlying source-scope failure.
1428        #[source]
1429        source: JournalIntentError,
1430    },
1431
1432    /// A small typed checksum preimage could not be canonicalized.
1433    #[error("journal event integrity calculation failed: {source}")]
1434    Integrity {
1435        /// Underlying integrity failure.
1436        #[source]
1437        source: JournalIntegrityError,
1438    },
1439}
1440
1441impl JournalEventError {
1442    const fn intent(source: JournalIntentError) -> Self {
1443        Self::Intent { source }
1444    }
1445
1446    const fn integrity(source: JournalIntegrityError) -> Self {
1447        Self::Integrity { source }
1448    }
1449}
1450
1451/// Streaming verifier for a complete journal or a suffix after a trusted head.
1452///
1453/// Each accepted event must be individually self-validating, in the same scope,
1454/// exactly one sequence after the current head, chained to its digest, and no
1455/// earlier in durable time. Rejection leaves the verifier unchanged.
1456#[derive(Debug, Default)]
1457pub struct JournalChainVerifier {
1458    head: Option<JournalHead>,
1459}
1460
1461impl JournalChainVerifier {
1462    /// Constructs a verifier expecting the first event.
1463    #[must_use]
1464    pub const fn new() -> Self {
1465        Self { head: None }
1466    }
1467
1468    /// Constructs a suffix verifier after a trusted checkpoint or archive head.
1469    #[must_use]
1470    pub const fn after(head: JournalHead) -> Self {
1471        Self { head: Some(head) }
1472    }
1473
1474    /// Returns the most recently accepted head.
1475    #[must_use]
1476    pub const fn head(&self) -> Option<&JournalHead> {
1477        self.head.as_ref()
1478    }
1479
1480    /// Verifies and accepts the next event without buffering payload history.
1481    ///
1482    /// # Errors
1483    ///
1484    /// Returns [`JournalChainError`] for intrinsic corruption, wrong scope,
1485    /// sequence gaps, predecessor mismatch, or durable-clock regression.
1486    pub fn verify_next(&mut self, event: &JournalEvent) -> Result<(), JournalChainError> {
1487        event.validate().map_err(JournalChainError::event)?;
1488        match &self.head {
1489            None => {
1490                if event.sequence != JournalSequence::FIRST {
1491                    return Err(JournalChainError::FirstSequence {
1492                        actual: event.sequence,
1493                    });
1494                }
1495            }
1496            Some(head) => {
1497                if event.tenant_id != head.tenant_id {
1498                    return Err(JournalChainError::TenantMismatch);
1499                }
1500                if event.run_id != head.run_id {
1501                    return Err(JournalChainError::RunMismatch);
1502                }
1503                let expected = head
1504                    .sequence
1505                    .checked_next()
1506                    .ok_or(JournalChainError::SequenceOverflow)?;
1507                if event.sequence != expected {
1508                    return Err(JournalChainError::SequenceGap {
1509                        expected,
1510                        actual: event.sequence,
1511                    });
1512                }
1513                if event.previous_digest != Some(head.digest) {
1514                    return Err(JournalChainError::PreviousDigestMismatch);
1515                }
1516                if event.recorded_at < head.recorded_at {
1517                    return Err(JournalChainError::ClockRegression {
1518                        previous: head.recorded_at,
1519                        actual: event.recorded_at,
1520                    });
1521                }
1522            }
1523        }
1524        self.head = Some(event.head());
1525        Ok(())
1526    }
1527}
1528
1529/// Rejected event in streaming journal-chain verification.
1530#[derive(Clone, Debug, Eq, Error, PartialEq)]
1531#[non_exhaustive]
1532pub enum JournalChainError {
1533    /// An event failed its own checksum or structural validation.
1534    #[error("journal event failed intrinsic validation: {source}")]
1535    Event {
1536        /// Underlying event failure.
1537        #[source]
1538        source: JournalEventError,
1539    },
1540
1541    /// A complete journal did not start at sequence one.
1542    #[error("journal begins at sequence {actual}; expected one")]
1543    FirstSequence {
1544        /// Rejected first sequence.
1545        actual: JournalSequence,
1546    },
1547
1548    /// The event crossed a tenant boundary.
1549    #[error("journal event crosses the verifier tenant boundary")]
1550    TenantMismatch,
1551
1552    /// The event named a different run.
1553    #[error("journal event does not belong to the verifier run")]
1554    RunMismatch,
1555
1556    /// The current verified head has no representable successor.
1557    #[error("journal verifier sequence overflowed")]
1558    SequenceOverflow,
1559
1560    /// The event was not the exact contiguous successor.
1561    #[error("journal sequence is {actual}; expected {expected}")]
1562    SequenceGap {
1563        /// Exact required successor.
1564        expected: JournalSequence,
1565        /// Rejected sequence.
1566        actual: JournalSequence,
1567    },
1568
1569    /// The event did not chain to the accepted head checksum.
1570    #[error("journal previous digest does not match the verifier head")]
1571    PreviousDigestMismatch,
1572
1573    /// Durable time regressed across the chain.
1574    #[error("journal event time {actual} precedes verified head time {previous}")]
1575    ClockRegression {
1576        /// Previous durable observation.
1577        previous: Timestamp,
1578        /// Rejected event observation.
1579        actual: Timestamp,
1580    },
1581}
1582
1583impl JournalChainError {
1584    const fn event(source: JournalEventError) -> Self {
1585        Self::Event { source }
1586    }
1587}
1588
1589/// Failure to produce a small domain-separated journal checksum.
1590#[derive(Clone, Debug, Eq, Error, PartialEq)]
1591#[non_exhaustive]
1592pub enum JournalIntegrityError {
1593    /// Canonical serialization of a closed typed checksum preimage failed.
1594    #[error("journal checksum preimage canonical serialization failed")]
1595    CanonicalSerialization,
1596}
1597
1598fn domain_separated_digest<T: Serialize>(
1599    domain: &[u8],
1600    value: &T,
1601) -> Result<Digest, JournalIntegrityError> {
1602    let canonical = serde_json_canonicalizer::to_vec(value)
1603        .map_err(|_| JournalIntegrityError::CanonicalSerialization)?;
1604    let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
1605    preimage.extend_from_slice(domain);
1606    preimage.extend_from_slice(&canonical);
1607    Ok(Digest::sha256(preimage))
1608}
1609
1610#[cfg(test)]
1611mod tests {
1612    use super::*;
1613    use crate::{AttemptId, FencingEpoch, SchemaId, Version};
1614    use proptest::prelude::*;
1615    use serde_json::{Value, from_value, json, to_value};
1616
1617    fn at(offset_micros: i64) -> Timestamp {
1618        let base = "2030-01-01T00:00:00.000000Z".parse::<Timestamp>().unwrap();
1619        Timestamp::from_unix_micros(base.unix_micros() + offset_micros).unwrap()
1620    }
1621
1622    fn tenant() -> TenantId {
1623        TenantId::try_from("tenant-a").unwrap()
1624    }
1625
1626    fn other_tenant() -> TenantId {
1627        TenantId::try_from("tenant-b").unwrap()
1628    }
1629
1630    fn run() -> RunId {
1631        "01912345-6789-7abc-8def-0123456789ab".parse().unwrap()
1632    }
1633
1634    fn other_run() -> RunId {
1635        "01912345-6789-7abc-8def-0123456789bb".parse().unwrap()
1636    }
1637
1638    fn event(suffix: &str) -> EventId {
1639        format!("01912345-6789-7abc-8def-0123456789{suffix}")
1640            .parse()
1641            .unwrap()
1642    }
1643
1644    fn attempt(suffix: &str) -> AttemptId {
1645        format!("01912345-6789-7abc-8def-0123456789{suffix}")
1646            .parse()
1647            .unwrap()
1648    }
1649
1650    fn schema() -> SchemaReference {
1651        SchemaReference::new(
1652            "https://stateknot.github.io/schema/run-event/1.0.0"
1653                .parse::<SchemaId>()
1654                .unwrap(),
1655            Version::new(1, 0, 0),
1656            Digest::sha256(b"run event schema v1"),
1657        )
1658    }
1659
1660    fn payload(value: Value) -> JournalPayload {
1661        JournalPayload::new(
1662            schema(),
1663            JournalEventKind::new("run-transition-applied").unwrap(),
1664            BoundedJson::try_from_value(value).unwrap(),
1665        )
1666        .unwrap()
1667    }
1668
1669    fn control_intent(event_id: EventId, value: Value) -> JournalEventIntent {
1670        JournalEventIntent::control_plane(tenant(), run(), event_id, payload(value)).unwrap()
1671    }
1672
1673    fn first_event() -> JournalEvent {
1674        JournalEvent::commit(
1675            JournalAppend::new(
1676                JournalExpectation::Empty,
1677                control_intent(event("a1"), json!({"revision": "0"})),
1678            )
1679            .unwrap(),
1680            at(10),
1681        )
1682        .unwrap()
1683    }
1684
1685    fn worker_fence() -> RunFence {
1686        RunFence::new(tenant(), run(), attempt("ac"), FencingEpoch::FIRST)
1687    }
1688
1689    #[test]
1690    fn sequences_are_positive_canonical_database_ordinals() {
1691        assert_eq!(JournalSequence::new(1), Ok(JournalSequence::FIRST));
1692        assert_eq!(JournalSequence::new(0), Err(JournalSequenceError::Zero));
1693        assert_eq!(
1694            JournalSequence::new(MAX_DATABASE_ORDINAL + 1),
1695            Err(JournalSequenceError::AboveMaximum)
1696        );
1697        assert_eq!(JournalSequence::MAX.checked_next(), None);
1698        assert_eq!(JournalSequence::FIRST.checked_next().unwrap().get(), 2);
1699        assert_eq!(to_value(JournalSequence::FIRST).unwrap(), json!("1"));
1700        for invalid in [json!("0"), json!("01"), json!("x"), json!(1), Value::Null] {
1701            assert!(from_value::<JournalSequence>(invalid).is_err());
1702        }
1703    }
1704
1705    #[test]
1706    fn event_kinds_enforce_lower_kebab_case_and_bounds() {
1707        for valid in ["run-admitted", "tool2-result", "a"] {
1708            assert_eq!(JournalEventKind::new(valid).unwrap().as_str(), valid);
1709        }
1710        assert_eq!(JournalEventKind::new(""), Err(JournalEventKindError::Empty));
1711        assert_eq!(
1712            JournalEventKind::new("9event"),
1713            Err(JournalEventKindError::InvalidStart)
1714        );
1715        assert!(matches!(
1716            JournalEventKind::new("Run-Admitted"),
1717            Err(JournalEventKindError::InvalidStart)
1718        ));
1719        assert!(matches!(
1720            JournalEventKind::new("run--admitted"),
1721            Err(JournalEventKindError::NonCanonicalSeparator { .. })
1722        ));
1723        assert!(matches!(
1724            JournalEventKind::new("run-admitted-"),
1725            Err(JournalEventKindError::NonCanonicalSeparator { .. })
1726        ));
1727        assert!(matches!(
1728            JournalEventKind::new("run_admitted"),
1729            Err(JournalEventKindError::InvalidByte { .. })
1730        ));
1731    }
1732
1733    #[test]
1734    fn payload_digest_is_rfc_8785_stable_and_redacted() {
1735        let first = payload(json!({"z": -0.0, "a": [1, true]}));
1736        let second = JournalPayload::new(
1737            schema(),
1738            JournalEventKind::new("run-transition-applied").unwrap(),
1739            BoundedJson::from_str(r#"{"a":[1,true],"z":0}"#).unwrap(),
1740        )
1741        .unwrap();
1742        assert_eq!(first.digest(), second.digest());
1743        assert_eq!(
1744            first.canonical_json().unwrap(),
1745            second.canonical_json().unwrap()
1746        );
1747        assert_eq!(first.canonical_json().unwrap().digest(), first.digest());
1748        let debug = format!("{:?}", payload(json!({"secret": "never-print-me"})));
1749        assert!(!debug.contains("never-print-me"));
1750    }
1751
1752    #[test]
1753    fn payload_rejects_non_interoperable_integers() {
1754        let result = JournalPayload::new(
1755            schema(),
1756            JournalEventKind::new("run-transition-applied").unwrap(),
1757            BoundedJson::from_str("9007199254740992").unwrap(),
1758        );
1759        assert!(matches!(
1760            result,
1761            Err(JournalPayloadError::Canonical {
1762                source: CanonicalJsonError::IntegerOutsideIJsonSafeRange
1763            })
1764        ));
1765    }
1766
1767    #[test]
1768    fn first_event_has_stable_idempotency_and_chain_identity() {
1769        let intent = control_intent(event("a1"), json!({"revision": "0"}));
1770        let append = JournalAppend::new(JournalExpectation::Empty, intent.clone()).unwrap();
1771        let committed = JournalEvent::commit(append, at(10)).unwrap();
1772        assert_eq!(committed.sequence(), JournalSequence::FIRST);
1773        assert_eq!(committed.previous_digest(), None);
1774        assert_eq!(committed.payload_digest(), committed.payload().digest());
1775        assert!(committed.matches_intent(&intent));
1776        assert_eq!(committed.head().digest(), committed.digest());
1777
1778        let round_trip = from_value::<JournalEvent>(to_value(&committed).unwrap()).unwrap();
1779        assert_eq!(round_trip, committed);
1780    }
1781
1782    #[test]
1783    fn storage_restore_recomputes_the_complete_event_integrity_layer() {
1784        let committed = first_event();
1785        let intent = control_intent(committed.event_id(), json!({"revision": "0"}));
1786        let restored = JournalEvent::restore(
1787            intent.clone(),
1788            committed.sequence(),
1789            committed.recorded_at(),
1790            committed.previous_digest(),
1791            committed.digest(),
1792        )
1793        .unwrap();
1794        assert_eq!(restored, committed);
1795        assert_eq!(
1796            JournalEvent::restore(
1797                intent,
1798                committed.sequence(),
1799                committed.recorded_at(),
1800                committed.previous_digest(),
1801                Digest::sha256(b"corrupt durable event"),
1802            ),
1803            Err(JournalEventError::EventDigestMismatch)
1804        );
1805    }
1806
1807    #[test]
1808    fn same_event_id_with_different_content_is_not_an_idempotent_match() {
1809        let committed = first_event();
1810        let same = control_intent(event("a1"), json!({"revision": "0"}));
1811        let conflict = control_intent(event("a1"), json!({"revision": "1"}));
1812        assert!(committed.matches_intent(&same));
1813        assert!(!committed.matches_intent(&conflict));
1814        assert_ne!(same.intent_digest(), conflict.intent_digest());
1815    }
1816
1817    #[test]
1818    fn worker_intent_binds_scope_and_current_lease() {
1819        let fence = worker_fence();
1820        let intent = JournalEventIntent::worker(
1821            tenant(),
1822            run(),
1823            event("a2"),
1824            fence.clone(),
1825            payload(json!({"revision": "1"})),
1826        )
1827        .unwrap();
1828        let append =
1829            JournalAppend::new(JournalExpectation::exact(first_event().head()), intent).unwrap();
1830        let lease = RunLease::new(fence, at(10), at(20)).unwrap();
1831        assert_eq!(append.validate_worker_lease(&lease, at(19)), Ok(()));
1832        assert!(matches!(
1833            append.validate_worker_lease(&lease, at(20)),
1834            Err(JournalAuthorityError::Lease {
1835                source: RunLeaseValidationError::Expired { .. }
1836            })
1837        ));
1838
1839        let wrong_tenant = JournalEventIntent::worker(
1840            other_tenant(),
1841            run(),
1842            event("a2"),
1843            worker_fence(),
1844            payload(json!({})),
1845        );
1846        assert_eq!(wrong_tenant, Err(JournalIntentError::FenceTenantMismatch));
1847    }
1848
1849    #[test]
1850    fn exact_head_must_share_the_intent_scope() {
1851        let first = first_event();
1852        let intent = JournalEventIntent::control_plane(
1853            other_tenant(),
1854            run(),
1855            event("a2"),
1856            payload(json!({})),
1857        )
1858        .unwrap();
1859        assert_eq!(
1860            JournalAppend::new(JournalExpectation::exact(first.head()), intent),
1861            Err(JournalAppendError::HeadTenantMismatch)
1862        );
1863
1864        let intent = JournalEventIntent::control_plane(
1865            tenant(),
1866            other_run(),
1867            event("a2"),
1868            payload(json!({})),
1869        )
1870        .unwrap();
1871        assert_eq!(
1872            JournalAppend::new(JournalExpectation::exact(first.head()), intent),
1873            Err(JournalAppendError::HeadRunMismatch)
1874        );
1875    }
1876
1877    #[test]
1878    fn contiguous_chain_verifies_without_buffering_payloads() {
1879        let first = first_event();
1880        let second = JournalEvent::commit(
1881            JournalAppend::new(
1882                JournalExpectation::exact(first.head()),
1883                control_intent(event("a2"), json!({"revision": "1"})),
1884            )
1885            .unwrap(),
1886            at(11),
1887        )
1888        .unwrap();
1889        assert_eq!(second.sequence().get(), 2);
1890        assert_eq!(second.previous_digest(), Some(first.digest()));
1891
1892        let mut verifier = JournalChainVerifier::new();
1893        verifier.verify_next(&first).unwrap();
1894        verifier.verify_next(&second).unwrap();
1895        assert_eq!(verifier.head(), Some(&second.head()));
1896    }
1897
1898    #[test]
1899    fn chain_verifier_rejects_gaps_wrong_scope_and_wrong_predecessor() {
1900        let first = first_event();
1901        let second = JournalEvent::commit(
1902            JournalAppend::new(
1903                JournalExpectation::exact(first.head()),
1904                control_intent(event("a2"), json!({})),
1905            )
1906            .unwrap(),
1907            at(11),
1908        )
1909        .unwrap();
1910        let third = JournalEvent::commit(
1911            JournalAppend::new(
1912                JournalExpectation::exact(second.head()),
1913                control_intent(event("a3"), json!({})),
1914            )
1915            .unwrap(),
1916            at(12),
1917        )
1918        .unwrap();
1919
1920        let mut gap = JournalChainVerifier::after(first.head());
1921        assert!(matches!(
1922            gap.verify_next(&third),
1923            Err(JournalChainError::SequenceGap { .. })
1924        ));
1925        assert_eq!(gap.head(), Some(&first.head()));
1926
1927        let foreign = JournalEvent::commit(
1928            JournalAppend::new(
1929                JournalExpectation::Empty,
1930                JournalEventIntent::control_plane(
1931                    other_tenant(),
1932                    run(),
1933                    event("b1"),
1934                    payload(json!({})),
1935                )
1936                .unwrap(),
1937            )
1938            .unwrap(),
1939            at(11),
1940        )
1941        .unwrap();
1942        let mut scoped = JournalChainVerifier::after(first.head());
1943        assert_eq!(
1944            scoped.verify_next(&foreign),
1945            Err(JournalChainError::TenantMismatch)
1946        );
1947
1948        let alternate_head = JournalHead::new(
1949            tenant(),
1950            run(),
1951            JournalSequence::FIRST,
1952            first.event_id(),
1953            first.recorded_at(),
1954            Digest::sha256(b"alternate-head"),
1955        );
1956        let wrong_predecessor = JournalEvent::commit(
1957            JournalAppend::new(
1958                JournalExpectation::exact(alternate_head),
1959                control_intent(event("b2"), json!({})),
1960            )
1961            .unwrap(),
1962            at(11),
1963        )
1964        .unwrap();
1965        let mut predecessor = JournalChainVerifier::after(first.head());
1966        assert_eq!(
1967            predecessor.verify_next(&wrong_predecessor),
1968            Err(JournalChainError::PreviousDigestMismatch)
1969        );
1970
1971        let earlier_head = JournalHead::new(
1972            tenant(),
1973            run(),
1974            JournalSequence::FIRST,
1975            first.event_id(),
1976            at(1),
1977            first.digest(),
1978        );
1979        let earlier = JournalEvent::commit(
1980            JournalAppend::new(
1981                JournalExpectation::exact(earlier_head),
1982                control_intent(event("b3"), json!({})),
1983            )
1984            .unwrap(),
1985            at(2),
1986        )
1987        .unwrap();
1988        let mut clock = JournalChainVerifier::after(first.head());
1989        assert!(matches!(
1990            clock.verify_next(&earlier),
1991            Err(JournalChainError::ClockRegression { .. })
1992        ));
1993    }
1994
1995    #[test]
1996    fn event_deserialization_detects_every_integrity_layer() {
1997        let encoded = to_value(first_event()).unwrap();
1998
1999        let mut payload_digest = encoded.clone();
2000        payload_digest["payload_digest"] = json!(Digest::sha256(b"wrong").to_string());
2001        assert!(from_value::<JournalEvent>(payload_digest).is_err());
2002
2003        let mut intent_digest = encoded.clone();
2004        intent_digest["intent_digest"] = json!(Digest::sha256(b"wrong").to_string());
2005        assert!(from_value::<JournalEvent>(intent_digest).is_err());
2006
2007        let mut event_digest = encoded.clone();
2008        event_digest["digest"] = json!(Digest::sha256(b"wrong").to_string());
2009        assert!(from_value::<JournalEvent>(event_digest).is_err());
2010
2011        let mut predecessor = encoded.clone();
2012        predecessor["previous_digest"] = json!(Digest::sha256(b"unexpected").to_string());
2013        assert!(from_value::<JournalEvent>(predecessor).is_err());
2014
2015        let mut extra = encoded;
2016        extra["payload"]["extra"] = json!(true);
2017        assert!(from_value::<JournalEvent>(extra).is_err());
2018    }
2019
2020    #[test]
2021    fn commit_rejects_clock_regression_and_sequence_exhaustion() {
2022        let first = first_event();
2023        let append = JournalAppend::new(
2024            JournalExpectation::exact(first.head()),
2025            control_intent(event("a2"), json!({})),
2026        )
2027        .unwrap();
2028        assert!(matches!(
2029            JournalEvent::commit(append, at(9)),
2030            Err(JournalEventError::ClockRegression { .. })
2031        ));
2032
2033        let exhausted = JournalHead::new(
2034            tenant(),
2035            run(),
2036            JournalSequence::MAX,
2037            event("af"),
2038            at(10),
2039            Digest::sha256(b"head"),
2040        );
2041        let append = JournalAppend::new(
2042            JournalExpectation::exact(exhausted),
2043            control_intent(event("b0"), json!({})),
2044        )
2045        .unwrap();
2046        assert_eq!(
2047            JournalEvent::commit(append, at(11)),
2048            Err(JournalEventError::SequenceOverflow)
2049        );
2050    }
2051
2052    #[test]
2053    fn schemas_close_all_integrity_bearing_objects() {
2054        for schema in [
2055            to_value(schemars::schema_for!(JournalPayload)).unwrap(),
2056            to_value(schemars::schema_for!(JournalEventIntent)).unwrap(),
2057            to_value(schemars::schema_for!(JournalAppend)).unwrap(),
2058            to_value(schemars::schema_for!(JournalEvent)).unwrap(),
2059        ] {
2060            assert_eq!(schema["type"], "object");
2061            assert_eq!(schema["additionalProperties"], false);
2062        }
2063    }
2064
2065    proptest! {
2066        #[test]
2067        fn generated_contiguous_chains_replay_to_their_last_head(length in 1_usize..128) {
2068            let mut verifier = JournalChainVerifier::new();
2069            let mut head = None;
2070            for index in 0..length {
2071                let event_id = EventId::generate();
2072                let intent = control_intent(event_id, json!({"index": index.to_string()}));
2073                let expectation = head
2074                    .clone()
2075                    .map_or(JournalExpectation::Empty, JournalExpectation::exact);
2076                let event = JournalEvent::commit(
2077                    JournalAppend::new(expectation, intent).unwrap(),
2078                    at(i64::try_from(index).unwrap()),
2079                ).unwrap();
2080                verifier.verify_next(&event).unwrap();
2081                head = Some(event.head());
2082            }
2083            prop_assert_eq!(verifier.head(), head.as_ref());
2084        }
2085    }
2086}