Skip to main content

stateknot_store_postgres/
model.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{fmt, time::Duration};
5
6use serde::{Deserialize, Serialize};
7use stateknot_core::{
8    AgentAdmission, ArtifactRef, Checkpoint, CheckpointHead, CheckpointId, CompiledGraph,
9    DeliveryFence, Digest, DurableTimer, DurableTimerRecord, DurableWait, FencingEpoch,
10    InterruptRecord, InterruptRequest, JournalEvent, JournalExpectation, JournalHead,
11    JournalPayload, ModelInvocation, NodeAttempt, OutboxAttempt, OutboxAttemptCompletion,
12    OutboxAttemptStart, OutboxDelivery, OutboxDestinationRef, PendingNodeResult,
13    PendingNodeResultHead, QuarantineId, RunFence, RunId, RunLease, RunLifecycle, RunRevision,
14    RunTransition, SchedulerReservationId, SchedulerShardId, Superstep, TenantId, Timestamp,
15    ToolInvocation,
16};
17
18use crate::StoreError;
19
20const SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN: &[u8] = b"stateknot.scheduler-fairness-policy.v1\0";
21
22/// Private storage coordinates for one immutable artifact object.
23///
24/// This value belongs only inside trusted storage providers. It must never be
25/// serialized into an [`ArtifactRef`], returned through an Agent protocol, or
26/// accepted as authorization. `Debug` deliberately omits every coordinate.
27#[derive(Clone, Eq, PartialEq)]
28pub struct ArtifactStorageLocator {
29    storage_namespace: Box<str>,
30    object_key: Box<str>,
31    object_version: Option<Box<str>>,
32    object_etag: Option<Box<str>>,
33}
34
35impl ArtifactStorageLocator {
36    /// Maximum byte length of a deployment-owned storage namespace.
37    pub const MAX_STORAGE_NAMESPACE_BYTES: usize = 128;
38    /// Maximum UTF-8 byte length of a provider object key.
39    pub const MAX_OBJECT_KEY_BYTES: usize = 1024;
40    /// Maximum byte length of an opaque provider object version.
41    pub const MAX_OBJECT_VERSION_BYTES: usize = 1024;
42    /// Maximum byte length of an opaque provider entity tag.
43    pub const MAX_OBJECT_ETAG_BYTES: usize = 1024;
44
45    /// Validates private, provider-neutral object coordinates.
46    ///
47    /// The namespace is a non-secret deployment identifier, not a bucket name
48    /// or endpoint. Object keys are relative and reject control characters,
49    /// backslashes, empty segments, and traversal-like segments so the same
50    /// locator remains safe across S3-compatible and in-memory backends.
51    ///
52    /// # Errors
53    ///
54    /// Returns [`StoreError::InvalidArtifactStorageLocator`] when any value is
55    /// empty, oversized, contains a forbidden byte, or is path-like.
56    pub fn new(
57        storage_namespace: impl Into<String>,
58        object_key: impl Into<String>,
59        object_version: Option<String>,
60        object_etag: Option<String>,
61    ) -> Result<Self, StoreError> {
62        let storage_namespace = storage_namespace.into();
63        let object_key = object_key.into();
64        validate_storage_namespace(&storage_namespace)?;
65        validate_object_key(&object_key)?;
66        let object_version =
67            validate_opaque_locator_value(object_version, Self::MAX_OBJECT_VERSION_BYTES)?;
68        let object_etag = validate_opaque_locator_value(object_etag, Self::MAX_OBJECT_ETAG_BYTES)?;
69        Ok(Self {
70            storage_namespace: storage_namespace.into_boxed_str(),
71            object_key: object_key.into_boxed_str(),
72            object_version,
73            object_etag,
74        })
75    }
76
77    /// Returns the deployment-owned storage namespace.
78    #[must_use]
79    pub fn storage_namespace(&self) -> &str {
80        &self.storage_namespace
81    }
82
83    /// Returns the private relative object key.
84    #[must_use]
85    pub fn object_key(&self) -> &str {
86        &self.object_key
87    }
88
89    /// Returns the optional immutable provider version identifier.
90    #[must_use]
91    pub fn object_version(&self) -> Option<&str> {
92        self.object_version.as_deref()
93    }
94
95    /// Returns the optional provider entity tag captured after upload.
96    #[must_use]
97    pub fn object_etag(&self) -> Option<&str> {
98        self.object_etag.as_deref()
99    }
100}
101
102impl fmt::Debug for ArtifactStorageLocator {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        formatter
105            .debug_struct("ArtifactStorageLocator")
106            .field("coordinates", &"<redacted>")
107            .field("has_object_version", &self.object_version.is_some())
108            .field("has_object_etag", &self.object_etag.is_some())
109            .finish_non_exhaustive()
110    }
111}
112
113/// Exact immutable input for one idempotent artifact registration.
114#[derive(Clone, Eq, PartialEq)]
115pub struct ArtifactRegistration {
116    registration_key: Digest,
117    artifact: ArtifactRef,
118    locator: ArtifactStorageLocator,
119}
120
121impl ArtifactRegistration {
122    /// Constructs an exact registry write intent.
123    #[must_use]
124    pub const fn new(
125        registration_key: Digest,
126        artifact: ArtifactRef,
127        locator: ArtifactStorageLocator,
128    ) -> Self {
129        Self {
130            registration_key,
131            artifact,
132            locator,
133        }
134    }
135
136    /// Returns the caller's domain-separated idempotency digest.
137    #[must_use]
138    pub const fn registration_key(&self) -> Digest {
139        self.registration_key
140    }
141
142    /// Returns the public immutable artifact metadata.
143    #[must_use]
144    pub const fn artifact(&self) -> &ArtifactRef {
145        &self.artifact
146    }
147
148    /// Returns private object coordinates for the trusted provider.
149    #[must_use]
150    pub const fn locator(&self) -> &ArtifactStorageLocator {
151        &self.locator
152    }
153}
154
155impl fmt::Debug for ArtifactRegistration {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter
158            .debug_struct("ArtifactRegistration")
159            .field("identity", self.artifact.identity())
160            .field("locator", &self.locator)
161            .finish_non_exhaustive()
162    }
163}
164
165/// Fully verified immutable artifact registry record.
166#[derive(Clone, Eq, PartialEq)]
167pub struct StoredArtifact {
168    pub(crate) registration: ArtifactRegistration,
169    pub(crate) registered_at: Timestamp,
170}
171
172impl StoredArtifact {
173    /// Constructs a verified registry result for a custom registry provider.
174    ///
175    /// Custom implementations are responsible for returning this value only
176    /// after enforcing the same immutable, tenant, lineage, and idempotency
177    /// guarantees as `PostgresStore`.
178    #[must_use]
179    pub const fn new(registration: ArtifactRegistration, registered_at: Timestamp) -> Self {
180        Self {
181            registration,
182            registered_at,
183        }
184    }
185
186    /// Returns the exact immutable registration.
187    #[must_use]
188    pub const fn registration(&self) -> &ArtifactRegistration {
189        &self.registration
190    }
191
192    /// Returns the public artifact reference.
193    #[must_use]
194    pub const fn artifact(&self) -> &ArtifactRef {
195        self.registration.artifact()
196    }
197
198    /// Returns private object coordinates for the trusted provider.
199    #[must_use]
200    pub const fn locator(&self) -> &ArtifactStorageLocator {
201        self.registration.locator()
202    }
203
204    /// Returns the database-clock registration observation.
205    #[must_use]
206    pub const fn registered_at(&self) -> Timestamp {
207        self.registered_at
208    }
209}
210
211impl fmt::Debug for StoredArtifact {
212    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
213        formatter
214            .debug_struct("StoredArtifact")
215            .field("identity", self.artifact().identity())
216            .field("registered_at", &self.registered_at)
217            .field("locator", self.locator())
218            .finish_non_exhaustive()
219    }
220}
221
222/// Result of idempotently registering one immutable artifact and its locator.
223#[derive(Clone, Debug, Eq, PartialEq)]
224#[non_exhaustive]
225pub enum ArtifactRegistrationOutcome {
226    /// A new registry record committed.
227    Registered(StoredArtifact),
228    /// The exact record was already committed by an earlier attempt.
229    Idempotent(StoredArtifact),
230}
231
232impl ArtifactRegistrationOutcome {
233    /// Returns the fully verified durable record.
234    #[must_use]
235    pub const fn stored(&self) -> &StoredArtifact {
236        match self {
237            Self::Registered(stored) | Self::Idempotent(stored) => stored,
238        }
239    }
240}
241
242fn validate_storage_namespace(value: &str) -> Result<(), StoreError> {
243    if value.is_empty()
244        || value.len() > ArtifactStorageLocator::MAX_STORAGE_NAMESPACE_BYTES
245        || value == "."
246        || value == ".."
247        || !value.as_bytes()[0].is_ascii_alphanumeric()
248        || value
249            .bytes()
250            .any(|byte| !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b':' | b'-'))
251    {
252        return Err(StoreError::InvalidArtifactStorageLocator);
253    }
254    Ok(())
255}
256
257fn validate_object_key(value: &str) -> Result<(), StoreError> {
258    if value.is_empty()
259        || value.len() > ArtifactStorageLocator::MAX_OBJECT_KEY_BYTES
260        || value.starts_with('/')
261        || value.ends_with('/')
262        || value.chars().any(|character| {
263            character == '\\'
264                || character.is_control()
265                || matches!(character, '\u{FDD0}'..='\u{FDEF}')
266                || (character as u32 & 0xFFFE) == 0xFFFE
267        })
268        || value
269            .split('/')
270            .any(|segment| segment.is_empty() || matches!(segment, "." | ".."))
271    {
272        return Err(StoreError::InvalidArtifactStorageLocator);
273    }
274    Ok(())
275}
276
277fn validate_opaque_locator_value(
278    value: Option<String>,
279    maximum_bytes: usize,
280) -> Result<Option<Box<str>>, StoreError> {
281    value
282        .map(|value| {
283            if value.is_empty()
284                || value.len() > maximum_bytes
285                || !value
286                    .bytes()
287                    .all(|byte| byte.is_ascii_graphic() || byte == b' ')
288            {
289                return Err(StoreError::InvalidArtifactStorageLocator);
290            }
291            Ok(value.into_boxed_str())
292        })
293        .transpose()
294}
295
296/// Immutable canonical policy bytes registered for one scheduler shard.
297///
298/// The store deliberately treats the policy body as opaque canonical bytes;
299/// `stateknot-runtime` owns the weighted-schedule schema and verifies it before
300/// registration and after loading. The domain-separated digest prevents policy
301/// bytes from being substituted with another digest-bearing record type.
302#[derive(Clone, Debug, Eq, PartialEq)]
303pub struct SchedulerFairnessPolicyRegistration {
304    shard_id: SchedulerShardId,
305    policy_digest: Digest,
306    policy_bytes: Box<[u8]>,
307    cycle_length: u16,
308}
309
310impl SchedulerFairnessPolicyRegistration {
311    /// Maximum canonical policy byte length accepted by the provider.
312    pub const MAX_POLICY_BYTES: usize = 262_144;
313    /// Maximum number of deterministic slots in one weighted cycle.
314    pub const MAX_CYCLE_LENGTH: u16 = 4096;
315
316    /// Constructs and checksums one immutable shard policy registration.
317    ///
318    /// # Errors
319    ///
320    /// Rejects empty/oversized policy bytes or a zero/excessive cycle length.
321    pub fn new(
322        shard_id: SchedulerShardId,
323        policy_bytes: impl Into<Vec<u8>>,
324        cycle_length: u16,
325    ) -> Result<Self, StoreError> {
326        let policy_bytes = policy_bytes.into();
327        if policy_bytes.is_empty()
328            || policy_bytes.len() > Self::MAX_POLICY_BYTES
329            || cycle_length == 0
330            || cycle_length > Self::MAX_CYCLE_LENGTH
331        {
332            return Err(StoreError::InvalidSchedulerFairnessPolicy);
333        }
334        let mut preimage =
335            Vec::with_capacity(SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN.len() + policy_bytes.len());
336        preimage.extend_from_slice(SCHEDULER_FAIRNESS_POLICY_DIGEST_DOMAIN);
337        preimage.extend_from_slice(&policy_bytes);
338        Ok(Self {
339            shard_id,
340            policy_digest: Digest::sha256(preimage),
341            policy_bytes: policy_bytes.into_boxed_slice(),
342            cycle_length,
343        })
344    }
345
346    /// Returns the immutable distributed-scheduler shard identity.
347    #[must_use]
348    pub const fn shard_id(&self) -> &SchedulerShardId {
349        &self.shard_id
350    }
351
352    /// Returns the domain-separated canonical policy checksum.
353    #[must_use]
354    pub const fn policy_digest(&self) -> Digest {
355        self.policy_digest
356    }
357
358    /// Returns the canonical runtime policy bytes.
359    #[must_use]
360    pub const fn policy_bytes(&self) -> &[u8] {
361        &self.policy_bytes
362    }
363
364    /// Returns the exact number of slots in one weighted cycle.
365    #[must_use]
366    pub const fn cycle_length(&self) -> u16 {
367        self.cycle_length
368    }
369}
370
371/// Fully verified durable scheduler fairness policy snapshot.
372#[derive(Clone, Debug, Eq, PartialEq)]
373pub struct StoredSchedulerFairnessPolicy {
374    pub(crate) registration: SchedulerFairnessPolicyRegistration,
375    pub(crate) registered_at: Timestamp,
376}
377
378impl StoredSchedulerFairnessPolicy {
379    /// Returns the immutable registration payload.
380    #[must_use]
381    pub const fn registration(&self) -> &SchedulerFairnessPolicyRegistration {
382        &self.registration
383    }
384
385    /// Returns the database clock at first registration.
386    #[must_use]
387    pub const fn registered_at(&self) -> Timestamp {
388        self.registered_at
389    }
390}
391
392/// Result of registering one immutable scheduler fairness shard.
393#[derive(Clone, Debug, Eq, PartialEq)]
394#[non_exhaustive]
395pub enum SchedulerFairnessPolicyRegistrationOutcome {
396    /// A new policy and global cursor committed.
397    Registered(StoredSchedulerFairnessPolicy),
398    /// The exact policy was already registered.
399    Idempotent(StoredSchedulerFairnessPolicy),
400}
401
402impl SchedulerFairnessPolicyRegistrationOutcome {
403    /// Returns the verified durable policy in either outcome.
404    #[must_use]
405    pub const fn policy(&self) -> &StoredSchedulerFairnessPolicy {
406        match self {
407            Self::Registered(policy) | Self::Idempotent(policy) => policy,
408        }
409    }
410}
411
412/// One globally ordered, lost-acknowledgement-safe fairness slot reservation.
413#[derive(Clone, Debug, Eq, PartialEq)]
414pub struct SchedulerFairnessReservation {
415    pub(crate) shard_id: SchedulerShardId,
416    pub(crate) reservation_id: SchedulerReservationId,
417    pub(crate) policy_digest: Digest,
418    pub(crate) sequence: u64,
419    pub(crate) slot: u16,
420    pub(crate) reserved_at: Timestamp,
421}
422
423impl SchedulerFairnessReservation {
424    /// Returns the immutable scheduler shard.
425    #[must_use]
426    pub const fn shard_id(&self) -> &SchedulerShardId {
427        &self.shard_id
428    }
429
430    /// Returns the stable idempotency identity supplied by the worker.
431    #[must_use]
432    pub const fn reservation_id(&self) -> SchedulerReservationId {
433        self.reservation_id
434    }
435
436    /// Returns the immutable policy snapshot used for selection.
437    #[must_use]
438    pub const fn policy_digest(&self) -> Digest {
439        self.policy_digest
440    }
441
442    /// Returns the zero-based global reservation sequence.
443    #[must_use]
444    pub const fn sequence(&self) -> u64 {
445        self.sequence
446    }
447
448    /// Returns the zero-based slot within the weighted policy cycle.
449    #[must_use]
450    pub const fn slot(&self) -> u16 {
451        self.slot
452    }
453
454    /// Returns the database time at first reservation.
455    #[must_use]
456    pub const fn reserved_at(&self) -> Timestamp {
457        self.reserved_at
458    }
459}
460
461/// Bounded maintenance policy for durable fairness reservation evidence.
462///
463/// A deployment must stop retrying a reservation identity before `retain_for`
464/// elapses. Deleting an identity and retrying it later would legitimately
465/// allocate a new slot, so the hard minimum provides an operational safety
466/// margin above the runtime's bounded immediate retry loop.
467#[derive(Clone, Copy, Debug, Eq, PartialEq)]
468pub struct SchedulerFairnessRetentionPolicy {
469    retain_for: Duration,
470    batch_size: u16,
471}
472
473impl SchedulerFairnessRetentionPolicy {
474    /// Smallest supported evidence retention window.
475    pub const MIN_RETAIN_FOR: Duration = Duration::from_secs(60 * 60);
476    /// Largest supported evidence retention window.
477    pub const MAX_RETAIN_FOR: Duration = Duration::from_secs(366 * 24 * 60 * 60);
478    /// Largest row count deleted by one short transaction.
479    pub const MAX_BATCH_SIZE: u16 = 10_000;
480
481    /// Constructs one bounded retention policy.
482    ///
483    /// # Errors
484    ///
485    /// Rejects retention outside the hard window or a zero/excessive batch.
486    pub const fn new(retain_for: Duration, batch_size: u16) -> Result<Self, StoreError> {
487        if retain_for.as_nanos() < Self::MIN_RETAIN_FOR.as_nanos()
488            || retain_for.as_nanos() > Self::MAX_RETAIN_FOR.as_nanos()
489            || batch_size == 0
490            || batch_size > Self::MAX_BATCH_SIZE
491        {
492            return Err(StoreError::InvalidSchedulerFairnessRetention);
493        }
494        Ok(Self {
495            retain_for,
496            batch_size,
497        })
498    }
499
500    /// Returns the minimum age of evidence eligible for deletion.
501    #[must_use]
502    pub const fn retain_for(self) -> Duration {
503        self.retain_for
504    }
505
506    /// Returns the maximum rows deleted by one transaction.
507    #[must_use]
508    pub const fn batch_size(self) -> u16 {
509        self.batch_size
510    }
511}
512
513/// Auditable result of one bounded fairness-reservation retention pass.
514#[derive(Clone, Copy, Debug, Eq, PartialEq)]
515pub struct SchedulerFairnessRetentionReport {
516    pub(crate) observed_at: Timestamp,
517    pub(crate) cutoff: Timestamp,
518    pub(crate) deleted: u16,
519}
520
521impl SchedulerFairnessRetentionReport {
522    /// Returns the authoritative database clock for this maintenance pass.
523    #[must_use]
524    pub const fn observed_at(self) -> Timestamp {
525        self.observed_at
526    }
527
528    /// Returns the exclusive oldest-retained cutoff.
529    #[must_use]
530    pub const fn cutoff(self) -> Timestamp {
531        self.cutoff
532    }
533
534    /// Returns the exact number of deleted reservations.
535    #[must_use]
536    pub const fn deleted(self) -> u16 {
537        self.deleted
538    }
539}
540
541/// Fully validated immutable graph definition in one tenant registry.
542#[derive(Clone, Debug, Eq, PartialEq)]
543pub struct StoredGraphDefinition {
544    pub(crate) tenant_id: TenantId,
545    pub(crate) graph: CompiledGraph,
546    pub(crate) registered_at: Timestamp,
547}
548
549impl StoredGraphDefinition {
550    /// Returns the tenant registry that owns this durable registration.
551    #[must_use]
552    pub const fn tenant_id(&self) -> &TenantId {
553        &self.tenant_id
554    }
555
556    /// Returns the fully recompiled and integrity-checked graph definition.
557    #[must_use]
558    pub const fn graph(&self) -> &CompiledGraph {
559        &self.graph
560    }
561
562    /// Returns the database-clock registration observation.
563    #[must_use]
564    pub const fn registered_at(&self) -> Timestamp {
565        self.registered_at
566    }
567}
568
569/// Result of idempotently registering one immutable compiled graph version.
570#[derive(Clone, Debug, Eq, PartialEq)]
571#[non_exhaustive]
572pub enum GraphDefinitionRegistrationOutcome {
573    /// A new owner-qualified graph version committed.
574    Registered(StoredGraphDefinition),
575    /// The exact canonical graph definition was already registered.
576    Idempotent(StoredGraphDefinition),
577}
578
579impl GraphDefinitionRegistrationOutcome {
580    /// Returns the fully validated durable graph definition.
581    #[must_use]
582    pub const fn definition(&self) -> &StoredGraphDefinition {
583        match self {
584            Self::Registered(definition) | Self::Idempotent(definition) => definition,
585        }
586    }
587}
588
589/// Closed reason taxonomy for stopping all execution of one durable run.
590///
591/// The caller stores only a stable component code and an integrity digest; raw
592/// payloads, credentials, SQL, and private error text are intentionally outside
593/// this record.
594#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
595#[serde(rename_all = "snake_case")]
596#[non_exhaustive]
597pub enum RunQuarantineCause {
598    /// Canonical bytes, digests, links, or immutable history failed validation.
599    IntegrityFailure,
600    /// A required durable schema or graph format is unsupported by this binary.
601    UnsupportedSchema,
602    /// Required integrity-bound external storage evidence is unavailable.
603    MissingArtifact,
604    /// A durable reference escaped its tenant boundary.
605    CrossTenantReference,
606    /// Authoritative history and a mutable projection disagree.
607    ProjectionMismatch,
608    /// No higher safe fencing epoch can be issued.
609    FencingEpochExhausted,
610    /// A trusted operator policy explicitly prohibited further execution.
611    OperatorPolicy,
612}
613
614impl RunQuarantineCause {
615    /// Returns the stable storage and metrics code.
616    #[must_use]
617    pub const fn as_str(self) -> &'static str {
618        match self {
619            Self::IntegrityFailure => "integrity_failure",
620            Self::UnsupportedSchema => "unsupported_schema",
621            Self::MissingArtifact => "missing_artifact",
622            Self::CrossTenantReference => "cross_tenant_reference",
623            Self::ProjectionMismatch => "projection_mismatch",
624            Self::FencingEpochExhausted => "fencing_epoch_exhausted",
625            Self::OperatorPolicy => "operator_policy",
626        }
627    }
628}
629
630/// Bounded non-secret machine code identifying the failed recovery component.
631#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
632pub struct RunQuarantineComponent(Box<str>);
633
634impl RunQuarantineComponent {
635    /// Maximum encoded component-code length.
636    pub const MAX_LEN: usize = 128;
637
638    /// Validates a lowercase ASCII component code.
639    ///
640    /// Codes use `a-z`, `0-9`, `.`, `_`, `:`, and `-`. They are suitable for
641    /// metrics and audit routing, not for user-controlled diagnostic text.
642    ///
643    /// # Errors
644    ///
645    /// Returns [`StoreError::InvalidRunQuarantineComponent`] when the code is
646    /// empty, oversized, or outside the documented grammar.
647    pub fn new(value: impl Into<String>) -> Result<Self, StoreError> {
648        let value = value.into();
649        if value.is_empty()
650            || value.len() > Self::MAX_LEN
651            || value.bytes().any(|byte| {
652                !byte.is_ascii_lowercase()
653                    && !byte.is_ascii_digit()
654                    && !matches!(byte, b'.' | b'_' | b':' | b'-')
655            })
656        {
657            return Err(StoreError::InvalidRunQuarantineComponent);
658        }
659        Ok(Self(value.into_boxed_str()))
660    }
661
662    /// Derives a stable `store.*` component from a payload-redacted corruption.
663    ///
664    /// # Errors
665    ///
666    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when `error` is not
667    /// [`StoreError::CorruptData`], or
668    /// [`StoreError::InvalidRunQuarantineComponent`] if a future record category
669    /// cannot fit the bounded component grammar.
670    pub fn from_corrupt_store_error(error: &StoreError) -> Result<Self, StoreError> {
671        let record = error
672            .corrupt_record()
673            .ok_or(StoreError::InvalidRunQuarantineRequest)?;
674        let mut component = String::with_capacity("store.".len() + record.len());
675        component.push_str("store.");
676        let mut previous_separator = false;
677        for byte in record.bytes() {
678            let normalized = if byte.is_ascii_alphanumeric() {
679                byte.to_ascii_lowercase()
680            } else if matches!(byte, b'.' | b':' | b'-') {
681                byte
682            } else {
683                b'_'
684            };
685            if normalized == b'_' {
686                if previous_separator {
687                    continue;
688                }
689                previous_separator = true;
690            } else {
691                previous_separator = false;
692            }
693            component.push(char::from(normalized));
694        }
695        while component.ends_with('_') {
696            component.pop();
697        }
698        Self::new(component)
699    }
700
701    /// Returns the stable component code.
702    #[must_use]
703    pub fn as_str(&self) -> &str {
704        &self.0
705    }
706}
707
708/// Immutable idempotency intent for quarantining one tenant-scoped run.
709#[derive(Clone, Debug, Eq, PartialEq)]
710pub struct RunQuarantineRequest {
711    pub(crate) tenant_id: TenantId,
712    pub(crate) run_id: RunId,
713    pub(crate) quarantine_id: QuarantineId,
714    pub(crate) expectation: JournalExpectation,
715    pub(crate) cause: RunQuarantineCause,
716    pub(crate) component: RunQuarantineComponent,
717    pub(crate) evidence_digest: Digest,
718    pub(crate) expected_fence: Option<RunFence>,
719}
720
721impl RunQuarantineRequest {
722    /// Constructs an exact, tenant-bound quarantine observation intent.
723    ///
724    /// `evidence_digest` identifies a caller-retained, redacted evidence bundle;
725    /// evidence bytes are deliberately not copied into the operational store.
726    ///
727    /// # Errors
728    ///
729    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when an exact journal
730    /// expectation belongs to another tenant or run.
731    pub fn new(
732        tenant_id: TenantId,
733        run_id: RunId,
734        quarantine_id: QuarantineId,
735        expectation: JournalExpectation,
736        cause: RunQuarantineCause,
737        component: RunQuarantineComponent,
738        evidence_digest: Digest,
739    ) -> Result<Self, StoreError> {
740        if expectation
741            .head()
742            .is_some_and(|head| head.tenant_id() != &tenant_id || head.run_id() != run_id)
743        {
744            return Err(StoreError::InvalidRunQuarantineRequest);
745        }
746        Ok(Self {
747            tenant_id,
748            run_id,
749            quarantine_id,
750            expectation,
751            cause,
752            component,
753            evidence_digest,
754            expected_fence: None,
755        })
756    }
757
758    /// Binds this observation to the exact live worker fence that detected it.
759    ///
760    /// A fenced quarantine commits only while that attempt and epoch still own
761    /// an unexpired lease. This prevents a superseded or expired recovery worker
762    /// from stopping a successor that happens to share the same journal head.
763    ///
764    /// # Errors
765    ///
766    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when the fence
767    /// crosses the request tenant or run.
768    pub fn with_expected_fence(mut self, fence: RunFence) -> Result<Self, StoreError> {
769        if fence.tenant_id() != &self.tenant_id || fence.run_id() != self.run_id {
770            return Err(StoreError::InvalidRunQuarantineRequest);
771        }
772        if self
773            .expected_fence
774            .as_ref()
775            .is_some_and(|expected| expected != &fence)
776        {
777            return Err(StoreError::InvalidRunQuarantineRequest);
778        }
779        self.expected_fence = Some(fence);
780        Ok(self)
781    }
782
783    /// Returns the tenant boundary.
784    #[must_use]
785    pub const fn tenant_id(&self) -> &TenantId {
786        &self.tenant_id
787    }
788
789    /// Returns the quarantined run identity.
790    #[must_use]
791    pub const fn run_id(&self) -> RunId {
792        self.run_id
793    }
794
795    /// Returns the stable lost-acknowledgement identity.
796    #[must_use]
797    pub const fn quarantine_id(&self) -> QuarantineId {
798        self.quarantine_id
799    }
800
801    /// Returns the exact journal observation that this evidence describes.
802    #[must_use]
803    pub const fn expectation(&self) -> &JournalExpectation {
804        &self.expectation
805    }
806
807    /// Returns the closed quarantine cause.
808    #[must_use]
809    pub const fn cause(&self) -> RunQuarantineCause {
810        self.cause
811    }
812
813    /// Returns the non-secret recovery component code.
814    #[must_use]
815    pub const fn component(&self) -> &RunQuarantineComponent {
816        &self.component
817    }
818
819    /// Returns the caller-retained evidence checksum.
820    #[must_use]
821    pub const fn evidence_digest(&self) -> Digest {
822        self.evidence_digest
823    }
824
825    /// Returns the exact recovery fence that must still own the run, if any.
826    #[must_use]
827    pub const fn expected_fence(&self) -> Option<&RunFence> {
828        self.expected_fence.as_ref()
829    }
830}
831
832/// Stable context for automatically quarantining one failed recovery read.
833///
834/// Clone and reuse the complete value after an ambiguous database outcome. The
835/// eventual corruption category is derived from [`StoreError::CorruptData`]
836/// rather than accepted from the caller.
837#[derive(Clone, Debug, Eq, PartialEq)]
838pub struct CorruptionQuarantineContext {
839    pub(crate) tenant_id: TenantId,
840    pub(crate) run_id: RunId,
841    pub(crate) quarantine_id: QuarantineId,
842    pub(crate) expectation: JournalExpectation,
843    pub(crate) evidence_digest: Digest,
844    pub(crate) expected_fence: Option<RunFence>,
845}
846
847impl CorruptionQuarantineContext {
848    /// Constructs a tenant-bound recovery observation.
849    ///
850    /// # Errors
851    ///
852    /// Returns [`StoreError::InvalidRunQuarantineRequest`] when an exact head
853    /// belongs to another tenant or run.
854    pub fn new(
855        tenant_id: TenantId,
856        run_id: RunId,
857        quarantine_id: QuarantineId,
858        expectation: JournalExpectation,
859        evidence_digest: Digest,
860    ) -> Result<Self, StoreError> {
861        if expectation
862            .head()
863            .is_some_and(|head| head.tenant_id() != &tenant_id || head.run_id() != run_id)
864        {
865            return Err(StoreError::InvalidRunQuarantineRequest);
866        }
867        Ok(Self {
868            tenant_id,
869            run_id,
870            quarantine_id,
871            expectation,
872            evidence_digest,
873            expected_fence: None,
874        })
875    }
876
877    /// Binds all corruption quarantines from this context to one live fence.
878    ///
879    /// # Errors
880    ///
881    /// Returns [`StoreError::InvalidClaimedRunRecoveryContext`] when the fence
882    /// crosses the context tenant or run.
883    pub fn with_expected_fence(mut self, fence: RunFence) -> Result<Self, StoreError> {
884        if fence.tenant_id() != &self.tenant_id || fence.run_id() != self.run_id {
885            return Err(StoreError::InvalidClaimedRunRecoveryContext);
886        }
887        if self
888            .expected_fence
889            .as_ref()
890            .is_some_and(|expected| expected != &fence)
891        {
892            return Err(StoreError::InvalidClaimedRunRecoveryContext);
893        }
894        self.expected_fence = Some(fence);
895        Ok(self)
896    }
897
898    /// Returns the tenant boundary.
899    #[must_use]
900    pub const fn tenant_id(&self) -> &TenantId {
901        &self.tenant_id
902    }
903
904    /// Returns the observed run identity.
905    #[must_use]
906    pub const fn run_id(&self) -> RunId {
907        self.run_id
908    }
909
910    /// Returns the stable quarantine identity.
911    #[must_use]
912    pub const fn quarantine_id(&self) -> QuarantineId {
913        self.quarantine_id
914    }
915
916    /// Returns the exact journal observation made by recovery.
917    #[must_use]
918    pub const fn expectation(&self) -> &JournalExpectation {
919        &self.expectation
920    }
921
922    /// Returns the caller-retained redacted evidence checksum.
923    #[must_use]
924    pub const fn evidence_digest(&self) -> Digest {
925        self.evidence_digest
926    }
927
928    /// Returns the exact live fence required for quarantine, when bound.
929    #[must_use]
930    pub const fn expected_fence(&self) -> Option<&RunFence> {
931        self.expected_fence.as_ref()
932    }
933
934    pub(crate) fn into_request(
935        self,
936        component: RunQuarantineComponent,
937    ) -> Result<RunQuarantineRequest, StoreError> {
938        let request = RunQuarantineRequest::new(
939            self.tenant_id,
940            self.run_id,
941            self.quarantine_id,
942            self.expectation,
943            RunQuarantineCause::IntegrityFailure,
944            component,
945            self.evidence_digest,
946        )?;
947        match self.expected_fence {
948            Some(fence) => request.with_expected_fence(fence),
949            None => Ok(request),
950        }
951    }
952}
953
954/// Fully verified immutable quarantine observation.
955#[derive(Clone, Debug, Eq, PartialEq)]
956pub struct RunQuarantine {
957    pub(crate) request: RunQuarantineRequest,
958    pub(crate) quarantined_at: Timestamp,
959    pub(crate) digest: Digest,
960}
961
962impl RunQuarantine {
963    /// Returns the immutable quarantine request.
964    #[must_use]
965    pub const fn request(&self) -> &RunQuarantineRequest {
966        &self.request
967    }
968
969    /// Returns the database-clock observation that removed the run from execution.
970    #[must_use]
971    pub const fn quarantined_at(&self) -> Timestamp {
972        self.quarantined_at
973    }
974
975    /// Returns the canonical observation checksum.
976    #[must_use]
977    pub const fn digest(&self) -> Digest {
978        self.digest
979    }
980}
981
982/// Result of atomically recording evidence and removing a run from execution.
983#[derive(Clone, Debug, Eq, PartialEq)]
984#[non_exhaustive]
985pub enum RunQuarantineCommitOutcome {
986    /// New immutable evidence and the run quarantine projection committed.
987    Committed(RunQuarantine),
988    /// The exact stable request had already committed.
989    Idempotent(RunQuarantine),
990}
991
992impl RunQuarantineCommitOutcome {
993    /// Returns the fully verified durable quarantine observation.
994    #[must_use]
995    pub const fn quarantine(&self) -> &RunQuarantine {
996        match self {
997            Self::Committed(quarantine) | Self::Idempotent(quarantine) => quarantine,
998        }
999    }
1000}
1001
1002/// Result of idempotent run admission.
1003#[derive(Clone, Debug)]
1004#[non_exhaustive]
1005pub enum AdmissionOutcome {
1006    /// A new pending run row committed.
1007    Committed(RunLifecycle),
1008    /// The same provenance was already admitted; the current snapshot is returned.
1009    Idempotent(RunLifecycle),
1010}
1011
1012impl AdmissionOutcome {
1013    /// Returns the validated lifecycle snapshot.
1014    #[must_use]
1015    pub const fn lifecycle(&self) -> &RunLifecycle {
1016        match self {
1017            Self::Committed(lifecycle) | Self::Idempotent(lifecycle) => lifecycle,
1018        }
1019    }
1020}
1021
1022/// Fully verified durable Agent admission and its current run projection.
1023///
1024/// `event` and `checkpoint` are always the immutable sequence-one and
1025/// superstep-zero anchors. `run` is the current snapshot and may therefore have
1026/// advanced beyond both anchors when this value is returned by a retry or load.
1027#[derive(Clone, Debug)]
1028pub struct StoredAgentAdmission {
1029    pub(crate) admission: AgentAdmission,
1030    pub(crate) run: StoredRun,
1031    pub(crate) event: JournalEvent,
1032    pub(crate) checkpoint: Checkpoint,
1033}
1034
1035impl StoredAgentAdmission {
1036    /// Returns the immutable database-clock admission snapshot.
1037    #[must_use]
1038    pub const fn admission(&self) -> &AgentAdmission {
1039        &self.admission
1040    }
1041
1042    /// Returns the current validated run row.
1043    #[must_use]
1044    pub const fn run(&self) -> &StoredRun {
1045        &self.run
1046    }
1047
1048    /// Returns the immutable first journal event.
1049    #[must_use]
1050    pub const fn event(&self) -> &JournalEvent {
1051        &self.event
1052    }
1053
1054    /// Returns the immutable superstep-zero checkpoint.
1055    #[must_use]
1056    pub const fn checkpoint(&self) -> &Checkpoint {
1057        &self.checkpoint
1058    }
1059}
1060
1061/// Result of atomically admitting and initializing one executable Agent run.
1062#[derive(Clone, Debug)]
1063#[non_exhaustive]
1064pub enum AgentAdmissionCommitOutcome {
1065    /// The admission, run, event, lifecycle start, and checkpoint committed.
1066    Committed(StoredAgentAdmission),
1067    /// The exact immutable request had already committed.
1068    Idempotent(StoredAgentAdmission),
1069}
1070
1071impl AgentAdmissionCommitOutcome {
1072    /// Returns the fully verified durable admission in either outcome.
1073    #[must_use]
1074    pub const fn stored(&self) -> &StoredAgentAdmission {
1075        match self {
1076            Self::Committed(stored) | Self::Idempotent(stored) => stored,
1077        }
1078    }
1079}
1080
1081/// Fully verified tenant-scoped ingress idempotency mapping and Agent admission.
1082#[derive(Clone, Debug)]
1083pub struct StoredAgentSubmission {
1084    pub(crate) key_digest: Digest,
1085    pub(crate) submission_digest: Digest,
1086    pub(crate) admission: StoredAgentAdmission,
1087    pub(crate) created_at: Timestamp,
1088}
1089
1090impl StoredAgentSubmission {
1091    /// Returns the tenant-scoped digest of the raw caller key.
1092    #[must_use]
1093    pub const fn key_digest(&self) -> Digest {
1094        self.key_digest
1095    }
1096
1097    /// Returns the digest of caller-controlled submission content.
1098    #[must_use]
1099    pub const fn submission_digest(&self) -> Digest {
1100        self.submission_digest
1101    }
1102
1103    /// Returns the exact durable Agent admission selected by this key.
1104    #[must_use]
1105    pub const fn admission(&self) -> &StoredAgentAdmission {
1106        &self.admission
1107    }
1108
1109    /// Returns the database observation shared with the atomic admission.
1110    #[must_use]
1111    pub const fn created_at(&self) -> Timestamp {
1112        self.created_at
1113    }
1114}
1115
1116/// Result of an ingress-keyed atomic Agent submission.
1117#[derive(Clone, Debug)]
1118#[non_exhaustive]
1119pub enum AgentSubmissionCommitOutcome {
1120    /// A new key mapping committed with a new or exact retained Agent admission.
1121    Committed(StoredAgentSubmission),
1122    /// The same key and caller content already selected one durable run.
1123    Idempotent(StoredAgentSubmission),
1124}
1125
1126impl AgentSubmissionCommitOutcome {
1127    /// Returns the fully verified mapping and admission in either outcome.
1128    #[must_use]
1129    pub const fn stored(&self) -> &StoredAgentSubmission {
1130        match self {
1131            Self::Committed(stored) | Self::Idempotent(stored) => stored,
1132        }
1133    }
1134}
1135
1136/// Result of an idempotent journal append.
1137#[derive(Clone, Debug)]
1138#[non_exhaustive]
1139pub enum AppendOutcome {
1140    /// A new event and projection committed atomically.
1141    Committed(JournalEvent),
1142    /// The identical event intent was already committed.
1143    Idempotent(JournalEvent),
1144}
1145
1146/// Result of atomically committing a journal event and initial graph
1147/// checkpoint.
1148#[derive(Clone, Debug)]
1149#[non_exhaustive]
1150pub enum CheckpointCommitOutcome {
1151    /// A new event, checkpoint, run head, and optional lifecycle projection committed.
1152    Committed {
1153        /// Newly committed journal event.
1154        event: JournalEvent,
1155        /// Newly committed immutable checkpoint.
1156        checkpoint: Checkpoint,
1157    },
1158    /// The exact event, projection, and checkpoint intent had already committed.
1159    Idempotent {
1160        /// Previously committed journal event.
1161        event: JournalEvent,
1162        /// Previously committed immutable checkpoint.
1163        checkpoint: Checkpoint,
1164    },
1165}
1166
1167impl CheckpointCommitOutcome {
1168    /// Returns the validated anchoring journal event.
1169    #[must_use]
1170    pub const fn event(&self) -> &JournalEvent {
1171        match self {
1172            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1173        }
1174    }
1175
1176    /// Returns the validated immutable checkpoint.
1177    #[must_use]
1178    pub const fn checkpoint(&self) -> &Checkpoint {
1179        match self {
1180            Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
1181        }
1182    }
1183}
1184
1185/// Result of atomically entering `waiting` with a checkpoint and complete
1186/// durable interrupt/timer registration set.
1187#[derive(Clone, Debug)]
1188#[non_exhaustive]
1189pub enum WaitCheckpointCommitOutcome {
1190    /// The event, checkpoint, lifecycle projection, and registrations committed.
1191    Committed {
1192        /// Newly committed anchoring journal event.
1193        event: JournalEvent,
1194        /// Newly committed immutable checkpoint.
1195        checkpoint: Checkpoint,
1196        /// Complete materialized registration batch in semantic order.
1197        waits: Vec<DurableWait>,
1198    },
1199    /// The exact complete transaction had already committed.
1200    Idempotent {
1201        /// Previously committed anchoring journal event.
1202        event: JournalEvent,
1203        /// Previously committed immutable checkpoint.
1204        checkpoint: Checkpoint,
1205        /// Complete verified registration batch in semantic order.
1206        waits: Vec<DurableWait>,
1207    },
1208}
1209
1210impl WaitCheckpointCommitOutcome {
1211    /// Returns the exact anchoring event.
1212    #[must_use]
1213    pub const fn event(&self) -> &JournalEvent {
1214        match self {
1215            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1216        }
1217    }
1218
1219    /// Returns the immutable checkpoint committed at the wait barrier.
1220    #[must_use]
1221    pub const fn checkpoint(&self) -> &Checkpoint {
1222        match self {
1223            Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
1224        }
1225    }
1226
1227    /// Returns every durable registration in lifecycle semantic order.
1228    #[must_use]
1229    pub fn waits(&self) -> &[DurableWait] {
1230        match self {
1231            Self::Committed { waits, .. } | Self::Idempotent { waits, .. } => waits,
1232        }
1233    }
1234}
1235
1236/// Result of atomically resolving one exact durable interrupt.
1237#[derive(Clone, Debug)]
1238#[non_exhaustive]
1239pub enum InterruptResolutionCommitOutcome {
1240    /// The event, resolution, lifecycle, and wait projection committed.
1241    Committed {
1242        /// Newly committed resolution event.
1243        event: JournalEvent,
1244        /// Complete immutable interrupt history.
1245        record: InterruptRecord,
1246    },
1247    /// The exact complete resolution transaction had already committed.
1248    Idempotent {
1249        /// Previously committed resolution event.
1250        event: JournalEvent,
1251        /// Complete verified interrupt history.
1252        record: InterruptRecord,
1253    },
1254}
1255
1256impl InterruptResolutionCommitOutcome {
1257    /// Returns the exact resolution event.
1258    #[must_use]
1259    pub const fn event(&self) -> &JournalEvent {
1260        match self {
1261            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1262        }
1263    }
1264
1265    /// Returns the complete interrupt history.
1266    #[must_use]
1267    pub const fn record(&self) -> &InterruptRecord {
1268        match self {
1269            Self::Committed { record, .. } | Self::Idempotent { record, .. } => record,
1270        }
1271    }
1272}
1273
1274/// Result of atomically firing one exact due durable timer.
1275#[derive(Clone, Debug)]
1276#[non_exhaustive]
1277pub enum TimerFiringCommitOutcome {
1278    /// The event, firing, lifecycle, and wait projection committed.
1279    Committed {
1280        /// Newly committed firing event.
1281        event: JournalEvent,
1282        /// Complete immutable timer history.
1283        record: DurableTimerRecord,
1284    },
1285    /// The exact complete firing transaction had already committed.
1286    Idempotent {
1287        /// Previously committed firing event.
1288        event: JournalEvent,
1289        /// Complete verified timer history.
1290        record: DurableTimerRecord,
1291    },
1292}
1293
1294impl TimerFiringCommitOutcome {
1295    /// Returns the exact firing event.
1296    #[must_use]
1297    pub const fn event(&self) -> &JournalEvent {
1298        match self {
1299            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1300        }
1301    }
1302
1303    /// Returns the complete timer history.
1304    #[must_use]
1305    pub const fn record(&self) -> &DurableTimerRecord {
1306        match self {
1307            Self::Committed { record, .. } | Self::Idempotent { record, .. } => record,
1308        }
1309    }
1310}
1311
1312/// Durable reason an outstanding wait was abandoned without resolution/firing.
1313#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize)]
1314#[serde(rename_all = "snake_case")]
1315#[non_exhaustive]
1316pub enum WaitAbandonmentReason {
1317    /// The run entered cooperative cancellation.
1318    RunCancellation,
1319    /// The run committed a terminal non-cancellation failure.
1320    RunFailure,
1321}
1322
1323/// One integrity-bound audit fact for a wait abandoned by a run-level edge.
1324#[derive(Clone, Debug, Eq, PartialEq)]
1325pub struct WaitAbandonment {
1326    pub(crate) wait: DurableWait,
1327    pub(crate) reason: WaitAbandonmentReason,
1328    pub(crate) journal: JournalHead,
1329    pub(crate) digest: Digest,
1330}
1331
1332impl WaitAbandonment {
1333    /// Returns the immutable registration that was abandoned.
1334    #[must_use]
1335    pub const fn wait(&self) -> &DurableWait {
1336        &self.wait
1337    }
1338
1339    /// Returns the run-level reason for abandonment.
1340    #[must_use]
1341    pub const fn reason(&self) -> WaitAbandonmentReason {
1342        self.reason
1343    }
1344
1345    /// Returns the exact journal event that abandoned the wait.
1346    #[must_use]
1347    pub const fn journal(&self) -> &JournalHead {
1348        &self.journal
1349    }
1350
1351    /// Returns the provider-domain integrity checksum.
1352    #[must_use]
1353    pub const fn digest(&self) -> Digest {
1354        self.digest
1355    }
1356}
1357
1358/// Result of atomically cancelling/failing a waiting run and abandoning its
1359/// complete outstanding wait set.
1360#[derive(Clone, Debug)]
1361#[non_exhaustive]
1362pub enum WaitAbandonmentCommitOutcome {
1363    /// The event, lifecycle edge, and every abandonment fact committed.
1364    Committed {
1365        /// Newly committed run-level event.
1366        event: JournalEvent,
1367        /// Complete abandoned set in deterministic registration identity order.
1368        abandonments: Vec<WaitAbandonment>,
1369    },
1370    /// The exact complete abandonment transaction had already committed.
1371    Idempotent {
1372        /// Previously committed run-level event.
1373        event: JournalEvent,
1374        /// Complete verified abandoned set.
1375        abandonments: Vec<WaitAbandonment>,
1376    },
1377}
1378
1379impl WaitAbandonmentCommitOutcome {
1380    /// Returns the exact run-level event.
1381    #[must_use]
1382    pub const fn event(&self) -> &JournalEvent {
1383        match self {
1384            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1385        }
1386    }
1387
1388    /// Returns every abandonment fact.
1389    #[must_use]
1390    pub fn abandonments(&self) -> &[WaitAbandonment] {
1391        match self {
1392            Self::Committed { abandonments, .. } | Self::Idempotent { abandonments, .. } => {
1393                abandonments
1394            }
1395        }
1396    }
1397}
1398
1399/// Result of atomically consuming one complete result barrier and committing
1400/// its anchoring event and successor checkpoint.
1401#[derive(Clone, Debug)]
1402#[non_exhaustive]
1403pub enum BarrierCommitOutcome {
1404    /// The event, successor checkpoint, and every result-consumption record
1405    /// committed in one transaction.
1406    Committed {
1407        /// Newly committed anchoring journal event.
1408        event: JournalEvent,
1409        /// Newly committed immutable successor checkpoint.
1410        checkpoint: Checkpoint,
1411    },
1412    /// The exact barrier transaction had already committed.
1413    Idempotent {
1414        /// Previously committed anchoring journal event.
1415        event: JournalEvent,
1416        /// Previously committed immutable successor checkpoint.
1417        checkpoint: Checkpoint,
1418    },
1419}
1420
1421impl BarrierCommitOutcome {
1422    /// Returns the validated anchoring journal event.
1423    #[must_use]
1424    pub const fn event(&self) -> &JournalEvent {
1425        match self {
1426            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1427        }
1428    }
1429
1430    /// Returns the validated immutable successor checkpoint.
1431    #[must_use]
1432    pub const fn checkpoint(&self) -> &Checkpoint {
1433        match self {
1434            Self::Committed { checkpoint, .. } | Self::Idempotent { checkpoint, .. } => checkpoint,
1435        }
1436    }
1437}
1438
1439/// Result of atomically committing a journal event and tool invocation revision.
1440#[derive(Clone, Debug)]
1441#[non_exhaustive]
1442pub enum ToolInvocationCommitOutcome {
1443    /// A new event and immutable invocation revision committed atomically.
1444    Committed {
1445        /// Newly committed journal event.
1446        event: JournalEvent,
1447        /// Newly committed invocation revision.
1448        invocation: ToolInvocation,
1449    },
1450    /// The exact event and invocation mutation had already committed.
1451    Idempotent {
1452        /// Previously committed journal event.
1453        event: JournalEvent,
1454        /// Previously committed invocation revision.
1455        invocation: ToolInvocation,
1456    },
1457}
1458
1459impl ToolInvocationCommitOutcome {
1460    /// Returns the validated anchoring journal event.
1461    #[must_use]
1462    pub const fn event(&self) -> &JournalEvent {
1463        match self {
1464            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1465        }
1466    }
1467
1468    /// Returns the validated immutable invocation revision.
1469    #[must_use]
1470    pub const fn invocation(&self) -> &ToolInvocation {
1471        match self {
1472            Self::Committed { invocation, .. } | Self::Idempotent { invocation, .. } => invocation,
1473        }
1474    }
1475}
1476
1477/// Result of atomically committing a journal event and model invocation revision.
1478#[derive(Clone, Debug)]
1479#[non_exhaustive]
1480pub enum ModelInvocationCommitOutcome {
1481    /// A new event and immutable invocation revision committed atomically.
1482    Committed {
1483        /// Newly committed journal event.
1484        event: JournalEvent,
1485        /// Newly committed invocation revision.
1486        invocation: ModelInvocation,
1487    },
1488    /// The exact event and invocation mutation had already committed.
1489    Idempotent {
1490        /// Previously committed journal event.
1491        event: JournalEvent,
1492        /// Previously committed invocation revision.
1493        invocation: ModelInvocation,
1494    },
1495}
1496
1497impl ModelInvocationCommitOutcome {
1498    /// Returns the validated anchoring journal event.
1499    #[must_use]
1500    pub const fn event(&self) -> &JournalEvent {
1501        match self {
1502            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1503        }
1504    }
1505
1506    /// Returns the validated immutable invocation revision.
1507    #[must_use]
1508    pub const fn invocation(&self) -> &ModelInvocation {
1509        match self {
1510            Self::Committed { invocation, .. } | Self::Idempotent { invocation, .. } => invocation,
1511        }
1512    }
1513}
1514
1515/// Legacy outcome shape for the pre-v6 direct pending-result API.
1516///
1517/// New writes return [`NodeAttemptCommitOutcome`] because every result must be
1518/// owned by a durable physical node attempt. This type remains public so the
1519/// fail-closed compatibility method can preserve its original signature.
1520#[derive(Clone, Debug)]
1521#[non_exhaustive]
1522pub enum PendingNodeResultCommitOutcome {
1523    /// A new event and immutable pending result committed atomically.
1524    Committed {
1525        /// Newly committed journal event.
1526        event: JournalEvent,
1527        /// Newly committed pending node result.
1528        result: PendingNodeResult,
1529    },
1530    /// The same semantic node result had already committed.
1531    Idempotent {
1532        /// Original journal event that anchored the stored winner.
1533        event: JournalEvent,
1534        /// Previously committed pending node result.
1535        result: PendingNodeResult,
1536    },
1537}
1538
1539impl PendingNodeResultCommitOutcome {
1540    /// Returns the validated anchoring journal event.
1541    #[must_use]
1542    pub const fn event(&self) -> &JournalEvent {
1543        match self {
1544            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1545        }
1546    }
1547
1548    /// Returns the validated immutable pending result.
1549    #[must_use]
1550    pub const fn result(&self) -> &PendingNodeResult {
1551        match self {
1552            Self::Committed { result, .. } | Self::Idempotent { result, .. } => result,
1553        }
1554    }
1555}
1556
1557/// Result of atomically committing a node-attempt start or completion event.
1558#[derive(Clone, Debug)]
1559#[non_exhaustive]
1560pub enum NodeAttemptCommitOutcome {
1561    /// A new event and immutable node-attempt record committed atomically.
1562    Committed {
1563        /// Newly committed anchoring journal event.
1564        event: JournalEvent,
1565        /// Fully restored attempt after this mutation.
1566        attempt: NodeAttempt,
1567    },
1568    /// The exact start or completion had already committed.
1569    Idempotent {
1570        /// Original journal event that anchored the stored mutation.
1571        event: JournalEvent,
1572        /// Fully restored durable attempt.
1573        attempt: NodeAttempt,
1574    },
1575}
1576
1577impl NodeAttemptCommitOutcome {
1578    /// Returns the validated anchoring journal event.
1579    #[must_use]
1580    pub const fn event(&self) -> &JournalEvent {
1581        match self {
1582            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1583        }
1584    }
1585
1586    /// Returns the fully restored physical attempt.
1587    #[must_use]
1588    pub const fn attempt(&self) -> &NodeAttempt {
1589        match self {
1590            Self::Committed { attempt, .. } | Self::Idempotent { attempt, .. } => attempt,
1591        }
1592    }
1593}
1594
1595/// Fully validated immutable destination snapshot used by dispatch adapters.
1596#[derive(Clone, Debug, Eq, PartialEq)]
1597pub struct StoredOutboxDestination {
1598    pub(crate) destination: OutboxDestinationRef,
1599    pub(crate) config: JournalPayload,
1600    pub(crate) created_at: Timestamp,
1601}
1602
1603impl StoredOutboxDestination {
1604    /// Returns the immutable destination identity and snapshot checksum.
1605    #[must_use]
1606    pub const fn destination(&self) -> &OutboxDestinationRef {
1607        &self.destination
1608    }
1609
1610    /// Returns the canonical schema-pinned non-secret routing configuration.
1611    #[must_use]
1612    pub const fn config(&self) -> &JournalPayload {
1613        &self.config
1614    }
1615
1616    /// Returns the database registration observation.
1617    #[must_use]
1618    pub const fn created_at(&self) -> Timestamp {
1619        self.created_at
1620    }
1621}
1622
1623/// Result of idempotently registering one immutable destination snapshot.
1624#[derive(Clone, Debug, Eq, PartialEq)]
1625#[non_exhaustive]
1626pub enum OutboxDestinationRegistrationOutcome {
1627    /// A new immutable destination snapshot committed.
1628    Registered(StoredOutboxDestination),
1629    /// The exact snapshot was already registered.
1630    Idempotent(StoredOutboxDestination),
1631}
1632
1633impl OutboxDestinationRegistrationOutcome {
1634    /// Returns the validated immutable destination snapshot.
1635    #[must_use]
1636    pub const fn destination(&self) -> &StoredOutboxDestination {
1637        match self {
1638            Self::Registered(destination) | Self::Idempotent(destination) => destination,
1639        }
1640    }
1641}
1642
1643/// Result of atomically appending one journal fact and its exact outbox set.
1644#[derive(Clone, Debug)]
1645#[non_exhaustive]
1646pub enum OutboxEnqueueOutcome {
1647    /// The event and every requested delivery committed in one transaction.
1648    Committed {
1649        /// Newly committed journal event.
1650        event: JournalEvent,
1651        /// Immutable deliveries in caller order.
1652        deliveries: Vec<OutboxDelivery>,
1653    },
1654    /// The exact event and complete delivery set had already committed.
1655    Idempotent {
1656        /// Previously committed journal event.
1657        event: JournalEvent,
1658        /// Fully validated durable deliveries in caller order.
1659        deliveries: Vec<OutboxDelivery>,
1660    },
1661}
1662
1663impl OutboxEnqueueOutcome {
1664    /// Returns the atomically anchoring journal event.
1665    #[must_use]
1666    pub const fn event(&self) -> &JournalEvent {
1667        match self {
1668            Self::Committed { event, .. } | Self::Idempotent { event, .. } => event,
1669        }
1670    }
1671
1672    /// Returns the complete immutable delivery set.
1673    #[must_use]
1674    pub fn deliveries(&self) -> &[OutboxDelivery] {
1675        match self {
1676            Self::Committed { deliveries, .. } | Self::Idempotent { deliveries, .. } => deliveries,
1677        }
1678    }
1679}
1680
1681/// One atomically claimed delivery and its durable-before-dispatch start.
1682#[derive(Clone, Debug)]
1683pub struct OutboxClaim {
1684    pub(crate) destination: StoredOutboxDestination,
1685    pub(crate) delivery: OutboxDelivery,
1686    pub(crate) start: OutboxAttemptStart,
1687}
1688
1689impl OutboxClaim {
1690    /// Returns the pinned destination snapshot needed by the adapter.
1691    #[must_use]
1692    pub const fn destination(&self) -> &StoredOutboxDestination {
1693        &self.destination
1694    }
1695
1696    /// Returns the immutable delivery and protocol payload.
1697    #[must_use]
1698    pub const fn delivery(&self) -> &OutboxDelivery {
1699        &self.delivery
1700    }
1701
1702    /// Returns the durable attempt start that must precede network I/O.
1703    #[must_use]
1704    pub const fn start(&self) -> &OutboxAttemptStart {
1705        &self.start
1706    }
1707
1708    /// Returns the exact completion fence.
1709    #[must_use]
1710    pub const fn fence(&self) -> &DeliveryFence {
1711        self.start.fence()
1712    }
1713}
1714
1715/// Result of an atomic tenant queue claim with a stable physical attempt ID.
1716#[derive(Clone, Debug)]
1717#[non_exhaustive]
1718pub enum OutboxClaimOutcome {
1719    /// New ownership committed before dispatch may begin.
1720    Claimed(OutboxClaim),
1721    /// The same attempt ID had already claimed this exact delivery.
1722    Idempotent(OutboxClaim),
1723    /// No eligible unlocked delivery was visible at the database observation.
1724    NoWork,
1725}
1726
1727impl OutboxClaimOutcome {
1728    /// Returns the claimed work, if any.
1729    #[must_use]
1730    pub const fn claim(&self) -> Option<&OutboxClaim> {
1731        match self {
1732            Self::Claimed(claim) | Self::Idempotent(claim) => Some(claim),
1733            Self::NoWork => None,
1734        }
1735    }
1736}
1737
1738/// Result of idempotently committing one delivery-attempt completion.
1739#[derive(Clone, Debug)]
1740#[non_exhaustive]
1741pub enum OutboxCompletionOutcome {
1742    /// A new immutable completion and projection update committed.
1743    Committed {
1744        /// Fully restored terminal physical attempt.
1745        attempt: OutboxAttempt,
1746    },
1747    /// The exact semantic completion had already committed.
1748    Idempotent {
1749        /// Fully restored terminal physical attempt.
1750        attempt: OutboxAttempt,
1751    },
1752}
1753
1754impl OutboxCompletionOutcome {
1755    /// Returns the fully restored completed attempt.
1756    #[must_use]
1757    pub const fn attempt(&self) -> &OutboxAttempt {
1758        match self {
1759            Self::Committed { attempt } | Self::Idempotent { attempt } => attempt,
1760        }
1761    }
1762
1763    /// Returns the immutable completion.
1764    #[must_use]
1765    pub const fn completion(&self) -> Option<&OutboxAttemptCompletion> {
1766        self.attempt().completion()
1767    }
1768}
1769
1770/// Hard-bounded number of outbox attempts returned in one history page.
1771#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1772pub struct OutboxAttemptHistoryPageSize(u8);
1773
1774impl OutboxAttemptHistoryPageSize {
1775    /// Largest decoded page accepted by the provider.
1776    pub const MAX: u8 = 16;
1777
1778    /// Constructs a positive bounded page size.
1779    ///
1780    /// # Errors
1781    ///
1782    /// Returns [`StoreError::InvalidOutboxAttemptPageSize`] outside `1..=16`.
1783    pub const fn new(value: u8) -> Result<Self, StoreError> {
1784        if value == 0 || value > Self::MAX {
1785            return Err(StoreError::InvalidOutboxAttemptPageSize);
1786        }
1787        Ok(Self(value))
1788    }
1789
1790    /// Returns the page size as an integer.
1791    #[must_use]
1792    pub const fn get(self) -> u8 {
1793        self.0
1794    }
1795}
1796
1797/// One bounded, fully verified ascending outbox-attempt history page.
1798#[derive(Clone, Debug)]
1799pub struct OutboxAttemptHistoryPage {
1800    pub(crate) records: Vec<OutboxAttempt>,
1801    pub(crate) has_more: bool,
1802}
1803
1804impl OutboxAttemptHistoryPage {
1805    /// Returns immutable attempts in ascending fencing-epoch order.
1806    #[must_use]
1807    pub fn records(&self) -> &[OutboxAttempt] {
1808        &self.records
1809    }
1810
1811    /// Returns whether a later attempt remains.
1812    #[must_use]
1813    pub const fn has_more(&self) -> bool {
1814        self.has_more
1815    }
1816
1817    /// Returns the exact next-page cursor.
1818    #[must_use]
1819    pub fn next_cursor(&self) -> Option<OutboxAttempt> {
1820        self.records.last().cloned()
1821    }
1822}
1823
1824/// Hard-bounded number of physical node attempts in one history page.
1825#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1826pub struct NodeAttemptHistoryPageSize(u8);
1827
1828impl NodeAttemptHistoryPageSize {
1829    /// Largest page accepted by the provider.
1830    ///
1831    /// A start and completion can occupy about 17 MiB together, so two
1832    /// records cap provider-owned decoded page memory near 34 MiB before
1833    /// driver overhead.
1834    pub const MAX: u8 = 2;
1835
1836    /// Constructs a positive bounded history page size.
1837    ///
1838    /// # Errors
1839    ///
1840    /// Returns [`StoreError::InvalidNodeAttemptPageSize`] for zero or values
1841    /// above two.
1842    pub const fn new(value: u8) -> Result<Self, StoreError> {
1843        if value == 0 || value > Self::MAX {
1844            return Err(StoreError::InvalidNodeAttemptPageSize);
1845        }
1846        Ok(Self(value))
1847    }
1848
1849    /// Returns the page size as an integer.
1850    #[must_use]
1851    pub const fn get(self) -> u8 {
1852        self.0
1853    }
1854}
1855
1856/// One bounded, fully verified ascending physical-attempt history page.
1857#[derive(Clone, Debug)]
1858pub struct NodeAttemptHistoryPage {
1859    pub(crate) records: Vec<NodeAttempt>,
1860    pub(crate) has_more: bool,
1861}
1862
1863impl NodeAttemptHistoryPage {
1864    /// Returns immutable physical attempts in ascending start order.
1865    #[must_use]
1866    pub fn records(&self) -> &[NodeAttempt] {
1867        &self.records
1868    }
1869
1870    /// Returns whether a later physical attempt remains in the snapshot.
1871    #[must_use]
1872    pub const fn has_more(&self) -> bool {
1873        self.has_more
1874    }
1875
1876    /// Returns the full last attempt required as the exact next-page cursor.
1877    #[must_use]
1878    pub fn next_cursor(&self) -> Option<NodeAttempt> {
1879        self.records.last().cloned()
1880    }
1881}
1882
1883/// Hard-bounded number of fully decoded pending results in one recovery page.
1884#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1885pub struct PendingNodeResultPageSize(u8);
1886
1887impl PendingNodeResultPageSize {
1888    /// Largest page accepted by the provider.
1889    ///
1890    /// One canonical pending result may occupy 16 MiB and can reference large
1891    /// model records that are verified in bounded sub-batches. Two retained
1892    /// results cap provider-owned decoded page memory near 32 MiB before driver
1893    /// and invocation-verification overhead. Look-ahead rows remain compact.
1894    pub const MAX: u8 = 2;
1895
1896    /// Constructs a positive bounded pending-result page size.
1897    ///
1898    /// # Errors
1899    ///
1900    /// Returns [`StoreError::InvalidPendingNodeResultPageSize`] for zero or
1901    /// values above two.
1902    pub const fn new(value: u8) -> Result<Self, StoreError> {
1903        if value == 0 || value > Self::MAX {
1904            return Err(StoreError::InvalidPendingNodeResultPageSize);
1905        }
1906        Ok(Self(value))
1907    }
1908
1909    /// Returns the page size as an integer.
1910    #[must_use]
1911    pub const fn get(self) -> u8 {
1912        self.0
1913    }
1914}
1915
1916/// Exact stable-snapshot continuation for unconsumed pending-result scanning.
1917///
1918/// The cursor binds the immutable base checkpoint, the run journal head seen
1919/// by the first page, and the last fully verified result. A later result commit
1920/// changes the run journal head, making continuation fail explicitly instead
1921/// of silently skipping a newly inserted lower sort key.
1922#[derive(Clone, Debug, Eq, PartialEq)]
1923pub struct PendingNodeResultPageCursor {
1924    pub(crate) base_checkpoint: CheckpointHead,
1925    pub(crate) snapshot_journal_head: JournalHead,
1926    pub(crate) after: PendingNodeResultHead,
1927}
1928
1929impl PendingNodeResultPageCursor {
1930    /// Returns the exact checkpoint whose unconsumed set is being scanned.
1931    #[must_use]
1932    pub const fn base_checkpoint(&self) -> &CheckpointHead {
1933        &self.base_checkpoint
1934    }
1935
1936    /// Returns the run head that must remain unchanged across page calls.
1937    #[must_use]
1938    pub const fn snapshot_journal_head(&self) -> &JournalHead {
1939        &self.snapshot_journal_head
1940    }
1941
1942    /// Returns the last fully verified result from the preceding page.
1943    #[must_use]
1944    pub const fn after(&self) -> &PendingNodeResultHead {
1945        &self.after
1946    }
1947}
1948
1949/// One bounded, fully verified page of unconsumed pending node results.
1950#[derive(Clone, Debug)]
1951pub struct PendingNodeResultPage {
1952    pub(crate) base_checkpoint: CheckpointHead,
1953    pub(crate) snapshot_journal_head: JournalHead,
1954    pub(crate) records: Vec<PendingNodeResult>,
1955    pub(crate) has_more: bool,
1956}
1957
1958impl PendingNodeResultPage {
1959    /// Returns the exact base checkpoint observed by this page.
1960    #[must_use]
1961    pub const fn base_checkpoint(&self) -> &CheckpointHead {
1962        &self.base_checkpoint
1963    }
1964
1965    /// Returns the stable run journal head shared by every page continuation.
1966    #[must_use]
1967    pub const fn snapshot_journal_head(&self) -> &JournalHead {
1968        &self.snapshot_journal_head
1969    }
1970
1971    /// Returns immutable pending results in canonical activation order.
1972    #[must_use]
1973    pub fn records(&self) -> &[PendingNodeResult] {
1974        &self.records
1975    }
1976
1977    /// Consumes the page and returns its fully verified records without cloning
1978    /// their bounded JSON payloads.
1979    #[must_use]
1980    pub fn into_records(self) -> Vec<PendingNodeResult> {
1981        self.records
1982    }
1983
1984    /// Returns whether a later result remains in the observed snapshot.
1985    #[must_use]
1986    pub const fn has_more(&self) -> bool {
1987        self.has_more
1988    }
1989
1990    /// Returns the exact continuation required for the next page.
1991    #[must_use]
1992    pub fn next_cursor(&self) -> Option<PendingNodeResultPageCursor> {
1993        self.records
1994            .last()
1995            .map(|result| PendingNodeResultPageCursor {
1996                base_checkpoint: self.base_checkpoint.clone(),
1997                snapshot_journal_head: self.snapshot_journal_head.clone(),
1998                after: result.head(),
1999            })
2000    }
2001}
2002
2003/// Hard-bounded number of model invocation revisions in one history page.
2004#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2005pub struct ModelInvocationHistoryPageSize(u8);
2006
2007impl ModelInvocationHistoryPageSize {
2008    /// Largest page accepted by the provider.
2009    ///
2010    /// A compact revision and its separately loaded intent may each occupy up
2011    /// to 128 MiB, so the provider admits only one revision per decoded page.
2012    pub const MAX: u8 = 1;
2013
2014    /// Constructs a positive bounded history page size.
2015    ///
2016    /// # Errors
2017    ///
2018    /// Returns [`StoreError::InvalidModelInvocationPageSize`] unless `value` is one.
2019    pub const fn new(value: u8) -> Result<Self, StoreError> {
2020        if value != Self::MAX {
2021            return Err(StoreError::InvalidModelInvocationPageSize);
2022        }
2023        Ok(Self(value))
2024    }
2025
2026    /// Returns the page size as an integer.
2027    #[must_use]
2028    pub const fn get(self) -> u8 {
2029        self.0
2030    }
2031}
2032
2033/// One bounded, fully verified ascending model-invocation history page.
2034#[derive(Clone, Debug)]
2035pub struct ModelInvocationHistoryPage {
2036    pub(crate) records: Vec<ModelInvocation>,
2037    pub(crate) has_more: bool,
2038}
2039
2040impl ModelInvocationHistoryPage {
2041    /// Returns immutable revisions in ascending order.
2042    #[must_use]
2043    pub fn records(&self) -> &[ModelInvocation] {
2044        &self.records
2045    }
2046
2047    /// Returns whether a later revision remains in the observed snapshot.
2048    #[must_use]
2049    pub const fn has_more(&self) -> bool {
2050        self.has_more
2051    }
2052
2053    /// Returns the full last record required as the exact next-page cursor.
2054    #[must_use]
2055    pub fn next_cursor(&self) -> Option<ModelInvocation> {
2056        self.records.last().cloned()
2057    }
2058}
2059
2060/// Hard-bounded number of invocation revisions returned in one history page.
2061#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2062pub struct ToolInvocationHistoryPageSize(u8);
2063
2064impl ToolInvocationHistoryPageSize {
2065    /// Largest page accepted by the provider.
2066    ///
2067    /// One canonical record may occupy up to 16 MiB, so two records cap the
2068    /// provider-owned decoded page near 32 MiB before driver overhead.
2069    pub const MAX: u8 = 2;
2070
2071    /// Constructs a positive bounded history page size.
2072    ///
2073    /// # Errors
2074    ///
2075    /// Returns [`StoreError::InvalidToolInvocationPageSize`] for zero or values
2076    /// above two.
2077    pub const fn new(value: u8) -> Result<Self, StoreError> {
2078        if value == 0 || value > Self::MAX {
2079            return Err(StoreError::InvalidToolInvocationPageSize);
2080        }
2081        Ok(Self(value))
2082    }
2083
2084    /// Returns the page size as an integer.
2085    #[must_use]
2086    pub const fn get(self) -> u8 {
2087        self.0
2088    }
2089}
2090
2091/// One bounded, fully verified ascending invocation-history page.
2092#[derive(Clone, Debug)]
2093pub struct ToolInvocationHistoryPage {
2094    pub(crate) records: Vec<ToolInvocation>,
2095    pub(crate) has_more: bool,
2096}
2097
2098impl ToolInvocationHistoryPage {
2099    /// Returns immutable revisions in ascending order.
2100    #[must_use]
2101    pub fn records(&self) -> &[ToolInvocation] {
2102        &self.records
2103    }
2104
2105    /// Returns whether a later revision remains in the observed snapshot.
2106    #[must_use]
2107    pub const fn has_more(&self) -> bool {
2108        self.has_more
2109    }
2110
2111    /// Returns the full last record required as the exact next-page cursor.
2112    #[must_use]
2113    pub fn next_cursor(&self) -> Option<ToolInvocation> {
2114        self.records.last().cloned()
2115    }
2116}
2117
2118impl AppendOutcome {
2119    /// Returns the validated committed event.
2120    #[must_use]
2121    pub const fn event(&self) -> &JournalEvent {
2122        match self {
2123            Self::Committed(event) | Self::Idempotent(event) => event,
2124        }
2125    }
2126}
2127
2128/// Lifecycle projection to commit atomically with one journal append.
2129#[allow(clippy::large_enum_variant)]
2130#[derive(Clone, Debug)]
2131#[non_exhaustive]
2132pub enum RunProjection {
2133    /// Preserve the current lifecycle bytes and revision.
2134    Unchanged,
2135    /// Apply one pure lifecycle transition after matching the exact revision.
2136    Transition {
2137        /// Revision from which the pure lifecycle transition was derived.
2138        expected_revision: RunRevision,
2139        /// Transition to apply to the locked durable lifecycle.
2140        transition: RunTransition,
2141    },
2142}
2143
2144/// Compact current-checkpoint pointer projected into the locked run row.
2145///
2146/// The full checkpoint must still be loaded and validated before recovery.
2147#[derive(Clone, Debug, Eq, PartialEq)]
2148pub struct CheckpointPointer {
2149    pub(crate) checkpoint_id: CheckpointId,
2150    pub(crate) superstep: Superstep,
2151    pub(crate) digest: Digest,
2152}
2153
2154impl CheckpointPointer {
2155    /// Returns the immutable checkpoint identity.
2156    #[must_use]
2157    pub const fn checkpoint_id(&self) -> CheckpointId {
2158        self.checkpoint_id
2159    }
2160
2161    /// Returns the current committed barrier position.
2162    #[must_use]
2163    pub const fn superstep(&self) -> Superstep {
2164        self.superstep
2165    }
2166
2167    /// Returns the complete checkpoint checksum.
2168    #[must_use]
2169    pub const fn digest(&self) -> Digest {
2170        self.digest
2171    }
2172}
2173
2174/// Hard-bounded number of checkpoints returned in one lineage page.
2175#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2176pub struct CheckpointLineagePageSize(u8);
2177
2178impl CheckpointLineagePageSize {
2179    /// Largest page accepted by the provider.
2180    ///
2181    /// One checkpoint envelope may occupy roughly 2.5 MiB, so this deliberately
2182    /// remains much smaller than [`JournalPageSize::MAX`]. The provider may
2183    /// decode one additional parent as a fail-closed lineage look-ahead.
2184    pub const MAX: u8 = 8;
2185
2186    /// Constructs a positive bounded checkpoint-lineage page size.
2187    ///
2188    /// # Errors
2189    ///
2190    /// Returns [`StoreError::InvalidCheckpointPageSize`] for zero or values
2191    /// above eight.
2192    pub const fn new(value: u8) -> Result<Self, StoreError> {
2193        if value == 0 || value > Self::MAX {
2194            return Err(StoreError::InvalidCheckpointPageSize);
2195        }
2196        Ok(Self(value))
2197    }
2198
2199    /// Returns the page size as an integer.
2200    #[must_use]
2201    pub const fn get(self) -> u8 {
2202        self.0
2203    }
2204}
2205
2206/// One bounded, fully verified reverse checkpoint-lineage page.
2207#[derive(Clone, Debug, Eq, PartialEq)]
2208pub struct CheckpointLineagePage {
2209    pub(crate) checkpoints: Vec<Checkpoint>,
2210    pub(crate) next_cursor: Option<CheckpointHead>,
2211}
2212
2213impl CheckpointLineagePage {
2214    /// Returns checkpoints in newest-to-oldest lineage order.
2215    #[must_use]
2216    pub fn checkpoints(&self) -> &[Checkpoint] {
2217        &self.checkpoints
2218    }
2219
2220    /// Returns whether older ancestors remain before the superstep-zero root.
2221    #[must_use]
2222    pub const fn has_more(&self) -> bool {
2223        self.next_cursor.is_some()
2224    }
2225
2226    /// Returns the exact parent head at which the next reverse page must start.
2227    #[must_use]
2228    pub fn next_cursor(&self) -> Option<CheckpointHead> {
2229        self.next_cursor.clone()
2230    }
2231}
2232
2233/// Memory ceiling for independently replaying one historical graph barrier.
2234///
2235/// The provider measures the compact serialized size of every fully verified
2236/// pending result before retaining it for the deterministic planner. A single
2237/// bounded result may transiently sit beside the retained set while the limit
2238/// check runs, but the configured aggregate is never exceeded after insertion.
2239#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2240pub struct GraphReplayLimits {
2241    maximum_barrier_result_bytes: usize,
2242}
2243
2244impl GraphReplayLimits {
2245    /// Absolute implementation maximum for retained results in one barrier.
2246    pub const HARD_MAXIMUM_BARRIER_RESULT_BYTES: usize = 512 * 1024 * 1024;
2247
2248    /// Constructs a positive replay memory ceiling.
2249    ///
2250    /// # Errors
2251    ///
2252    /// Returns [`StoreError::InvalidGraphReplayLimits`] for zero or more than
2253    /// 512 MiB.
2254    pub const fn new(maximum_barrier_result_bytes: usize) -> Result<Self, StoreError> {
2255        if maximum_barrier_result_bytes == 0
2256            || maximum_barrier_result_bytes > Self::HARD_MAXIMUM_BARRIER_RESULT_BYTES
2257        {
2258            return Err(StoreError::InvalidGraphReplayLimits);
2259        }
2260        Ok(Self {
2261            maximum_barrier_result_bytes,
2262        })
2263    }
2264
2265    /// Returns the retained compact-result byte ceiling per barrier.
2266    #[must_use]
2267    pub const fn maximum_barrier_result_bytes(self) -> usize {
2268        self.maximum_barrier_result_bytes
2269    }
2270}
2271
2272impl Default for GraphReplayLimits {
2273    fn default() -> Self {
2274        Self {
2275            maximum_barrier_result_bytes: 64 * 1024 * 1024,
2276        }
2277    }
2278}
2279
2280/// Evidence summary returned after complete noninitial checkpoint replay.
2281#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2282pub struct GraphReplayReport {
2283    pub(crate) checkpoints_validated: u64,
2284    pub(crate) barriers_replayed: u64,
2285    pub(crate) results_replayed: u64,
2286    pub(crate) maximum_barrier_result_bytes: usize,
2287}
2288
2289impl GraphReplayReport {
2290    /// Returns every checkpoint whose lineage and graph binding was verified.
2291    #[must_use]
2292    pub const fn checkpoints_validated(self) -> u64 {
2293        self.checkpoints_validated
2294    }
2295
2296    /// Returns the number of parent-to-child transitions independently planned.
2297    #[must_use]
2298    pub const fn barriers_replayed(self) -> u64 {
2299        self.barriers_replayed
2300    }
2301
2302    /// Returns the total number of immutable node results re-evaluated.
2303    #[must_use]
2304    pub const fn results_replayed(self) -> u64 {
2305        self.results_replayed
2306    }
2307
2308    /// Returns the largest retained compact result set observed for one barrier.
2309    #[must_use]
2310    pub const fn maximum_barrier_result_bytes(self) -> usize {
2311        self.maximum_barrier_result_bytes
2312    }
2313}
2314
2315impl RunProjection {
2316    /// Constructs a no-op lifecycle projection.
2317    #[must_use]
2318    pub const fn unchanged() -> Self {
2319        Self::Unchanged
2320    }
2321
2322    /// Constructs an exact-revision pure lifecycle transition.
2323    #[must_use]
2324    pub const fn transition(expected_revision: RunRevision, transition: RunTransition) -> Self {
2325        Self::Transition {
2326            expected_revision,
2327            transition,
2328        }
2329    }
2330}
2331
2332/// Hard-bounded size for tenant-level timer/interrupt discovery pages.
2333#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2334pub struct WaitDiscoveryPageSize(u8);
2335
2336impl WaitDiscoveryPageSize {
2337    /// Largest page accepted by the provider.
2338    pub const MAX: u8 = 16;
2339
2340    /// Constructs a positive bounded discovery page size.
2341    ///
2342    /// # Errors
2343    ///
2344    /// Returns [`StoreError::InvalidWaitDiscoveryPageSize`] outside `1..=16`.
2345    pub const fn new(value: u8) -> Result<Self, StoreError> {
2346        if value == 0 || value > Self::MAX {
2347            return Err(StoreError::InvalidWaitDiscoveryPageSize);
2348        }
2349        Ok(Self(value))
2350    }
2351
2352    /// Returns the page size as an integer.
2353    #[must_use]
2354    pub const fn get(self) -> u8 {
2355        self.0
2356    }
2357}
2358
2359/// Opaque continuation for one fixed-cutoff due-timer scan.
2360#[derive(Clone, Debug, Eq, PartialEq)]
2361pub struct DueTimerPageCursor {
2362    pub(crate) tenant_id: stateknot_core::TenantId,
2363    pub(crate) snapshot_at: Timestamp,
2364    pub(crate) due_at: Timestamp,
2365    pub(crate) run_id: stateknot_core::RunId,
2366    pub(crate) timer_id: stateknot_core::TimerId,
2367}
2368
2369/// One bounded tenant-level page of fully verified outstanding due timers.
2370#[derive(Clone, Debug)]
2371pub struct DueTimerPage {
2372    pub(crate) tenant_id: stateknot_core::TenantId,
2373    pub(crate) snapshot_at: Timestamp,
2374    pub(crate) records: Vec<DurableTimer>,
2375    pub(crate) has_more: bool,
2376}
2377
2378impl DueTimerPage {
2379    /// Returns the database-time cutoff fixed for this page chain.
2380    #[must_use]
2381    pub const fn snapshot_at(&self) -> Timestamp {
2382        self.snapshot_at
2383    }
2384
2385    /// Returns timers ordered by due time, run identity, then timer identity.
2386    #[must_use]
2387    pub fn records(&self) -> &[DurableTimer] {
2388        &self.records
2389    }
2390
2391    /// Returns whether another matching row remained after this page.
2392    #[must_use]
2393    pub const fn has_more(&self) -> bool {
2394        self.has_more
2395    }
2396
2397    /// Returns the exact key required to continue the fixed-cutoff scan.
2398    #[must_use]
2399    pub fn next_cursor(&self) -> Option<DueTimerPageCursor> {
2400        self.records.last().map(|timer| DueTimerPageCursor {
2401            tenant_id: self.tenant_id.clone(),
2402            snapshot_at: self.snapshot_at,
2403            due_at: timer.marker().due_at(),
2404            run_id: timer.intent().run_id(),
2405            timer_id: timer.marker().timer_id(),
2406        })
2407    }
2408}
2409
2410/// Opaque continuation for one fixed-cutoff expired-interrupt scan.
2411#[derive(Clone, Debug, Eq, PartialEq)]
2412pub struct ExpiredInterruptPageCursor {
2413    pub(crate) tenant_id: stateknot_core::TenantId,
2414    pub(crate) snapshot_at: Timestamp,
2415    pub(crate) expires_at: Timestamp,
2416    pub(crate) run_id: stateknot_core::RunId,
2417    pub(crate) interrupt_id: stateknot_core::InterruptId,
2418}
2419
2420/// One bounded tenant-level page of fully verified outstanding expired interrupts.
2421#[derive(Clone, Debug)]
2422pub struct ExpiredInterruptPage {
2423    pub(crate) tenant_id: stateknot_core::TenantId,
2424    pub(crate) snapshot_at: Timestamp,
2425    pub(crate) records: Vec<InterruptRequest>,
2426    pub(crate) has_more: bool,
2427}
2428
2429impl ExpiredInterruptPage {
2430    /// Returns the database-time cutoff fixed for this page chain.
2431    #[must_use]
2432    pub const fn snapshot_at(&self) -> Timestamp {
2433        self.snapshot_at
2434    }
2435
2436    /// Returns requests ordered by expiry, run identity, then interrupt identity.
2437    #[must_use]
2438    pub fn records(&self) -> &[InterruptRequest] {
2439        &self.records
2440    }
2441
2442    /// Returns whether another matching row remained after this page.
2443    #[must_use]
2444    pub const fn has_more(&self) -> bool {
2445        self.has_more
2446    }
2447
2448    /// Returns the exact key required to continue the fixed-cutoff scan.
2449    #[must_use]
2450    pub fn next_cursor(&self) -> Option<ExpiredInterruptPageCursor> {
2451        let request = self.records.last()?;
2452        Some(ExpiredInterruptPageCursor {
2453            tenant_id: self.tenant_id.clone(),
2454            snapshot_at: self.snapshot_at,
2455            expires_at: request.marker().expires_at()?,
2456            run_id: request.intent().run_id(),
2457            interrupt_id: request.marker().interrupt_id(),
2458        })
2459    }
2460}
2461
2462/// Validated durable snapshot of one tenant-scoped run row.
2463#[derive(Clone, Debug)]
2464pub struct StoredRun {
2465    pub(crate) lifecycle: RunLifecycle,
2466    pub(crate) journal_head: Option<JournalHead>,
2467    pub(crate) lease: Option<RunLease>,
2468    pub(crate) last_fencing_epoch: Option<FencingEpoch>,
2469    pub(crate) checkpoint: Option<CheckpointPointer>,
2470    pub(crate) scheduler_ready_at: Option<stateknot_core::Timestamp>,
2471    pub(crate) scheduler_not_before: Option<stateknot_core::Timestamp>,
2472    pub(crate) wait_set_digest: Option<Digest>,
2473    pub(crate) unresolved_wait_count: u8,
2474    pub(crate) next_timer_due_at: Option<Timestamp>,
2475    pub(crate) next_interrupt_expiry_at: Option<Timestamp>,
2476    pub(crate) quarantined: bool,
2477}
2478
2479impl StoredRun {
2480    /// Returns current validated business lifecycle.
2481    #[must_use]
2482    pub const fn lifecycle(&self) -> &RunLifecycle {
2483        &self.lifecycle
2484    }
2485
2486    /// Returns the current exact journal head, if non-empty.
2487    #[must_use]
2488    pub const fn journal_head(&self) -> Option<&JournalHead> {
2489        self.journal_head.as_ref()
2490    }
2491
2492    /// Returns the active lease, including an expired lease not yet reclaimed.
2493    #[must_use]
2494    pub const fn lease(&self) -> Option<&RunLease> {
2495        self.lease.as_ref()
2496    }
2497
2498    /// Returns the last issued fencing epoch; an unleased new run has none.
2499    #[must_use]
2500    pub const fn last_fencing_epoch(&self) -> Option<FencingEpoch> {
2501        self.last_fencing_epoch
2502    }
2503
2504    /// Returns the compact current-checkpoint pointer, if the graph has reached
2505    /// its first durable barrier.
2506    #[must_use]
2507    pub const fn checkpoint(&self) -> Option<&CheckpointPointer> {
2508        self.checkpoint.as_ref()
2509    }
2510
2511    /// Returns when the run most recently entered the durable scheduler queue.
2512    ///
2513    /// Waiting and terminal runs have no readiness observation. A live or
2514    /// expired lease can delay actual availability beyond this instant.
2515    #[must_use]
2516    pub const fn scheduler_ready_at(&self) -> Option<stateknot_core::Timestamp> {
2517        self.scheduler_ready_at
2518    }
2519
2520    /// Returns the durable execution gate for a verified delayed node retry.
2521    ///
2522    /// Queue age remains available through [`Self::scheduler_ready_at`]. A
2523    /// scheduler must not claim this run before the inclusive instant returned
2524    /// here. Claiming at or after the boundary clears the gate atomically.
2525    #[must_use]
2526    pub const fn scheduler_not_before(&self) -> Option<stateknot_core::Timestamp> {
2527        self.scheduler_not_before
2528    }
2529
2530    /// Returns the integrity checksum of the current ordered outstanding wait set.
2531    #[must_use]
2532    pub const fn wait_set_digest(&self) -> Option<Digest> {
2533        self.wait_set_digest
2534    }
2535
2536    /// Returns the number of outstanding interrupt/timer registrations.
2537    #[must_use]
2538    pub const fn unresolved_wait_count(&self) -> u8 {
2539        self.unresolved_wait_count
2540    }
2541
2542    /// Returns the earliest outstanding timer due instant, when present.
2543    #[must_use]
2544    pub const fn next_timer_due_at(&self) -> Option<Timestamp> {
2545        self.next_timer_due_at
2546    }
2547
2548    /// Returns the earliest finite outstanding interrupt expiry, when present.
2549    #[must_use]
2550    pub const fn next_interrupt_expiry_at(&self) -> Option<Timestamp> {
2551        self.next_interrupt_expiry_at
2552    }
2553
2554    /// Returns whether integrity or operator policy quarantined the run.
2555    #[must_use]
2556    pub const fn is_quarantined(&self) -> bool {
2557        self.quarantined
2558    }
2559}
2560
2561/// Hard-bounded number of fully decoded runnable runs in one scheduler page.
2562#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2563pub struct RunnableRunPageSize(u8);
2564
2565impl RunnableRunPageSize {
2566    /// Largest page accepted by the provider.
2567    ///
2568    /// One lifecycle envelope may occupy two MiB. Sixteen retained records plus
2569    /// one driver look-ahead row bound provider-owned page memory near 34 MiB.
2570    pub const MAX: u8 = 16;
2571
2572    /// Constructs a positive bounded runnable-run page size.
2573    ///
2574    /// # Errors
2575    ///
2576    /// Returns [`StoreError::InvalidRunnableRunPageSize`] for zero or values
2577    /// above sixteen.
2578    pub const fn new(value: u8) -> Result<Self, StoreError> {
2579        if value == 0 || value > Self::MAX {
2580            return Err(StoreError::InvalidRunnableRunPageSize);
2581        }
2582        Ok(Self(value))
2583    }
2584
2585    /// Returns the page size as an integer.
2586    #[must_use]
2587    pub const fn get(self) -> u8 {
2588        self.0
2589    }
2590}
2591
2592/// One fully validated run visible to the tenant-level scheduler scan.
2593#[derive(Clone, Debug)]
2594pub struct RunnableRunCandidate {
2595    pub(crate) run: StoredRun,
2596    pub(crate) ready_at: stateknot_core::Timestamp,
2597    pub(crate) available_at: stateknot_core::Timestamp,
2598}
2599
2600impl RunnableRunCandidate {
2601    /// Returns the complete validated durable run projection.
2602    #[must_use]
2603    pub const fn run(&self) -> &StoredRun {
2604        &self.run
2605    }
2606
2607    /// Returns the database observation that inserted the run into the queue.
2608    #[must_use]
2609    pub const fn ready_at(&self) -> stateknot_core::Timestamp {
2610        self.ready_at
2611    }
2612
2613    /// Returns the effective claim time after applying retry and lease gates.
2614    #[must_use]
2615    pub const fn available_at(&self) -> stateknot_core::Timestamp {
2616        self.available_at
2617    }
2618}
2619
2620/// Opaque continuation for one fixed runnable-run database snapshot.
2621#[derive(Clone, Debug, Eq, PartialEq)]
2622pub struct RunnableRunPageCursor {
2623    pub(crate) tenant_id: stateknot_core::TenantId,
2624    pub(crate) snapshot_at: stateknot_core::Timestamp,
2625    pub(crate) available_at: stateknot_core::Timestamp,
2626    pub(crate) run_id: stateknot_core::RunId,
2627}
2628
2629/// One stable, bounded tenant-level scheduler candidate page.
2630#[derive(Clone, Debug)]
2631pub struct RunnableRunPage {
2632    pub(crate) tenant_id: stateknot_core::TenantId,
2633    pub(crate) snapshot_at: stateknot_core::Timestamp,
2634    pub(crate) records: Vec<RunnableRunCandidate>,
2635    pub(crate) has_more: bool,
2636}
2637
2638impl RunnableRunPage {
2639    /// Returns the database time fixed for the complete page chain.
2640    #[must_use]
2641    pub const fn snapshot_at(&self) -> stateknot_core::Timestamp {
2642        self.snapshot_at
2643    }
2644
2645    /// Returns candidates ordered by effective availability then run identity.
2646    #[must_use]
2647    pub fn records(&self) -> &[RunnableRunCandidate] {
2648        &self.records
2649    }
2650
2651    /// Returns whether another candidate remained in this fixed snapshot.
2652    #[must_use]
2653    pub const fn has_more(&self) -> bool {
2654        self.has_more
2655    }
2656
2657    /// Returns the opaque exact key required to continue this snapshot.
2658    #[must_use]
2659    pub fn next_cursor(&self) -> Option<RunnableRunPageCursor> {
2660        self.records.last().map(|candidate| RunnableRunPageCursor {
2661            tenant_id: self.tenant_id.clone(),
2662            snapshot_at: self.snapshot_at,
2663            available_at: candidate.available_at,
2664            run_id: candidate.run.lifecycle().provenance().run_id(),
2665        })
2666    }
2667}
2668
2669/// Result of a lease renewal with stable desired expiry.
2670#[derive(Clone, Debug, Eq, PartialEq)]
2671#[non_exhaustive]
2672pub enum LeaseRenewalOutcome {
2673    /// Renewal extended the durable expiry.
2674    Renewed(RunLease),
2675    /// The same desired expiry had already committed.
2676    Idempotent(RunLease),
2677}
2678
2679/// Exact lease proven live at one database-clock observation.
2680///
2681/// This is short-lived authority evidence, not a promise that the lease remains
2682/// live after [`Self::observed_at`]. Callers performing external work must
2683/// translate the remaining database duration into a conservative monotonic
2684/// deadline and continue renewing beneath the same fence.
2685#[derive(Clone, Debug, Eq, PartialEq)]
2686pub struct LiveLeaseObservation {
2687    pub(crate) lease: RunLease,
2688    pub(crate) observed_at: Timestamp,
2689}
2690
2691impl LiveLeaseObservation {
2692    /// Returns the exact fence and exclusive durable expiry observed.
2693    #[must_use]
2694    pub const fn lease(&self) -> &RunLease {
2695        &self.lease
2696    }
2697
2698    /// Returns the database clock used to prove the lease unexpired.
2699    #[must_use]
2700    pub const fn observed_at(&self) -> Timestamp {
2701        self.observed_at
2702    }
2703
2704    /// Consumes the observation into its lease and database time.
2705    #[must_use]
2706    pub fn into_parts(self) -> (RunLease, Timestamp) {
2707        (self.lease, self.observed_at)
2708    }
2709}
2710
2711/// Result of claiming or explicitly superseding execution ownership.
2712#[derive(Clone, Debug, Eq, PartialEq)]
2713#[non_exhaustive]
2714pub enum LeaseClaimOutcome {
2715    /// A new attempt and successor fencing epoch committed.
2716    Claimed(RunLease),
2717    /// The same stable attempt already owns the current unexpired lease.
2718    Idempotent(RunLease),
2719}
2720
2721impl LeaseClaimOutcome {
2722    /// Returns the current validated lease.
2723    #[must_use]
2724    pub const fn lease(&self) -> &RunLease {
2725        match self {
2726            Self::Claimed(lease) | Self::Idempotent(lease) => lease,
2727        }
2728    }
2729}
2730
2731impl LeaseRenewalOutcome {
2732    /// Returns the current validated lease.
2733    #[must_use]
2734    pub const fn lease(&self) -> &RunLease {
2735        match self {
2736            Self::Renewed(lease) | Self::Idempotent(lease) => lease,
2737        }
2738    }
2739}
2740
2741/// Result of an exact-fence lease release.
2742#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2743#[non_exhaustive]
2744pub enum LeaseReleaseOutcome {
2745    /// The active lease was cleared.
2746    Released,
2747    /// The exact epoch was already released and no successor was issued.
2748    Idempotent,
2749}
2750
2751/// Result of projecting a recovery plan's delayed retry into scheduler state.
2752#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2753#[non_exhaustive]
2754pub enum DelayedRetryScheduleOutcome {
2755    /// The exact live lease was released and the durable wakeup was committed.
2756    Scheduled {
2757        /// Inclusive earliest database instant for another scheduler claim.
2758        not_before: Timestamp,
2759    },
2760    /// The same fence and wakeup had already committed before acknowledgement.
2761    Idempotent {
2762        /// Inclusive earliest database instant already stored for the run.
2763        not_before: Timestamp,
2764    },
2765    /// Database time reached the retry boundary before the deferral committed.
2766    ///
2767    /// The caller retains its lease and should rebuild the recovery plan rather
2768    /// than release and immediately reclaim the same run.
2769    Due {
2770        /// Inclusive retry boundary from the supplied verified plan.
2771        not_before: Timestamp,
2772    },
2773}
2774
2775impl DelayedRetryScheduleOutcome {
2776    /// Returns the inclusive retry boundary shared by every outcome.
2777    #[must_use]
2778    pub const fn not_before(self) -> Timestamp {
2779        match self {
2780            Self::Scheduled { not_before }
2781            | Self::Idempotent { not_before }
2782            | Self::Due { not_before } => not_before,
2783        }
2784    }
2785}
2786
2787/// Hard-bounded number of events returned by one journal read.
2788#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2789pub struct JournalPageSize(u16);
2790
2791impl JournalPageSize {
2792    /// Largest page accepted by the provider.
2793    pub const MAX: u16 = 1_000;
2794
2795    /// Constructs a positive bounded page size.
2796    ///
2797    /// # Errors
2798    ///
2799    /// Returns [`StoreError::InvalidPageSize`] for zero or values above 1,000.
2800    pub const fn new(value: u16) -> Result<Self, StoreError> {
2801        if value == 0 || value > Self::MAX {
2802            return Err(StoreError::InvalidPageSize);
2803        }
2804        Ok(Self(value))
2805    }
2806
2807    /// Returns the page size as an integer.
2808    #[must_use]
2809    pub const fn get(self) -> u16 {
2810        self.0
2811    }
2812}
2813
2814/// One bounded, validated page from a run journal.
2815#[derive(Clone, Debug, Eq, PartialEq)]
2816pub struct JournalPage {
2817    pub(crate) events: Vec<JournalEvent>,
2818    pub(crate) has_more: bool,
2819}
2820
2821impl JournalPage {
2822    /// Returns events in ascending contiguous sequence order.
2823    #[must_use]
2824    pub fn events(&self) -> &[JournalEvent] {
2825        &self.events
2826    }
2827
2828    /// Returns whether another page exists after the final returned sequence.
2829    #[must_use]
2830    pub const fn has_more(&self) -> bool {
2831        self.has_more
2832    }
2833
2834    /// Returns the complete final event head to use as the next exact cursor.
2835    #[must_use]
2836    pub fn next_cursor(&self) -> Option<JournalHead> {
2837        self.events.last().map(JournalEvent::head)
2838    }
2839}