Skip to main content

stateknot_store_postgres/
error.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use thiserror::Error;
5
6/// Invalid `PostgreSQL` provider configuration.
7#[derive(Clone, Debug, Eq, Error, PartialEq)]
8#[non_exhaustive]
9pub enum ConfigurationError {
10    /// A required environment variable was absent.
11    #[error("required PostgreSQL environment variable {name} is missing")]
12    MissingEnvironmentVariable {
13        /// Stable environment variable name; never a secret value.
14        name: &'static str,
15    },
16    /// An environment variable was non-Unicode or used an unsupported value.
17    #[error("PostgreSQL environment variable {name} is invalid")]
18    InvalidEnvironmentVariable {
19        /// Stable environment variable name; never a secret value.
20        name: &'static str,
21    },
22    /// A required connection URL was empty.
23    #[error("PostgreSQL connection URL must not be empty")]
24    EmptyDatabaseUrl,
25    /// Production auto-migration omitted a dedicated credential.
26    #[error("production auto-migration requires STATEKNOT_MIGRATION_DATABASE_URL")]
27    MigrationDatabaseUrlRequired,
28    /// Production migration and runtime credentials were exactly the same URL.
29    #[error("production migration and runtime PostgreSQL URLs must be distinct")]
30    SharedProductionMigrationCredential,
31    /// The connection URL could not be parsed. The URL is intentionally omitted.
32    #[error("PostgreSQL connection URL is invalid")]
33    InvalidDatabaseUrl,
34    /// A pool with zero possible connections cannot make progress.
35    #[error("PostgreSQL maximum connections must be positive")]
36    ZeroMaximumConnections,
37    /// Minimum pool size exceeded maximum pool size.
38    #[error("PostgreSQL minimum connections must not exceed maximum connections")]
39    PoolMinimumExceedsMaximum,
40    /// A required timeout or lease duration was zero.
41    #[error("{name} must be positive")]
42    ZeroDuration {
43        /// Stable configuration field name.
44        name: &'static str,
45    },
46    /// A duration could not fit the signed microsecond database contract.
47    #[error("{name} exceeds the signed microsecond storage range")]
48    DurationTooLarge {
49        /// Stable configuration field name.
50        name: &'static str,
51    },
52    /// Lock timeout would not fire strictly before the statement timeout.
53    #[error("lock timeout must be strictly less than statement timeout")]
54    LockTimeoutNotBelowStatementTimeout,
55    /// A server-side timeout exceeded `PostgreSQL`'s signed millisecond range.
56    #[error("{name} exceeds PostgreSQL's signed millisecond timeout range")]
57    PostgresTimeoutTooLarge {
58        /// Stable configuration field name.
59        name: &'static str,
60    },
61    /// Durable lease timing was not exactly representable as microseconds.
62    #[error("{name} must be a positive whole number of microseconds")]
63    LeaseTimingNotMicrosecondAligned {
64        /// Stable configuration field name.
65        name: &'static str,
66    },
67    /// Initial leases exceeded the configured renewal safety horizon.
68    #[error("lease duration must not exceed the maximum lease horizon")]
69    LeaseDurationExceedsMaximumHorizon,
70    /// Fixed outbox attempt lease exceeded the core five-minute bound.
71    #[error("outbox attempt lease must not exceed five minutes")]
72    OutboxAttemptLeaseTooLong,
73}
74
75/// Durable `PostgreSQL` operation failure with payload-redacted diagnostics.
76#[derive(Debug, Error)]
77#[non_exhaustive]
78pub enum StoreError {
79    /// The failure-close boundary lacks complete settled direct evidence or scope.
80    #[error("invalid failure close boundary or evidence")]
81    InvalidRunFailureClose,
82    /// An immutable failure decision already owns this run's execution boundary.
83    #[error("run is sealed for failure closure")]
84    RunFailureClosing,
85    /// An older writer cannot mutate a failure-closing run.
86    #[error("compatible failure close runtime is required")]
87    UnsupportedFailureCloseRuntime,
88    /// Invalid tenant cursor or deadline cancellation audit construction.
89    #[error("Agent deadline request or scan scope is invalid")]
90    InvalidAgentDeadline,
91    /// Missing, mismatched or unconsumed dedicated child Join evidence.
92    #[error("child Join evidence is unavailable or conflicts with this result")]
93    ChildJoinRejected,
94    /// No durable parent cancellation witness owns this child key.
95    #[error("child cancellation request was not found")]
96    ChildCancellationNotFound,
97    /// A pre-child binary attempted to mutate a child-enabled run.
98    #[error("compatible child runtime is required")]
99    UnsupportedChildRuntime,
100    /// Terminal accounting omitted already recorded direct or delegated usage.
101    #[error("terminal child accounting is incomplete")]
102    IncompleteChildAccounting,
103    /// Owned-child records, immutable input or scope do not match.
104    #[error("child run commit conflicts with durable ownership")]
105    ChildRunConflict,
106    /// No ownership record exists inside the supplied parent/tenant boundary.
107    #[error("child run ownership was not found")]
108    ChildRunNotFound,
109    /// A fresh child admission failed readiness, authority or budget validation.
110    #[error("child run admission was rejected")]
111    ChildRunRejected,
112    /// An ancestor's finite depth or unsettled-descendant ceiling was reached.
113    #[error("child run topology limit reached")]
114    ChildRunTopologyExceeded,
115    /// Outstanding child work blocks direct external dispatch or parent closure.
116    #[error("unsettled children block this run mutation")]
117    UnsettledChildRuns,
118    /// Invocation start requires a fresh verified child-adjusted budget snapshot.
119    #[error("child-adjusted invocation budget observation is required")]
120    ChildBudgetObservationRequired,
121    /// No complete, fully priced immutable terminal evidence is available yet.
122    #[error("child run terminal settlement evidence is unavailable")]
123    ChildRunSettlementUnavailable,
124    /// Provider configuration was invalid.
125    #[error(transparent)]
126    Configuration(#[from] ConfigurationError),
127    /// Connection or SQL execution failed.
128    #[error("PostgreSQL {operation} failed")]
129    Database {
130        /// Stable operation category without SQL or bound values.
131        operation: &'static str,
132        /// Underlying driver error.
133        #[source]
134        source: sqlx_core::Error,
135    },
136    /// Ordered schema migration failed.
137    #[error("PostgreSQL schema migration failed")]
138    Migration {
139        /// Underlying migration error.
140        #[source]
141        source: sqlx_core::migrate::MigrateError,
142    },
143    /// The connected server is outside the qualified major versions.
144    #[error("PostgreSQL server major version is unsupported")]
145    UnsupportedServerVersion,
146    /// Required migration metadata has not been installed.
147    #[error("StateKnot PostgreSQL schema has not been migrated")]
148    SchemaNotMigrated,
149    /// Applied migration versions or checksums do not match this binary.
150    #[error("StateKnot PostgreSQL schema is incompatible with this binary")]
151    IncompatibleSchema,
152    /// Migration metadata exists but required schema objects are missing.
153    #[error("StateKnot PostgreSQL schema objects are incomplete")]
154    IncompleteSchema,
155    /// Private artifact object coordinates violated the portable storage contract.
156    #[error("artifact storage locator is invalid")]
157    InvalidArtifactStorageLocator,
158    /// No immutable artifact exists inside the supplied tenant boundary.
159    #[error("artifact was not found in the tenant registry")]
160    ArtifactNotFound,
161    /// An artifact identity, idempotency key, or object locator already owns another record.
162    #[error("artifact registration conflicts with durable registry evidence")]
163    ArtifactRegistrationConflict,
164    /// A direct artifact parent does not already exist in the same tenant.
165    #[error("artifact parent was not found in the tenant registry")]
166    ArtifactParentNotFound,
167    /// The artifact's causing run event does not exist in the same tenant.
168    #[error("artifact provenance event was not found in the tenant journal")]
169    ArtifactProvenanceNotFound,
170    /// No exact compiled graph exists inside the supplied tenant registry.
171    #[error("compiled graph definition was not found in the tenant registry")]
172    GraphDefinitionNotFound,
173    /// A graph version was already registered with different immutable bytes.
174    #[error("compiled graph identity already exists with a different definition")]
175    GraphDefinitionConflict,
176    /// A fairness policy was empty, oversized, or had an invalid cycle length.
177    #[error("scheduler fairness policy registration is invalid")]
178    InvalidSchedulerFairnessPolicy,
179    /// Reservation retention duration or batch bounds are unsafe.
180    #[error("scheduler fairness reservation retention policy is invalid")]
181    InvalidSchedulerFairnessRetention,
182    /// A scheduler shard identity already owns another immutable policy.
183    #[error("scheduler fairness shard already exists with a different policy")]
184    SchedulerFairnessPolicyConflict,
185    /// No immutable fairness policy exists for the supplied scheduler shard.
186    #[error("scheduler fairness policy was not found")]
187    SchedulerFairnessPolicyNotFound,
188    /// A reservation retry named another shard or policy snapshot.
189    #[error("scheduler fairness reservation identity conflicts with durable evidence")]
190    SchedulerFairnessReservationConflict,
191    /// The durable fairness reservation sequence reached its supported ceiling.
192    #[error("scheduler fairness reservation sequence is exhausted")]
193    SchedulerFairnessSequenceExhausted,
194    /// No run exists inside the supplied tenant boundary.
195    #[error("run was not found in the tenant boundary")]
196    RunNotFound,
197    /// Run admission reused an identity with different provenance.
198    #[error("run identity already exists with different admission provenance")]
199    RunConflict,
200    /// No immutable Agent admission snapshot exists for this tenant-scoped run.
201    #[error("agent admission was not found in the tenant-scoped run")]
202    AgentAdmissionNotFound,
203    /// The supplied event, checkpoint, graph, or scope cannot form an atomic admission.
204    #[error("agent admission commit input is invalid")]
205    InvalidAgentAdmissionCommit,
206    /// Database-time budget evaluation rejected a new Agent admission.
207    #[error("agent admission was rejected at its durable commit observation")]
208    AgentAdmissionRejected,
209    /// The exact pinned state-schema validator was unavailable or panicked.
210    #[error("agent admission state-schema dependency is unavailable")]
211    AgentAdmissionSchemaUnavailable,
212    /// Initial graph state did not satisfy the exact pinned state schema.
213    #[error("agent admission initial state was rejected by its pinned schema")]
214    AgentAdmissionStateRejected,
215    /// The run identity or one stable anchor belongs to another admission intent.
216    #[error("agent admission identity conflicts with durable evidence")]
217    AgentAdmissionConflict,
218    /// No durable ingress idempotency mapping exists for this tenant/key.
219    #[error("agent submission key was not found in the tenant boundary")]
220    AgentSubmissionNotFound,
221    /// One ingress key was reused for a different immutable submission.
222    #[error("agent submission key conflicts with durable submission evidence")]
223    AgentSubmissionConflict,
224    /// The run is quarantined and cannot execute or mutate normally.
225    #[error("run is quarantined")]
226    RunQuarantined,
227    /// A quarantine component code violated its bounded machine grammar.
228    #[error("run quarantine component code is invalid")]
229    InvalidRunQuarantineComponent,
230    /// A quarantine request crossed its tenant/run journal observation.
231    #[error("run quarantine request is invalid")]
232    InvalidRunQuarantineRequest,
233    /// No audit-grade quarantine observation exists for the supplied run.
234    #[error("run quarantine evidence was not found in the tenant-scoped run")]
235    RunQuarantineNotFound,
236    /// A stable quarantine identity was reused for another immutable intent.
237    #[error("run quarantine identity conflicts with durable evidence")]
238    RunQuarantineIdConflict,
239    /// Another immutable quarantine observation already owns the run.
240    #[error("run already has different durable quarantine evidence")]
241    RunQuarantineConflict,
242    /// The run journal changed after the evidence observation was constructed.
243    #[error("run quarantine journal observation is stale")]
244    StaleRunQuarantineObservation,
245    /// A claimed recovery session crossed its fence, tenant, or run boundary.
246    #[error("claimed run recovery context is invalid")]
247    InvalidClaimedRunRecoveryContext,
248    /// Durable journal progress invalidated the claimed recovery observation.
249    #[error("claimed run recovery journal observation is stale")]
250    StaleClaimedRunRecoveryObservation,
251    /// Ready-node recovery was requested before an initial checkpoint exists.
252    #[error("ready-node recovery requires a current graph checkpoint")]
253    ReadyNodeRecoveryCheckpointMissing,
254    /// Replay could not run because the exact local schema or reducer was not available.
255    #[error("noninitial graph replay dependency is unavailable on this worker")]
256    GraphReplayDependencyUnavailable,
257    /// Replay result material exceeded the explicitly configured memory bound.
258    #[error("noninitial graph replay exceeds its configured barrier byte limit")]
259    GraphReplayResourceLimit,
260    /// A recovery plan, journal append, fence, or node selection crossed scope.
261    #[error("ready-node dispatch plan is invalid for the requested durable start")]
262    InvalidReadyNodeDispatchPlan,
263    /// The selected recovery-plan node does not authorize a new physical start.
264    #[error("ready-node recovery decision is not dispatchable")]
265    ReadyNodeNotDispatchable,
266    /// A recovery plan contains immediate, in-flight, or terminal work and
267    /// therefore cannot be projected as one delayed retry wakeup.
268    #[error("ready-node recovery plan cannot schedule a delayed retry wakeup")]
269    InvalidDelayedRetryPlan,
270    /// Immutable quarantine evidence and the mutable run projection disagree.
271    #[error("run quarantine evidence conflicts with its durable projection")]
272    RunQuarantineCommitConflict,
273    /// The run lifecycle is not currently runnable.
274    #[error("run lifecycle is not runnable")]
275    RunNotRunnable,
276    /// A durable scheduler gate has not reached its inclusive database time.
277    #[error("run is not yet available for a scheduler claim")]
278    RunNotYetAvailable,
279    /// A caller reached the wrong trusted append entry point.
280    #[error("journal append source is not authorized by this entry point")]
281    WrongAppendAuthority,
282    /// A stable event ID was reused for a different immutable intent.
283    #[error("journal event identity conflicts with a committed intent")]
284    EventIdConflict,
285    /// A retry reused an event ID with a different or unverifiable projection intent.
286    #[error("journal event projection conflicts with the committed projection intent")]
287    ProjectionIntentConflict,
288    /// The supplied complete journal head did not match the locked run row.
289    #[error("journal expectation does not match the current durable head")]
290    StaleJournalHead,
291    /// No checkpoint exists for the supplied tenant/run/checkpoint identity.
292    #[error("checkpoint was not found in the tenant-scoped run")]
293    CheckpointNotFound,
294    /// A stable checkpoint ID was reused for a different immutable write intent.
295    #[error("checkpoint identity conflicts with a committed write intent")]
296    CheckpointIdConflict,
297    /// Event and checkpoint idempotency records do not describe one atomic commit.
298    #[error("journal event and checkpoint identities conflict with an atomic commit")]
299    CheckpointCommitConflict,
300    /// A wait batch was empty, oversized, duplicated, or crossed scope/event identity.
301    #[error("durable wait registration batch is invalid")]
302    InvalidWaitRegistrationBatch,
303    /// Wait event, checkpoint, lifecycle markers, and registration rows disagree.
304    #[error("durable wait registration conflicts with the atomic commit")]
305    WaitRegistrationCommitConflict,
306    /// No durable wait registration exists under the supplied tenant/run/identity.
307    #[error("durable wait registration was not found in the tenant-scoped run")]
308    WaitRegistrationNotFound,
309    /// A wait identity was loaded through the wrong interrupt/timer API.
310    #[error("durable wait registration kind does not match the requested API")]
311    WaitRegistrationKindMismatch,
312    /// Resolution intent did not match an outstanding durable interrupt.
313    #[error("interrupt resolution is invalid for the locked durable request")]
314    InvalidInterruptResolution,
315    /// Resolution event, immutable detail, and mutable wait projection disagree.
316    #[error("interrupt resolution conflicts with the atomic commit")]
317    InterruptResolutionCommitConflict,
318    /// Timer firing intent did not match an outstanding due durable timer.
319    #[error("timer firing is invalid for the locked durable timer")]
320    InvalidTimerFiring,
321    /// Firing event, immutable detail, and mutable wait projection disagree.
322    #[error("timer firing conflicts with the atomic commit")]
323    TimerFiringCommitConflict,
324    /// A wait-discovery page size was zero or exceeded the decoded-memory bound.
325    #[error("wait discovery page size is invalid")]
326    InvalidWaitDiscoveryPageSize,
327    /// A due-timer page cursor crossed tenant/cutoff/order scope.
328    #[error("due timer page cursor is invalid")]
329    InvalidDueTimerCursor,
330    /// An expired-interrupt page cursor crossed tenant/cutoff/order scope.
331    #[error("expired interrupt page cursor is invalid")]
332    InvalidExpiredInterruptCursor,
333    /// The supplied run-level edge was not cancellation/failure from waiting.
334    #[error("wait abandonment transition is invalid")]
335    InvalidWaitAbandonment,
336    /// Abandonment event, detail set, and mutable wait projections disagree.
337    #[error("wait abandonment conflicts with the atomic commit")]
338    WaitAbandonmentCommitConflict,
339    /// The requested wait has no immutable abandonment audit fact.
340    #[error("wait abandonment was not found in the tenant-scoped run")]
341    WaitAbandonmentNotFound,
342    /// Resolution/firing history was requested for a wait abandoned by the run.
343    #[error("durable wait was abandoned without resolution or firing")]
344    WaitWasAbandoned,
345    /// A successor checkpoint must prove the complete result barrier it consumes.
346    #[error("successor checkpoint commit requires a complete checkpoint barrier")]
347    CheckpointBarrierRequired,
348    /// The supplied barrier did not match its fully restored durable base.
349    #[error("checkpoint barrier does not match its durable base checkpoint")]
350    InvalidCheckpointBarrier,
351    /// At least one result required by the complete barrier is not durable.
352    #[error("checkpoint barrier is incomplete")]
353    CheckpointBarrierIncomplete,
354    /// Durable pending-result identities do not equal the supplied complete barrier.
355    #[error("checkpoint barrier result set conflicts with durable pending results")]
356    CheckpointBarrierResultConflict,
357    /// Barrier event, checkpoint, and consumption rows do not describe one atomic commit.
358    #[error("checkpoint barrier identities conflict with an atomic commit")]
359    CheckpointBarrierCommitConflict,
360    /// The supplied complete checkpoint parent did not match the locked run row.
361    #[error("checkpoint parent does not match the current durable checkpoint")]
362    StaleCheckpointHead,
363    /// A tool invocation on the current checkpoint has not committed a result.
364    #[error("checkpoint advancement is blocked by an unsettled tool invocation")]
365    CheckpointBlockedByToolInvocation,
366    /// No logical tool invocation exists in the supplied tenant/run boundary.
367    #[error("tool invocation was not found in the tenant-scoped run")]
368    ToolInvocationNotFound,
369    /// Receipt provenance or descriptor/input binding crossed its durable boundary.
370    #[error("Tool authorization receipt is invalid for the durable invocation boundary")]
371    InvalidToolAuthorizationReceipt,
372    /// No exact receipt or referenced durable invocation boundary exists.
373    #[error("Tool authorization receipt was not found in the tenant boundary")]
374    ToolAuthorizationReceiptNotFound,
375    /// A receipt identity was reused with different immutable canonical bytes.
376    #[error("Tool authorization receipt identity conflicts with durable evidence")]
377    ToolAuthorizationReceiptConflict,
378    /// A receipt audit page size was zero or exceeded its decoded-memory bound.
379    #[error("Tool authorization receipt page size is invalid")]
380    InvalidToolAuthorizationReceiptPageSize,
381    /// A receipt audit cursor crossed scope or did not match immutable storage.
382    #[error("Tool authorization receipt cursor is invalid")]
383    InvalidToolAuthorizationReceiptCursor,
384    /// Skill activation approval or acting-window evidence crossed its durable scope.
385    #[error("Skill activation evidence is invalid for the durable run boundary")]
386    InvalidSkillActivation,
387    /// No exact Skill acting window exists in the tenant boundary.
388    #[error("Skill acting window was not found in the tenant boundary")]
389    SkillActingWindowNotFound,
390    /// A Skill approval or window identity was reused with different evidence.
391    #[error("Skill activation identity conflicts with durable evidence")]
392    SkillActivationConflict,
393    /// The exact acting window expired or has an immutable revocation.
394    #[error("Skill acting window is inactive")]
395    SkillActingWindowInactive,
396    /// A stable invocation ID was reused with a different immutable intent.
397    #[error("tool invocation identity conflicts with a committed intent")]
398    ToolInvocationIdConflict,
399    /// Event and invocation records do not describe one atomic commit.
400    #[error("journal event and tool invocation identities conflict with an atomic commit")]
401    ToolInvocationCommitConflict,
402    /// The supplied complete invocation head did not match its durable current row.
403    #[error("tool invocation head is stale")]
404    StaleToolInvocationHead,
405    /// The requested invocation state transition was invalid for durable state.
406    #[error("tool invocation transition is invalid for the locked record")]
407    InvalidToolInvocationTransition,
408    /// The invocation activation is not a ready root-graph node of its checkpoint.
409    #[error("tool invocation activation is not ready in the base checkpoint")]
410    InvalidToolInvocationActivation,
411    /// A model invocation on the current checkpoint has not committed a response.
412    #[error("checkpoint advancement is blocked by an unsettled model invocation")]
413    CheckpointBlockedByModelInvocation,
414    /// No logical model invocation exists in the supplied tenant/run boundary.
415    #[error("model invocation was not found in the tenant-scoped run")]
416    ModelInvocationNotFound,
417    /// A stable model invocation ID was reused with a different immutable intent.
418    #[error("model invocation identity conflicts with a committed intent")]
419    ModelInvocationIdConflict,
420    /// Event and model invocation records do not describe one atomic commit.
421    #[error("journal event and model invocation identities conflict with an atomic commit")]
422    ModelInvocationCommitConflict,
423    /// The supplied complete model invocation head did not match its durable current row.
424    #[error("model invocation head is stale")]
425    StaleModelInvocationHead,
426    /// The requested model invocation transition was invalid for durable state.
427    #[error("model invocation transition is invalid for the locked record")]
428    InvalidModelInvocationTransition,
429    /// The model invocation activation is not a ready root-graph node of its checkpoint.
430    #[error("model invocation activation is not ready in the base checkpoint")]
431    InvalidModelInvocationActivation,
432    /// No pending result exists for the supplied logical node activation key.
433    #[error("pending node result was not found in the tenant-scoped run")]
434    PendingNodeResultNotFound,
435    /// A logical activation already has a different immutable semantic result.
436    #[error("pending node result conflicts with the committed semantic intent")]
437    PendingNodeResultConflict,
438    /// Event and pending-result rows do not describe one atomic commit.
439    #[error("journal event and pending node result conflict with an atomic commit")]
440    PendingNodeResultCommitConflict,
441    /// The pending result activation is not a ready root-graph node of its checkpoint.
442    #[error("pending node result activation is not ready in the base checkpoint")]
443    InvalidPendingNodeResultActivation,
444    /// New pending results must be committed through a durable physical node attempt.
445    #[error("pending node result commit requires a durable node attempt")]
446    NodeAttemptRequired,
447    /// The result's temporal or control invariants cannot commit at the database observation.
448    #[error("pending node result is invalid at its durable commit position")]
449    InvalidPendingNodeResult,
450    /// A pending result named an absent, non-committed, or crossed invocation revision.
451    #[error("pending node result contains an invalid external invocation binding")]
452    InvalidPendingNodeResultBinding,
453    /// A pending-result page size exceeded its decoded-memory safety bound.
454    #[error("pending node result page size is invalid")]
455    InvalidPendingNodeResultPageSize,
456    /// A pending-result page cursor crossed scope or did not match its durable row.
457    #[error("pending node result cursor is invalid")]
458    InvalidPendingNodeResultCursor,
459    /// No physical node attempt exists in the supplied tenant/run boundary.
460    #[error("node attempt was not found in the tenant-scoped run")]
461    NodeAttemptNotFound,
462    /// A stable physical attempt identity was reused for another owner.
463    #[error("node attempt identity conflicts with a committed owner")]
464    NodeAttemptIdConflict,
465    /// Event and node-attempt rows do not describe one atomic commit.
466    #[error("journal event and node attempt conflict with an atomic commit")]
467    NodeAttemptCommitConflict,
468    /// The attempt activation is not a ready root-graph node of its checkpoint.
469    #[error("node attempt activation is not ready in the base checkpoint")]
470    InvalidNodeAttemptActivation,
471    /// The requested physical-attempt transition is invalid for durable history.
472    #[error("node attempt transition is invalid for the locked history")]
473    InvalidNodeAttemptTransition,
474    /// One logical activation reached the hard physical-attempt ceiling.
475    #[error("node attempt history reached its hard physical-attempt limit")]
476    NodeAttemptLimitExceeded,
477    /// The supplied exact start does not match the durable physical attempt.
478    #[error("node attempt start is stale")]
479    StaleNodeAttemptStart,
480    /// A node-attempt history cursor did not identify the exact stored attempt.
481    #[error("node attempt history cursor does not match a durable attempt")]
482    InvalidNodeAttemptCursor,
483    /// A node-attempt history page size exceeded its decoded-memory safety bound.
484    #[error("node attempt history page size is invalid")]
485    InvalidNodeAttemptPageSize,
486    /// A runnable-run page size exceeded its decoded-memory safety bound.
487    #[error("runnable run page size is invalid")]
488    InvalidRunnableRunPageSize,
489    /// A runnable-run cursor crossed tenant scope or contained an invalid key.
490    #[error("runnable run cursor is invalid")]
491    InvalidRunnableRunCursor,
492    /// An outbox enqueue batch was empty, duplicated, or exceeded its hard bound.
493    #[error("outbox enqueue batch is invalid")]
494    InvalidOutboxBatch,
495    /// Destination snapshot digest did not match its canonical configuration.
496    #[error("outbox destination snapshot does not match its canonical configuration")]
497    OutboxDestinationSnapshotMismatch,
498    /// No immutable destination snapshot exists in the tenant boundary.
499    #[error("outbox destination snapshot was not found in the tenant boundary")]
500    OutboxDestinationNotFound,
501    /// A destination snapshot identity conflicts with durable configuration.
502    #[error("outbox destination snapshot conflicts with durable configuration")]
503    OutboxDestinationConflict,
504    /// No outbox delivery exists in the supplied tenant/run boundary.
505    #[error("outbox delivery was not found in the tenant-scoped run")]
506    OutboxDeliveryNotFound,
507    /// A stable delivery identity conflicts with a committed immutable intent.
508    #[error("outbox delivery identity conflicts with a committed intent")]
509    OutboxDeliveryIdConflict,
510    /// Journal event and complete outbox set do not describe one atomic commit.
511    #[error("journal event and outbox deliveries conflict with an atomic commit")]
512    OutboxEnqueueConflict,
513    /// A physical outbox attempt identity was already claimed by another owner.
514    #[error("outbox attempt identity conflicts with a committed owner")]
515    OutboxAttemptIdConflict,
516    /// The supplied delivery fence is not the exact current attempt.
517    #[error("outbox delivery fencing token is stale")]
518    StaleOutboxFence,
519    /// The current outbox attempt reached its exclusive database expiry.
520    #[error("outbox attempt lease has expired")]
521    OutboxAttemptExpired,
522    /// A delivery attempt has no durable start in the tenant-scoped run.
523    #[error("outbox attempt was not found in the tenant-scoped run")]
524    OutboxAttemptNotFound,
525    /// A completion conflicts with an already committed terminal attempt.
526    #[error("outbox attempt completion conflicts with durable evidence")]
527    OutboxCompletionConflict,
528    /// The requested outbox state transition is invalid for durable history.
529    #[error("outbox attempt transition is invalid for the locked history")]
530    InvalidOutboxTransition,
531    /// An outbox history cursor did not identify the exact stored attempt.
532    #[error("outbox attempt history cursor does not match a durable attempt")]
533    InvalidOutboxAttemptCursor,
534    /// An outbox-attempt page size exceeded its decoded-memory safety bound.
535    #[error("outbox attempt history page size is invalid")]
536    InvalidOutboxAttemptPageSize,
537    /// The run journal advanced after an earlier pending-result page snapshot.
538    #[error("pending node result page snapshot is stale and must be restarted")]
539    StalePendingNodeResultSnapshot,
540    /// A pagination cursor did not identify the exact stored event head.
541    #[error("journal cursor does not match a durable event")]
542    InvalidJournalCursor,
543    /// A reverse-lineage cursor did not identify the exact stored checkpoint head.
544    #[error("checkpoint lineage cursor does not match a durable checkpoint")]
545    InvalidCheckpointCursor,
546    /// An invocation-history cursor did not identify the exact stored revision.
547    #[error("tool invocation history cursor does not match a durable revision")]
548    InvalidToolInvocationCursor,
549    /// A model-invocation history cursor did not identify the exact stored revision.
550    #[error("model invocation history cursor does not match a durable revision")]
551    InvalidModelInvocationCursor,
552    /// No higher signed `PostgreSQL` journal sequence exists.
553    #[error("journal sequence is exhausted")]
554    JournalSequenceExhausted,
555    /// The expected lifecycle revision did not match the locked run row.
556    #[error("lifecycle projection revision is stale")]
557    StaleLifecycleRevision,
558    /// The requested lifecycle transition was not a valid direct successor.
559    #[error("lifecycle transition is invalid for the locked run state")]
560    InvalidLifecycleTransition,
561    /// A durable-wait edge was attempted through a journal-only mutation path.
562    #[error("durable wait lifecycle changes require the atomic wait persistence API")]
563    DurableWaitMutationRequired,
564    /// A lifecycle observation claimed to occur after the journal commit clock.
565    #[error("lifecycle transition observation is later than the journal commit observation")]
566    LifecycleObservationAfterCommit,
567    /// Another unexpired worker lease currently owns the run.
568    #[error("run already has an unexpired worker lease")]
569    LeaseHeld,
570    /// No active lease can satisfy the requested mutation.
571    #[error("run has no active worker lease")]
572    NoActiveLease,
573    /// Attempt or fencing epoch did not match the current lease.
574    #[error("worker fencing token is stale")]
575    StaleFence,
576    /// The exact lease reached its exclusive database expiry.
577    #[error("worker lease has expired")]
578    LeaseExpired,
579    /// The database wall clock moved before a durable lease observation.
580    #[error("database clock precedes a durable lease observation")]
581    DatabaseClockRegression,
582    /// Renewal did not strictly extend the current expiry.
583    #[error("worker lease renewal must strictly extend the current expiry")]
584    LeaseExpiryNotExtended,
585    /// Renewal requested an expiry beyond the configured safety horizon.
586    #[error("worker lease renewal exceeds the configured maximum horizon")]
587    LeaseHorizonExceeded,
588    /// No higher signed `PostgreSQL` fencing epoch exists.
589    #[error("worker fencing epoch is exhausted")]
590    FencingEpochExhausted,
591    /// A requested journal page exceeded the hard bound.
592    #[error("journal page size is invalid")]
593    InvalidPageSize,
594    /// A requested checkpoint-lineage page exceeded its memory-safety bound.
595    #[error("checkpoint lineage page size is invalid")]
596    InvalidCheckpointPageSize,
597    /// A graph replay memory limit was zero or exceeded its implementation bound.
598    #[error("noninitial graph replay limits are invalid")]
599    InvalidGraphReplayLimits,
600    /// A requested invocation-history page exceeded its memory-safety bound.
601    #[error("tool invocation history page size is invalid")]
602    InvalidToolInvocationPageSize,
603    /// A requested model-invocation history page exceeded its memory-safety bound.
604    #[error("model invocation history page size is invalid")]
605    InvalidModelInvocationPageSize,
606    /// Trusted in-process domain data could not be serialized canonically.
607    #[error("{record} could not be encoded for durable storage")]
608    Encoding {
609        /// Stable record category without user data.
610        record: &'static str,
611    },
612    /// Durable bytes or redundant columns failed closed validation.
613    #[error("durable {record} failed integrity validation")]
614    CorruptData {
615        /// Stable record category without payload or identifiers.
616        record: &'static str,
617    },
618}
619
620impl StoreError {
621    pub(crate) fn database(operation: &'static str, source: sqlx_core::Error) -> Self {
622        match source
623            .as_database_error()
624            .and_then(sqlx_core::error::DatabaseError::code)
625            .as_deref()
626        {
627            Some("SKC01") => return Self::UnsupportedChildRuntime,
628            Some("SKC02") => return Self::UnsettledChildRuns,
629            Some("SKC03") => return Self::ChildBudgetObservationRequired,
630            Some("SKC04") => return Self::IncompleteChildAccounting,
631            Some("SKC06") => return Self::RunNotRunnable,
632            Some("SKC07") => return Self::ChildJoinRejected,
633            Some("SKC08") => return Self::UnsupportedFailureCloseRuntime,
634            Some("SKC09") => return Self::RunFailureClosing,
635            _ => {}
636        }
637        Self::Database { operation, source }
638    }
639
640    pub(crate) const fn corrupt(record: &'static str) -> Self {
641        Self::CorruptData { record }
642    }
643
644    pub(crate) const fn encoding(record: &'static str) -> Self {
645        Self::Encoding { record }
646    }
647
648    /// Returns the stable, payload-free record category for an integrity error.
649    ///
650    /// Recovery code can map this value to a bounded quarantine component and
651    /// hash its separately retained evidence without exposing durable payloads.
652    #[must_use]
653    pub const fn corrupt_record(&self) -> Option<&'static str> {
654        match self {
655            Self::CorruptData { record } => Some(record),
656            _ => None,
657        }
658    }
659
660    /// Returns whether retrying the complete transaction with identical stable
661    /// identities is safe after this failure category.
662    #[must_use]
663    pub fn is_retryable(&self) -> bool {
664        match self {
665            Self::Database { source, .. } => retryable_database_error(source),
666            _ => false,
667        }
668    }
669}
670
671fn retryable_database_error(error: &sqlx_core::Error) -> bool {
672    match error {
673        sqlx_core::Error::Io(_)
674        | sqlx_core::Error::Tls(_)
675        | sqlx_core::Error::PoolTimedOut
676        | sqlx_core::Error::PoolClosed
677        | sqlx_core::Error::WorkerCrashed => true,
678        sqlx_core::Error::Database(database) => database.code().is_some_and(|code| {
679            matches!(
680                code.as_ref(),
681                "40001" | "40P01" | "55P03" | "57014" | "57P01" | "57P02" | "57P03"
682            )
683        }),
684        _ => false,
685    }
686}