stateknot-store-postgres 0.1.0-alpha.1

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

use thiserror::Error;

/// Invalid `PostgreSQL` provider configuration.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ConfigurationError {
    /// A required environment variable was absent.
    #[error("required PostgreSQL environment variable {name} is missing")]
    MissingEnvironmentVariable {
        /// Stable environment variable name; never a secret value.
        name: &'static str,
    },
    /// An environment variable was non-Unicode or used an unsupported value.
    #[error("PostgreSQL environment variable {name} is invalid")]
    InvalidEnvironmentVariable {
        /// Stable environment variable name; never a secret value.
        name: &'static str,
    },
    /// A required connection URL was empty.
    #[error("PostgreSQL connection URL must not be empty")]
    EmptyDatabaseUrl,
    /// Production auto-migration omitted a dedicated credential.
    #[error("production auto-migration requires STATEKNOT_MIGRATION_DATABASE_URL")]
    MigrationDatabaseUrlRequired,
    /// Production migration and runtime credentials were exactly the same URL.
    #[error("production migration and runtime PostgreSQL URLs must be distinct")]
    SharedProductionMigrationCredential,
    /// The connection URL could not be parsed. The URL is intentionally omitted.
    #[error("PostgreSQL connection URL is invalid")]
    InvalidDatabaseUrl,
    /// A pool with zero possible connections cannot make progress.
    #[error("PostgreSQL maximum connections must be positive")]
    ZeroMaximumConnections,
    /// Minimum pool size exceeded maximum pool size.
    #[error("PostgreSQL minimum connections must not exceed maximum connections")]
    PoolMinimumExceedsMaximum,
    /// A required timeout or lease duration was zero.
    #[error("{name} must be positive")]
    ZeroDuration {
        /// Stable configuration field name.
        name: &'static str,
    },
    /// A duration could not fit the signed microsecond database contract.
    #[error("{name} exceeds the signed microsecond storage range")]
    DurationTooLarge {
        /// Stable configuration field name.
        name: &'static str,
    },
    /// Lock timeout would not fire strictly before the statement timeout.
    #[error("lock timeout must be strictly less than statement timeout")]
    LockTimeoutNotBelowStatementTimeout,
    /// A server-side timeout exceeded `PostgreSQL`'s signed millisecond range.
    #[error("{name} exceeds PostgreSQL's signed millisecond timeout range")]
    PostgresTimeoutTooLarge {
        /// Stable configuration field name.
        name: &'static str,
    },
    /// Durable lease timing was not exactly representable as microseconds.
    #[error("{name} must be a positive whole number of microseconds")]
    LeaseTimingNotMicrosecondAligned {
        /// Stable configuration field name.
        name: &'static str,
    },
    /// Initial leases exceeded the configured renewal safety horizon.
    #[error("lease duration must not exceed the maximum lease horizon")]
    LeaseDurationExceedsMaximumHorizon,
    /// Fixed outbox attempt lease exceeded the core five-minute bound.
    #[error("outbox attempt lease must not exceed five minutes")]
    OutboxAttemptLeaseTooLong,
}

/// Durable `PostgreSQL` operation failure with payload-redacted diagnostics.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StoreError {
    /// The failure-close boundary lacks complete settled direct evidence or scope.
    #[error("invalid failure close boundary or evidence")]
    InvalidRunFailureClose,
    /// An immutable failure decision already owns this run's execution boundary.
    #[error("run is sealed for failure closure")]
    RunFailureClosing,
    /// An older writer cannot mutate a failure-closing run.
    #[error("compatible failure close runtime is required")]
    UnsupportedFailureCloseRuntime,
    /// Invalid tenant cursor or deadline cancellation audit construction.
    #[error("Agent deadline request or scan scope is invalid")]
    InvalidAgentDeadline,
    /// Missing, mismatched or unconsumed dedicated child Join evidence.
    #[error("child Join evidence is unavailable or conflicts with this result")]
    ChildJoinRejected,
    /// No durable parent cancellation witness owns this child key.
    #[error("child cancellation request was not found")]
    ChildCancellationNotFound,
    /// A pre-child binary attempted to mutate a child-enabled run.
    #[error("compatible child runtime is required")]
    UnsupportedChildRuntime,
    /// Terminal accounting omitted already recorded direct or delegated usage.
    #[error("terminal child accounting is incomplete")]
    IncompleteChildAccounting,
    /// Owned-child records, immutable input or scope do not match.
    #[error("child run commit conflicts with durable ownership")]
    ChildRunConflict,
    /// No ownership record exists inside the supplied parent/tenant boundary.
    #[error("child run ownership was not found")]
    ChildRunNotFound,
    /// A fresh child admission failed readiness, authority or budget validation.
    #[error("child run admission was rejected")]
    ChildRunRejected,
    /// An ancestor's finite depth or unsettled-descendant ceiling was reached.
    #[error("child run topology limit reached")]
    ChildRunTopologyExceeded,
    /// Outstanding child work blocks direct external dispatch or parent closure.
    #[error("unsettled children block this run mutation")]
    UnsettledChildRuns,
    /// Invocation start requires a fresh verified child-adjusted budget snapshot.
    #[error("child-adjusted invocation budget observation is required")]
    ChildBudgetObservationRequired,
    /// No complete, fully priced immutable terminal evidence is available yet.
    #[error("child run terminal settlement evidence is unavailable")]
    ChildRunSettlementUnavailable,
    /// Provider configuration was invalid.
    #[error(transparent)]
    Configuration(#[from] ConfigurationError),
    /// Connection or SQL execution failed.
    #[error("PostgreSQL {operation} failed")]
    Database {
        /// Stable operation category without SQL or bound values.
        operation: &'static str,
        /// Underlying driver error.
        #[source]
        source: sqlx_core::Error,
    },
    /// Ordered schema migration failed.
    #[error("PostgreSQL schema migration failed")]
    Migration {
        /// Underlying migration error.
        #[source]
        source: sqlx_core::migrate::MigrateError,
    },
    /// The connected server is outside the qualified major versions.
    #[error("PostgreSQL server major version is unsupported")]
    UnsupportedServerVersion,
    /// Required migration metadata has not been installed.
    #[error("StateKnot PostgreSQL schema has not been migrated")]
    SchemaNotMigrated,
    /// Applied migration versions or checksums do not match this binary.
    #[error("StateKnot PostgreSQL schema is incompatible with this binary")]
    IncompatibleSchema,
    /// Migration metadata exists but required schema objects are missing.
    #[error("StateKnot PostgreSQL schema objects are incomplete")]
    IncompleteSchema,
    /// Private artifact object coordinates violated the portable storage contract.
    #[error("artifact storage locator is invalid")]
    InvalidArtifactStorageLocator,
    /// No immutable artifact exists inside the supplied tenant boundary.
    #[error("artifact was not found in the tenant registry")]
    ArtifactNotFound,
    /// An artifact identity, idempotency key, or object locator already owns another record.
    #[error("artifact registration conflicts with durable registry evidence")]
    ArtifactRegistrationConflict,
    /// A direct artifact parent does not already exist in the same tenant.
    #[error("artifact parent was not found in the tenant registry")]
    ArtifactParentNotFound,
    /// The artifact's causing run event does not exist in the same tenant.
    #[error("artifact provenance event was not found in the tenant journal")]
    ArtifactProvenanceNotFound,
    /// No exact compiled graph exists inside the supplied tenant registry.
    #[error("compiled graph definition was not found in the tenant registry")]
    GraphDefinitionNotFound,
    /// A graph version was already registered with different immutable bytes.
    #[error("compiled graph identity already exists with a different definition")]
    GraphDefinitionConflict,
    /// A fairness policy was empty, oversized, or had an invalid cycle length.
    #[error("scheduler fairness policy registration is invalid")]
    InvalidSchedulerFairnessPolicy,
    /// Reservation retention duration or batch bounds are unsafe.
    #[error("scheduler fairness reservation retention policy is invalid")]
    InvalidSchedulerFairnessRetention,
    /// A scheduler shard identity already owns another immutable policy.
    #[error("scheduler fairness shard already exists with a different policy")]
    SchedulerFairnessPolicyConflict,
    /// No immutable fairness policy exists for the supplied scheduler shard.
    #[error("scheduler fairness policy was not found")]
    SchedulerFairnessPolicyNotFound,
    /// A reservation retry named another shard or policy snapshot.
    #[error("scheduler fairness reservation identity conflicts with durable evidence")]
    SchedulerFairnessReservationConflict,
    /// The durable fairness reservation sequence reached its supported ceiling.
    #[error("scheduler fairness reservation sequence is exhausted")]
    SchedulerFairnessSequenceExhausted,
    /// No run exists inside the supplied tenant boundary.
    #[error("run was not found in the tenant boundary")]
    RunNotFound,
    /// Run admission reused an identity with different provenance.
    #[error("run identity already exists with different admission provenance")]
    RunConflict,
    /// No immutable Agent admission snapshot exists for this tenant-scoped run.
    #[error("agent admission was not found in the tenant-scoped run")]
    AgentAdmissionNotFound,
    /// The supplied event, checkpoint, graph, or scope cannot form an atomic admission.
    #[error("agent admission commit input is invalid")]
    InvalidAgentAdmissionCommit,
    /// Database-time budget evaluation rejected a new Agent admission.
    #[error("agent admission was rejected at its durable commit observation")]
    AgentAdmissionRejected,
    /// The exact pinned state-schema validator was unavailable or panicked.
    #[error("agent admission state-schema dependency is unavailable")]
    AgentAdmissionSchemaUnavailable,
    /// Initial graph state did not satisfy the exact pinned state schema.
    #[error("agent admission initial state was rejected by its pinned schema")]
    AgentAdmissionStateRejected,
    /// The run identity or one stable anchor belongs to another admission intent.
    #[error("agent admission identity conflicts with durable evidence")]
    AgentAdmissionConflict,
    /// No durable ingress idempotency mapping exists for this tenant/key.
    #[error("agent submission key was not found in the tenant boundary")]
    AgentSubmissionNotFound,
    /// One ingress key was reused for a different immutable submission.
    #[error("agent submission key conflicts with durable submission evidence")]
    AgentSubmissionConflict,
    /// The run is quarantined and cannot execute or mutate normally.
    #[error("run is quarantined")]
    RunQuarantined,
    /// A quarantine component code violated its bounded machine grammar.
    #[error("run quarantine component code is invalid")]
    InvalidRunQuarantineComponent,
    /// A quarantine request crossed its tenant/run journal observation.
    #[error("run quarantine request is invalid")]
    InvalidRunQuarantineRequest,
    /// No audit-grade quarantine observation exists for the supplied run.
    #[error("run quarantine evidence was not found in the tenant-scoped run")]
    RunQuarantineNotFound,
    /// A stable quarantine identity was reused for another immutable intent.
    #[error("run quarantine identity conflicts with durable evidence")]
    RunQuarantineIdConflict,
    /// Another immutable quarantine observation already owns the run.
    #[error("run already has different durable quarantine evidence")]
    RunQuarantineConflict,
    /// The run journal changed after the evidence observation was constructed.
    #[error("run quarantine journal observation is stale")]
    StaleRunQuarantineObservation,
    /// A claimed recovery session crossed its fence, tenant, or run boundary.
    #[error("claimed run recovery context is invalid")]
    InvalidClaimedRunRecoveryContext,
    /// Durable journal progress invalidated the claimed recovery observation.
    #[error("claimed run recovery journal observation is stale")]
    StaleClaimedRunRecoveryObservation,
    /// Ready-node recovery was requested before an initial checkpoint exists.
    #[error("ready-node recovery requires a current graph checkpoint")]
    ReadyNodeRecoveryCheckpointMissing,
    /// Replay could not run because the exact local schema or reducer was not available.
    #[error("noninitial graph replay dependency is unavailable on this worker")]
    GraphReplayDependencyUnavailable,
    /// Replay result material exceeded the explicitly configured memory bound.
    #[error("noninitial graph replay exceeds its configured barrier byte limit")]
    GraphReplayResourceLimit,
    /// A recovery plan, journal append, fence, or node selection crossed scope.
    #[error("ready-node dispatch plan is invalid for the requested durable start")]
    InvalidReadyNodeDispatchPlan,
    /// The selected recovery-plan node does not authorize a new physical start.
    #[error("ready-node recovery decision is not dispatchable")]
    ReadyNodeNotDispatchable,
    /// A recovery plan contains immediate, in-flight, or terminal work and
    /// therefore cannot be projected as one delayed retry wakeup.
    #[error("ready-node recovery plan cannot schedule a delayed retry wakeup")]
    InvalidDelayedRetryPlan,
    /// Immutable quarantine evidence and the mutable run projection disagree.
    #[error("run quarantine evidence conflicts with its durable projection")]
    RunQuarantineCommitConflict,
    /// The run lifecycle is not currently runnable.
    #[error("run lifecycle is not runnable")]
    RunNotRunnable,
    /// A durable scheduler gate has not reached its inclusive database time.
    #[error("run is not yet available for a scheduler claim")]
    RunNotYetAvailable,
    /// A caller reached the wrong trusted append entry point.
    #[error("journal append source is not authorized by this entry point")]
    WrongAppendAuthority,
    /// A stable event ID was reused for a different immutable intent.
    #[error("journal event identity conflicts with a committed intent")]
    EventIdConflict,
    /// A retry reused an event ID with a different or unverifiable projection intent.
    #[error("journal event projection conflicts with the committed projection intent")]
    ProjectionIntentConflict,
    /// The supplied complete journal head did not match the locked run row.
    #[error("journal expectation does not match the current durable head")]
    StaleJournalHead,
    /// No checkpoint exists for the supplied tenant/run/checkpoint identity.
    #[error("checkpoint was not found in the tenant-scoped run")]
    CheckpointNotFound,
    /// A stable checkpoint ID was reused for a different immutable write intent.
    #[error("checkpoint identity conflicts with a committed write intent")]
    CheckpointIdConflict,
    /// Event and checkpoint idempotency records do not describe one atomic commit.
    #[error("journal event and checkpoint identities conflict with an atomic commit")]
    CheckpointCommitConflict,
    /// A wait batch was empty, oversized, duplicated, or crossed scope/event identity.
    #[error("durable wait registration batch is invalid")]
    InvalidWaitRegistrationBatch,
    /// Wait event, checkpoint, lifecycle markers, and registration rows disagree.
    #[error("durable wait registration conflicts with the atomic commit")]
    WaitRegistrationCommitConflict,
    /// No durable wait registration exists under the supplied tenant/run/identity.
    #[error("durable wait registration was not found in the tenant-scoped run")]
    WaitRegistrationNotFound,
    /// A wait identity was loaded through the wrong interrupt/timer API.
    #[error("durable wait registration kind does not match the requested API")]
    WaitRegistrationKindMismatch,
    /// Resolution intent did not match an outstanding durable interrupt.
    #[error("interrupt resolution is invalid for the locked durable request")]
    InvalidInterruptResolution,
    /// Resolution event, immutable detail, and mutable wait projection disagree.
    #[error("interrupt resolution conflicts with the atomic commit")]
    InterruptResolutionCommitConflict,
    /// Timer firing intent did not match an outstanding due durable timer.
    #[error("timer firing is invalid for the locked durable timer")]
    InvalidTimerFiring,
    /// Firing event, immutable detail, and mutable wait projection disagree.
    #[error("timer firing conflicts with the atomic commit")]
    TimerFiringCommitConflict,
    /// A wait-discovery page size was zero or exceeded the decoded-memory bound.
    #[error("wait discovery page size is invalid")]
    InvalidWaitDiscoveryPageSize,
    /// A due-timer page cursor crossed tenant/cutoff/order scope.
    #[error("due timer page cursor is invalid")]
    InvalidDueTimerCursor,
    /// An expired-interrupt page cursor crossed tenant/cutoff/order scope.
    #[error("expired interrupt page cursor is invalid")]
    InvalidExpiredInterruptCursor,
    /// The supplied run-level edge was not cancellation/failure from waiting.
    #[error("wait abandonment transition is invalid")]
    InvalidWaitAbandonment,
    /// Abandonment event, detail set, and mutable wait projections disagree.
    #[error("wait abandonment conflicts with the atomic commit")]
    WaitAbandonmentCommitConflict,
    /// The requested wait has no immutable abandonment audit fact.
    #[error("wait abandonment was not found in the tenant-scoped run")]
    WaitAbandonmentNotFound,
    /// Resolution/firing history was requested for a wait abandoned by the run.
    #[error("durable wait was abandoned without resolution or firing")]
    WaitWasAbandoned,
    /// A successor checkpoint must prove the complete result barrier it consumes.
    #[error("successor checkpoint commit requires a complete checkpoint barrier")]
    CheckpointBarrierRequired,
    /// The supplied barrier did not match its fully restored durable base.
    #[error("checkpoint barrier does not match its durable base checkpoint")]
    InvalidCheckpointBarrier,
    /// At least one result required by the complete barrier is not durable.
    #[error("checkpoint barrier is incomplete")]
    CheckpointBarrierIncomplete,
    /// Durable pending-result identities do not equal the supplied complete barrier.
    #[error("checkpoint barrier result set conflicts with durable pending results")]
    CheckpointBarrierResultConflict,
    /// Barrier event, checkpoint, and consumption rows do not describe one atomic commit.
    #[error("checkpoint barrier identities conflict with an atomic commit")]
    CheckpointBarrierCommitConflict,
    /// The supplied complete checkpoint parent did not match the locked run row.
    #[error("checkpoint parent does not match the current durable checkpoint")]
    StaleCheckpointHead,
    /// A tool invocation on the current checkpoint has not committed a result.
    #[error("checkpoint advancement is blocked by an unsettled tool invocation")]
    CheckpointBlockedByToolInvocation,
    /// No logical tool invocation exists in the supplied tenant/run boundary.
    #[error("tool invocation was not found in the tenant-scoped run")]
    ToolInvocationNotFound,
    /// Receipt provenance or descriptor/input binding crossed its durable boundary.
    #[error("Tool authorization receipt is invalid for the durable invocation boundary")]
    InvalidToolAuthorizationReceipt,
    /// No exact receipt or referenced durable invocation boundary exists.
    #[error("Tool authorization receipt was not found in the tenant boundary")]
    ToolAuthorizationReceiptNotFound,
    /// A receipt identity was reused with different immutable canonical bytes.
    #[error("Tool authorization receipt identity conflicts with durable evidence")]
    ToolAuthorizationReceiptConflict,
    /// A receipt audit page size was zero or exceeded its decoded-memory bound.
    #[error("Tool authorization receipt page size is invalid")]
    InvalidToolAuthorizationReceiptPageSize,
    /// A receipt audit cursor crossed scope or did not match immutable storage.
    #[error("Tool authorization receipt cursor is invalid")]
    InvalidToolAuthorizationReceiptCursor,
    /// Skill activation approval or acting-window evidence crossed its durable scope.
    #[error("Skill activation evidence is invalid for the durable run boundary")]
    InvalidSkillActivation,
    /// No exact Skill acting window exists in the tenant boundary.
    #[error("Skill acting window was not found in the tenant boundary")]
    SkillActingWindowNotFound,
    /// A Skill approval or window identity was reused with different evidence.
    #[error("Skill activation identity conflicts with durable evidence")]
    SkillActivationConflict,
    /// The exact acting window expired or has an immutable revocation.
    #[error("Skill acting window is inactive")]
    SkillActingWindowInactive,
    /// A stable invocation ID was reused with a different immutable intent.
    #[error("tool invocation identity conflicts with a committed intent")]
    ToolInvocationIdConflict,
    /// Event and invocation records do not describe one atomic commit.
    #[error("journal event and tool invocation identities conflict with an atomic commit")]
    ToolInvocationCommitConflict,
    /// The supplied complete invocation head did not match its durable current row.
    #[error("tool invocation head is stale")]
    StaleToolInvocationHead,
    /// The requested invocation state transition was invalid for durable state.
    #[error("tool invocation transition is invalid for the locked record")]
    InvalidToolInvocationTransition,
    /// The invocation activation is not a ready root-graph node of its checkpoint.
    #[error("tool invocation activation is not ready in the base checkpoint")]
    InvalidToolInvocationActivation,
    /// A model invocation on the current checkpoint has not committed a response.
    #[error("checkpoint advancement is blocked by an unsettled model invocation")]
    CheckpointBlockedByModelInvocation,
    /// No logical model invocation exists in the supplied tenant/run boundary.
    #[error("model invocation was not found in the tenant-scoped run")]
    ModelInvocationNotFound,
    /// A stable model invocation ID was reused with a different immutable intent.
    #[error("model invocation identity conflicts with a committed intent")]
    ModelInvocationIdConflict,
    /// Event and model invocation records do not describe one atomic commit.
    #[error("journal event and model invocation identities conflict with an atomic commit")]
    ModelInvocationCommitConflict,
    /// The supplied complete model invocation head did not match its durable current row.
    #[error("model invocation head is stale")]
    StaleModelInvocationHead,
    /// The requested model invocation transition was invalid for durable state.
    #[error("model invocation transition is invalid for the locked record")]
    InvalidModelInvocationTransition,
    /// The model invocation activation is not a ready root-graph node of its checkpoint.
    #[error("model invocation activation is not ready in the base checkpoint")]
    InvalidModelInvocationActivation,
    /// No pending result exists for the supplied logical node activation key.
    #[error("pending node result was not found in the tenant-scoped run")]
    PendingNodeResultNotFound,
    /// A logical activation already has a different immutable semantic result.
    #[error("pending node result conflicts with the committed semantic intent")]
    PendingNodeResultConflict,
    /// Event and pending-result rows do not describe one atomic commit.
    #[error("journal event and pending node result conflict with an atomic commit")]
    PendingNodeResultCommitConflict,
    /// The pending result activation is not a ready root-graph node of its checkpoint.
    #[error("pending node result activation is not ready in the base checkpoint")]
    InvalidPendingNodeResultActivation,
    /// New pending results must be committed through a durable physical node attempt.
    #[error("pending node result commit requires a durable node attempt")]
    NodeAttemptRequired,
    /// The result's temporal or control invariants cannot commit at the database observation.
    #[error("pending node result is invalid at its durable commit position")]
    InvalidPendingNodeResult,
    /// A pending result named an absent, non-committed, or crossed invocation revision.
    #[error("pending node result contains an invalid external invocation binding")]
    InvalidPendingNodeResultBinding,
    /// A pending-result page size exceeded its decoded-memory safety bound.
    #[error("pending node result page size is invalid")]
    InvalidPendingNodeResultPageSize,
    /// A pending-result page cursor crossed scope or did not match its durable row.
    #[error("pending node result cursor is invalid")]
    InvalidPendingNodeResultCursor,
    /// No physical node attempt exists in the supplied tenant/run boundary.
    #[error("node attempt was not found in the tenant-scoped run")]
    NodeAttemptNotFound,
    /// A stable physical attempt identity was reused for another owner.
    #[error("node attempt identity conflicts with a committed owner")]
    NodeAttemptIdConflict,
    /// Event and node-attempt rows do not describe one atomic commit.
    #[error("journal event and node attempt conflict with an atomic commit")]
    NodeAttemptCommitConflict,
    /// The attempt activation is not a ready root-graph node of its checkpoint.
    #[error("node attempt activation is not ready in the base checkpoint")]
    InvalidNodeAttemptActivation,
    /// The requested physical-attempt transition is invalid for durable history.
    #[error("node attempt transition is invalid for the locked history")]
    InvalidNodeAttemptTransition,
    /// One logical activation reached the hard physical-attempt ceiling.
    #[error("node attempt history reached its hard physical-attempt limit")]
    NodeAttemptLimitExceeded,
    /// The supplied exact start does not match the durable physical attempt.
    #[error("node attempt start is stale")]
    StaleNodeAttemptStart,
    /// A node-attempt history cursor did not identify the exact stored attempt.
    #[error("node attempt history cursor does not match a durable attempt")]
    InvalidNodeAttemptCursor,
    /// A node-attempt history page size exceeded its decoded-memory safety bound.
    #[error("node attempt history page size is invalid")]
    InvalidNodeAttemptPageSize,
    /// A runnable-run page size exceeded its decoded-memory safety bound.
    #[error("runnable run page size is invalid")]
    InvalidRunnableRunPageSize,
    /// A runnable-run cursor crossed tenant scope or contained an invalid key.
    #[error("runnable run cursor is invalid")]
    InvalidRunnableRunCursor,
    /// An outbox enqueue batch was empty, duplicated, or exceeded its hard bound.
    #[error("outbox enqueue batch is invalid")]
    InvalidOutboxBatch,
    /// Destination snapshot digest did not match its canonical configuration.
    #[error("outbox destination snapshot does not match its canonical configuration")]
    OutboxDestinationSnapshotMismatch,
    /// No immutable destination snapshot exists in the tenant boundary.
    #[error("outbox destination snapshot was not found in the tenant boundary")]
    OutboxDestinationNotFound,
    /// A destination snapshot identity conflicts with durable configuration.
    #[error("outbox destination snapshot conflicts with durable configuration")]
    OutboxDestinationConflict,
    /// No outbox delivery exists in the supplied tenant/run boundary.
    #[error("outbox delivery was not found in the tenant-scoped run")]
    OutboxDeliveryNotFound,
    /// A stable delivery identity conflicts with a committed immutable intent.
    #[error("outbox delivery identity conflicts with a committed intent")]
    OutboxDeliveryIdConflict,
    /// Journal event and complete outbox set do not describe one atomic commit.
    #[error("journal event and outbox deliveries conflict with an atomic commit")]
    OutboxEnqueueConflict,
    /// A physical outbox attempt identity was already claimed by another owner.
    #[error("outbox attempt identity conflicts with a committed owner")]
    OutboxAttemptIdConflict,
    /// The supplied delivery fence is not the exact current attempt.
    #[error("outbox delivery fencing token is stale")]
    StaleOutboxFence,
    /// The current outbox attempt reached its exclusive database expiry.
    #[error("outbox attempt lease has expired")]
    OutboxAttemptExpired,
    /// A delivery attempt has no durable start in the tenant-scoped run.
    #[error("outbox attempt was not found in the tenant-scoped run")]
    OutboxAttemptNotFound,
    /// A completion conflicts with an already committed terminal attempt.
    #[error("outbox attempt completion conflicts with durable evidence")]
    OutboxCompletionConflict,
    /// The requested outbox state transition is invalid for durable history.
    #[error("outbox attempt transition is invalid for the locked history")]
    InvalidOutboxTransition,
    /// An outbox history cursor did not identify the exact stored attempt.
    #[error("outbox attempt history cursor does not match a durable attempt")]
    InvalidOutboxAttemptCursor,
    /// An outbox-attempt page size exceeded its decoded-memory safety bound.
    #[error("outbox attempt history page size is invalid")]
    InvalidOutboxAttemptPageSize,
    /// The run journal advanced after an earlier pending-result page snapshot.
    #[error("pending node result page snapshot is stale and must be restarted")]
    StalePendingNodeResultSnapshot,
    /// A pagination cursor did not identify the exact stored event head.
    #[error("journal cursor does not match a durable event")]
    InvalidJournalCursor,
    /// A reverse-lineage cursor did not identify the exact stored checkpoint head.
    #[error("checkpoint lineage cursor does not match a durable checkpoint")]
    InvalidCheckpointCursor,
    /// An invocation-history cursor did not identify the exact stored revision.
    #[error("tool invocation history cursor does not match a durable revision")]
    InvalidToolInvocationCursor,
    /// A model-invocation history cursor did not identify the exact stored revision.
    #[error("model invocation history cursor does not match a durable revision")]
    InvalidModelInvocationCursor,
    /// No higher signed `PostgreSQL` journal sequence exists.
    #[error("journal sequence is exhausted")]
    JournalSequenceExhausted,
    /// The expected lifecycle revision did not match the locked run row.
    #[error("lifecycle projection revision is stale")]
    StaleLifecycleRevision,
    /// The requested lifecycle transition was not a valid direct successor.
    #[error("lifecycle transition is invalid for the locked run state")]
    InvalidLifecycleTransition,
    /// A durable-wait edge was attempted through a journal-only mutation path.
    #[error("durable wait lifecycle changes require the atomic wait persistence API")]
    DurableWaitMutationRequired,
    /// A lifecycle observation claimed to occur after the journal commit clock.
    #[error("lifecycle transition observation is later than the journal commit observation")]
    LifecycleObservationAfterCommit,
    /// Another unexpired worker lease currently owns the run.
    #[error("run already has an unexpired worker lease")]
    LeaseHeld,
    /// No active lease can satisfy the requested mutation.
    #[error("run has no active worker lease")]
    NoActiveLease,
    /// Attempt or fencing epoch did not match the current lease.
    #[error("worker fencing token is stale")]
    StaleFence,
    /// The exact lease reached its exclusive database expiry.
    #[error("worker lease has expired")]
    LeaseExpired,
    /// The database wall clock moved before a durable lease observation.
    #[error("database clock precedes a durable lease observation")]
    DatabaseClockRegression,
    /// Renewal did not strictly extend the current expiry.
    #[error("worker lease renewal must strictly extend the current expiry")]
    LeaseExpiryNotExtended,
    /// Renewal requested an expiry beyond the configured safety horizon.
    #[error("worker lease renewal exceeds the configured maximum horizon")]
    LeaseHorizonExceeded,
    /// No higher signed `PostgreSQL` fencing epoch exists.
    #[error("worker fencing epoch is exhausted")]
    FencingEpochExhausted,
    /// A requested journal page exceeded the hard bound.
    #[error("journal page size is invalid")]
    InvalidPageSize,
    /// A requested checkpoint-lineage page exceeded its memory-safety bound.
    #[error("checkpoint lineage page size is invalid")]
    InvalidCheckpointPageSize,
    /// A graph replay memory limit was zero or exceeded its implementation bound.
    #[error("noninitial graph replay limits are invalid")]
    InvalidGraphReplayLimits,
    /// A requested invocation-history page exceeded its memory-safety bound.
    #[error("tool invocation history page size is invalid")]
    InvalidToolInvocationPageSize,
    /// A requested model-invocation history page exceeded its memory-safety bound.
    #[error("model invocation history page size is invalid")]
    InvalidModelInvocationPageSize,
    /// Trusted in-process domain data could not be serialized canonically.
    #[error("{record} could not be encoded for durable storage")]
    Encoding {
        /// Stable record category without user data.
        record: &'static str,
    },
    /// Durable bytes or redundant columns failed closed validation.
    #[error("durable {record} failed integrity validation")]
    CorruptData {
        /// Stable record category without payload or identifiers.
        record: &'static str,
    },
}

impl StoreError {
    pub(crate) fn database(operation: &'static str, source: sqlx_core::Error) -> Self {
        match source
            .as_database_error()
            .and_then(sqlx_core::error::DatabaseError::code)
            .as_deref()
        {
            Some("SKC01") => return Self::UnsupportedChildRuntime,
            Some("SKC02") => return Self::UnsettledChildRuns,
            Some("SKC03") => return Self::ChildBudgetObservationRequired,
            Some("SKC04") => return Self::IncompleteChildAccounting,
            Some("SKC06") => return Self::RunNotRunnable,
            Some("SKC07") => return Self::ChildJoinRejected,
            Some("SKC08") => return Self::UnsupportedFailureCloseRuntime,
            Some("SKC09") => return Self::RunFailureClosing,
            _ => {}
        }
        Self::Database { operation, source }
    }

    pub(crate) const fn corrupt(record: &'static str) -> Self {
        Self::CorruptData { record }
    }

    pub(crate) const fn encoding(record: &'static str) -> Self {
        Self::Encoding { record }
    }

    /// Returns the stable, payload-free record category for an integrity error.
    ///
    /// Recovery code can map this value to a bounded quarantine component and
    /// hash its separately retained evidence without exposing durable payloads.
    #[must_use]
    pub const fn corrupt_record(&self) -> Option<&'static str> {
        match self {
            Self::CorruptData { record } => Some(record),
            _ => None,
        }
    }

    /// Returns whether retrying the complete transaction with identical stable
    /// identities is safe after this failure category.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Database { source, .. } => retryable_database_error(source),
            _ => false,
        }
    }
}

fn retryable_database_error(error: &sqlx_core::Error) -> bool {
    match error {
        sqlx_core::Error::Io(_)
        | sqlx_core::Error::Tls(_)
        | sqlx_core::Error::PoolTimedOut
        | sqlx_core::Error::PoolClosed
        | sqlx_core::Error::WorkerCrashed => true,
        sqlx_core::Error::Database(database) => database.code().is_some_and(|code| {
            matches!(
                code.as_ref(),
                "40001" | "40P01" | "55P03" | "57014" | "57P01" | "57P02" | "57P03"
            )
        }),
        _ => false,
    }
}