aedb 0.2.7

Embedded Rust storage engine with transactional commits, WAL durability, and snapshot-consistent reads
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
use thiserror::Error;

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryIntegrityKind {
    ManifestWalSegmentMissing,
    ManifestWalSegmentMissingSizeMetadata,
    ManifestWalSegmentMissingChecksumMetadata,
    ManifestWalSegmentChecksumMismatch,
    ManifestWalSegmentTruncated,
    ManifestWalSegmentSizeMismatch,
    ManifestWalSegmentInvalidChecksumMetadata,
}

impl RecoveryIntegrityKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            RecoveryIntegrityKind::ManifestWalSegmentMissing => "manifest_wal_segment_missing",
            RecoveryIntegrityKind::ManifestWalSegmentMissingSizeMetadata => {
                "manifest_wal_segment_missing_size_metadata"
            }
            RecoveryIntegrityKind::ManifestWalSegmentMissingChecksumMetadata => {
                "manifest_wal_segment_missing_checksum_metadata"
            }
            RecoveryIntegrityKind::ManifestWalSegmentChecksumMismatch => {
                "manifest_wal_segment_checksum_mismatch"
            }
            RecoveryIntegrityKind::ManifestWalSegmentTruncated => "manifest_wal_segment_truncated",
            RecoveryIntegrityKind::ManifestWalSegmentSizeMismatch => {
                "manifest_wal_segment_size_mismatch"
            }
            RecoveryIntegrityKind::ManifestWalSegmentInvalidChecksumMetadata => {
                "manifest_wal_segment_invalid_checksum_metadata"
            }
        }
    }
}

impl std::fmt::Display for RecoveryIntegrityKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RecoveryIntegrityDiagnostic {
    pub kind: RecoveryIntegrityKind,
    pub segment_filename: String,
    pub manifest_path: std::path::PathBuf,
    pub wal_dir: std::path::PathBuf,
    pub recovery_mode: crate::config::RecoveryMode,
    pub durable_seq: u64,
    pub visible_seq: u64,
    pub active_segment_seq: u64,
    pub segment_seq: u64,
    pub latest_checkpoint_seq: Option<u64>,
    pub expected_size_bytes: Option<u64>,
    pub actual_size_bytes: Option<u64>,
    pub expected_sha256_hex: Option<String>,
    pub actual_sha256_hex: Option<String>,
}

impl RecoveryIntegrityDiagnostic {
    pub fn operator_message(&self) -> &'static str {
        match self.recovery_mode {
            crate::config::RecoveryMode::Strict => {
                "strict recovery stopped because the manifest and WAL files are inconsistent; local dev data may be corrupt, and persisted data requires restore/repair from a known-good backup"
            }
            crate::config::RecoveryMode::Permissive => {
                "permissive recovery skipped manifest-referenced WAL data; local dev data may be corrupt, and persisted data requires restore/repair from a known-good backup before relying on it"
            }
        }
    }
}

impl std::fmt::Display for RecoveryIntegrityDiagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: segment={} manifest={} wal_dir={} mode={:?} durable_seq={} visible_seq={} active_segment_seq={} segment_seq={}",
            self.kind,
            self.segment_filename,
            self.manifest_path.display(),
            self.wal_dir.display(),
            self.recovery_mode,
            self.durable_seq,
            self.visible_seq,
            self.active_segment_seq,
            self.segment_seq
        )?;
        if let Some(seq) = self.latest_checkpoint_seq {
            write!(f, " latest_checkpoint_seq={seq}")?;
        }
        if let Some(size) = self.expected_size_bytes {
            write!(f, " expected_size_bytes={size}")?;
        }
        if let Some(size) = self.actual_size_bytes {
            write!(f, " actual_size_bytes={size}")?;
        }
        if let Some(ref sha) = self.expected_sha256_hex {
            write!(f, " expected_sha256_hex={sha}")?;
        }
        if let Some(ref sha) = self.actual_sha256_hex {
            write!(f, " actual_sha256_hex={sha}")?;
        }
        write!(f, "; {}", self.operator_message())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceType {
    Project,
    Scope,
    Table,
    Index,
}

impl std::fmt::Display for ResourceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResourceType::Project => write!(f, "project"),
            ResourceType::Scope => write!(f, "scope"),
            ResourceType::Table => write!(f, "table"),
            ResourceType::Index => write!(f, "index"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AedbErrorCode {
    Io,
    Encode,
    Decode,
    Validation,
    InvalidConfig,
    IntegrityError,
    RecoveryIntegrity,
    Unavailable,
    CheckpointInProgress,
    ProjectAlreadyExists,
    ScopeAlreadyExists,
    TableAlreadyExists,
    IndexAlreadyExists,
    ProjectNotFound,
    ScopeNotFound,
    TableNotFound,
    IndexNotFound,
    DuplicatePrimaryKey,
    UniqueViolation,
    ForeignKeyViolation,
    CheckConstraintFailed,
    NotNullViolation,
    TypeMismatch,
    UnknownColumn,
    Conflict,
    Underflow,
    Overflow,
    QueueFull,
    PermissionDenied,
    Timeout,
    PartitionLockTimeout,
    EpochApplyTimeout,
    ParallelApplyCancelled,
    ParallelApplyWorkerPanicked,
    SnapshotExpired,
    AssertionFailed,
}

/// Broad caller-action class for [`AedbError`].
///
/// Match on [`AedbError::code`] for stable machine-readable detail, then use
/// this class to choose the caller response without parsing error text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AedbErrorClass {
    /// Transient capacity or timing failure. Retrying with backoff is expected.
    Retryable,
    /// Optimistic concurrency or assertion failure. Refresh the read state and
    /// retry only if the business operation is still valid.
    Conflict,
    /// Caller is not authenticated or lacks permission. Do not retry until the
    /// caller identity or grants change.
    Permission,
    /// Request shape, schema, type, arithmetic, or missing resource problem.
    /// Fix the request before retrying.
    Validation,
    /// Durability, recovery, decode, or integrity failure. Treat as operator
    /// action required before continuing writes.
    Integrity,
    /// Service or subsystem is not currently available. Retry after readiness
    /// or the competing operation changes.
    Unavailable,
}

impl AedbErrorCode {
    pub fn as_str(self) -> &'static str {
        match self {
            AedbErrorCode::Io => "io",
            AedbErrorCode::Encode => "encode",
            AedbErrorCode::Decode => "decode",
            AedbErrorCode::Validation => "validation",
            AedbErrorCode::InvalidConfig => "invalid_config",
            AedbErrorCode::IntegrityError => "integrity_error",
            AedbErrorCode::RecoveryIntegrity => "recovery_integrity",
            AedbErrorCode::Unavailable => "unavailable",
            AedbErrorCode::CheckpointInProgress => "checkpoint_in_progress",
            AedbErrorCode::ProjectAlreadyExists => "project_already_exists",
            AedbErrorCode::ScopeAlreadyExists => "scope_already_exists",
            AedbErrorCode::TableAlreadyExists => "table_already_exists",
            AedbErrorCode::IndexAlreadyExists => "index_already_exists",
            AedbErrorCode::ProjectNotFound => "project_not_found",
            AedbErrorCode::ScopeNotFound => "scope_not_found",
            AedbErrorCode::TableNotFound => "table_not_found",
            AedbErrorCode::IndexNotFound => "index_not_found",
            AedbErrorCode::DuplicatePrimaryKey => "duplicate_primary_key",
            AedbErrorCode::UniqueViolation => "unique_violation",
            AedbErrorCode::ForeignKeyViolation => "foreign_key_violation",
            AedbErrorCode::CheckConstraintFailed => "check_constraint_failed",
            AedbErrorCode::NotNullViolation => "not_null_violation",
            AedbErrorCode::TypeMismatch => "type_mismatch",
            AedbErrorCode::UnknownColumn => "unknown_column",
            AedbErrorCode::Conflict => "conflict",
            AedbErrorCode::Underflow => "underflow",
            AedbErrorCode::Overflow => "overflow",
            AedbErrorCode::QueueFull => "queue_full",
            AedbErrorCode::PermissionDenied => "permission_denied",
            AedbErrorCode::Timeout => "timeout",
            AedbErrorCode::PartitionLockTimeout => "partition_lock_timeout",
            AedbErrorCode::EpochApplyTimeout => "epoch_apply_timeout",
            AedbErrorCode::ParallelApplyCancelled => "parallel_apply_cancelled",
            AedbErrorCode::ParallelApplyWorkerPanicked => "parallel_apply_worker_panicked",
            AedbErrorCode::SnapshotExpired => "snapshot_expired",
            AedbErrorCode::AssertionFailed => "assertion_failed",
        }
    }

    pub fn class(self) -> AedbErrorClass {
        match self {
            AedbErrorCode::QueueFull
            | AedbErrorCode::Timeout
            | AedbErrorCode::PartitionLockTimeout
            | AedbErrorCode::EpochApplyTimeout
            | AedbErrorCode::ParallelApplyCancelled
            | AedbErrorCode::ParallelApplyWorkerPanicked
            | AedbErrorCode::SnapshotExpired => AedbErrorClass::Retryable,
            AedbErrorCode::Conflict | AedbErrorCode::AssertionFailed => AedbErrorClass::Conflict,
            AedbErrorCode::PermissionDenied => AedbErrorClass::Permission,
            AedbErrorCode::Io
            | AedbErrorCode::Encode
            | AedbErrorCode::Decode
            | AedbErrorCode::IntegrityError
            | AedbErrorCode::RecoveryIntegrity => AedbErrorClass::Integrity,
            AedbErrorCode::Unavailable | AedbErrorCode::CheckpointInProgress => {
                AedbErrorClass::Unavailable
            }
            AedbErrorCode::Validation
            | AedbErrorCode::InvalidConfig
            | AedbErrorCode::ProjectAlreadyExists
            | AedbErrorCode::ScopeAlreadyExists
            | AedbErrorCode::TableAlreadyExists
            | AedbErrorCode::IndexAlreadyExists
            | AedbErrorCode::ProjectNotFound
            | AedbErrorCode::ScopeNotFound
            | AedbErrorCode::TableNotFound
            | AedbErrorCode::IndexNotFound
            | AedbErrorCode::DuplicatePrimaryKey
            | AedbErrorCode::UniqueViolation
            | AedbErrorCode::ForeignKeyViolation
            | AedbErrorCode::CheckConstraintFailed
            | AedbErrorCode::NotNullViolation
            | AedbErrorCode::TypeMismatch
            | AedbErrorCode::UnknownColumn
            | AedbErrorCode::Underflow
            | AedbErrorCode::Overflow => AedbErrorClass::Validation,
        }
    }

    pub fn is_retryable(self) -> bool {
        matches!(self.class(), AedbErrorClass::Retryable)
    }
}

#[derive(Debug, Error)]
pub enum AedbError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("encode error: {0}")]
    Encode(String),
    #[error("decode error: {0}")]
    Decode(String),
    #[error("validation error: {0}")]
    Validation(String),
    #[error("invalid config: {message}")]
    InvalidConfig { message: String },
    #[error("integrity error: {message}")]
    IntegrityError { message: String },
    #[error("recovery integrity error: {diagnostic}")]
    RecoveryIntegrity {
        diagnostic: Box<RecoveryIntegrityDiagnostic>,
    },
    #[error("resource unavailable: {message}")]
    Unavailable { message: String },
    #[error("checkpoint in progress")]
    CheckpointInProgress,
    #[error("{resource_type} '{resource_id}' already exists")]
    AlreadyExists {
        resource_type: ResourceType,
        resource_id: String,
    },
    #[error("{resource_type} '{resource_id}' not found")]
    NotFound {
        resource_type: ResourceType,
        resource_id: String,
    },
    #[error("duplicate primary key in table '{table}': {key}")]
    DuplicatePK { table: String, key: String },
    #[error("unique constraint violation on index '{index}' in table '{table}'")]
    UniqueViolation {
        table: String,
        index: String,
        key: String,
    },
    #[error("foreign key violation: {fk_name} references {ref_table}({ref_key})")]
    ForeignKeyViolation {
        fk_name: String,
        table: String,
        ref_table: String,
        ref_key: String,
    },
    #[error("check constraint '{constraint}' failed on table '{table}'")]
    CheckConstraintFailed { table: String, constraint: String },
    #[error("NOT NULL violation: column '{column}' in table '{table}'")]
    NotNullViolation { table: String, column: String },
    #[error(
        "type mismatch: column '{column}' in table '{table}' expected {expected}, got {actual}"
    )]
    TypeMismatch {
        table: String,
        column: String,
        expected: String,
        actual: String,
    },
    #[error("unknown column '{column}' in table '{table}'")]
    UnknownColumn { table: String, column: String },
    #[error("conflict error: {0}")]
    Conflict(String),
    #[error("underflow")]
    Underflow,
    #[error("overflow")]
    Overflow,
    #[error("queue full")]
    QueueFull,
    #[error("permission denied: {0}")]
    PermissionDenied(String),
    #[error("timeout")]
    Timeout,
    #[error("partition lock timeout")]
    PartitionLockTimeout,
    #[error("epoch apply timeout exceeded")]
    EpochApplyTimeout,
    #[error("parallel apply cancelled")]
    ParallelApplyCancelled,
    #[error("parallel apply worker panicked")]
    ParallelApplyWorkerPanicked,
    #[error("snapshot expired")]
    SnapshotExpired,
    #[error("assertion failed at index {index}")]
    AssertionFailed {
        index: usize,
        assertion: Box<crate::commit::tx::ReadAssertion>,
        actual: Box<crate::commit::tx::AssertionActual>,
    },
}

impl AedbError {
    pub fn code(&self) -> AedbErrorCode {
        match self {
            AedbError::Io(_) => AedbErrorCode::Io,
            AedbError::Encode(_) => AedbErrorCode::Encode,
            AedbError::Decode(_) => AedbErrorCode::Decode,
            AedbError::Validation(_) => AedbErrorCode::Validation,
            AedbError::InvalidConfig { .. } => AedbErrorCode::InvalidConfig,
            AedbError::IntegrityError { .. } => AedbErrorCode::IntegrityError,
            AedbError::RecoveryIntegrity { .. } => AedbErrorCode::RecoveryIntegrity,
            AedbError::Unavailable { .. } => AedbErrorCode::Unavailable,
            AedbError::CheckpointInProgress => AedbErrorCode::CheckpointInProgress,
            AedbError::AlreadyExists { resource_type, .. } => match resource_type {
                ResourceType::Project => AedbErrorCode::ProjectAlreadyExists,
                ResourceType::Scope => AedbErrorCode::ScopeAlreadyExists,
                ResourceType::Table => AedbErrorCode::TableAlreadyExists,
                ResourceType::Index => AedbErrorCode::IndexAlreadyExists,
            },
            AedbError::NotFound { resource_type, .. } => match resource_type {
                ResourceType::Project => AedbErrorCode::ProjectNotFound,
                ResourceType::Scope => AedbErrorCode::ScopeNotFound,
                ResourceType::Table => AedbErrorCode::TableNotFound,
                ResourceType::Index => AedbErrorCode::IndexNotFound,
            },
            AedbError::DuplicatePK { .. } => AedbErrorCode::DuplicatePrimaryKey,
            AedbError::UniqueViolation { .. } => AedbErrorCode::UniqueViolation,
            AedbError::ForeignKeyViolation { .. } => AedbErrorCode::ForeignKeyViolation,
            AedbError::CheckConstraintFailed { .. } => AedbErrorCode::CheckConstraintFailed,
            AedbError::NotNullViolation { .. } => AedbErrorCode::NotNullViolation,
            AedbError::TypeMismatch { .. } => AedbErrorCode::TypeMismatch,
            AedbError::UnknownColumn { .. } => AedbErrorCode::UnknownColumn,
            AedbError::Conflict(_) => AedbErrorCode::Conflict,
            AedbError::Underflow => AedbErrorCode::Underflow,
            AedbError::Overflow => AedbErrorCode::Overflow,
            AedbError::QueueFull => AedbErrorCode::QueueFull,
            AedbError::PermissionDenied(_) => AedbErrorCode::PermissionDenied,
            AedbError::Timeout => AedbErrorCode::Timeout,
            AedbError::PartitionLockTimeout => AedbErrorCode::PartitionLockTimeout,
            AedbError::EpochApplyTimeout => AedbErrorCode::EpochApplyTimeout,
            AedbError::ParallelApplyCancelled => AedbErrorCode::ParallelApplyCancelled,
            AedbError::ParallelApplyWorkerPanicked => AedbErrorCode::ParallelApplyWorkerPanicked,
            AedbError::SnapshotExpired => AedbErrorCode::SnapshotExpired,
            AedbError::AssertionFailed { .. } => AedbErrorCode::AssertionFailed,
        }
    }

    pub fn code_str(&self) -> &'static str {
        self.code().as_str()
    }

    pub fn class(&self) -> AedbErrorClass {
        self.code().class()
    }

    pub fn is_retryable(&self) -> bool {
        self.code().is_retryable()
    }
}

#[cfg(test)]
mod tests {
    use super::{AedbError, AedbErrorClass, AedbErrorCode, ResourceType};

    #[test]
    fn error_code_strings_are_stable() {
        let expected = [
            (AedbErrorCode::Io, "io"),
            (AedbErrorCode::Encode, "encode"),
            (AedbErrorCode::Decode, "decode"),
            (AedbErrorCode::Validation, "validation"),
            (AedbErrorCode::InvalidConfig, "invalid_config"),
            (AedbErrorCode::IntegrityError, "integrity_error"),
            (AedbErrorCode::RecoveryIntegrity, "recovery_integrity"),
            (AedbErrorCode::Unavailable, "unavailable"),
            (
                AedbErrorCode::CheckpointInProgress,
                "checkpoint_in_progress",
            ),
            (
                AedbErrorCode::ProjectAlreadyExists,
                "project_already_exists",
            ),
            (AedbErrorCode::ScopeAlreadyExists, "scope_already_exists"),
            (AedbErrorCode::TableAlreadyExists, "table_already_exists"),
            (AedbErrorCode::IndexAlreadyExists, "index_already_exists"),
            (AedbErrorCode::ProjectNotFound, "project_not_found"),
            (AedbErrorCode::ScopeNotFound, "scope_not_found"),
            (AedbErrorCode::TableNotFound, "table_not_found"),
            (AedbErrorCode::IndexNotFound, "index_not_found"),
            (AedbErrorCode::DuplicatePrimaryKey, "duplicate_primary_key"),
            (AedbErrorCode::UniqueViolation, "unique_violation"),
            (AedbErrorCode::ForeignKeyViolation, "foreign_key_violation"),
            (
                AedbErrorCode::CheckConstraintFailed,
                "check_constraint_failed",
            ),
            (AedbErrorCode::NotNullViolation, "not_null_violation"),
            (AedbErrorCode::TypeMismatch, "type_mismatch"),
            (AedbErrorCode::UnknownColumn, "unknown_column"),
            (AedbErrorCode::Conflict, "conflict"),
            (AedbErrorCode::Underflow, "underflow"),
            (AedbErrorCode::Overflow, "overflow"),
            (AedbErrorCode::QueueFull, "queue_full"),
            (AedbErrorCode::PermissionDenied, "permission_denied"),
            (AedbErrorCode::Timeout, "timeout"),
            (
                AedbErrorCode::PartitionLockTimeout,
                "partition_lock_timeout",
            ),
            (AedbErrorCode::EpochApplyTimeout, "epoch_apply_timeout"),
            (
                AedbErrorCode::ParallelApplyCancelled,
                "parallel_apply_cancelled",
            ),
            (
                AedbErrorCode::ParallelApplyWorkerPanicked,
                "parallel_apply_worker_panicked",
            ),
            (AedbErrorCode::SnapshotExpired, "snapshot_expired"),
            (AedbErrorCode::AssertionFailed, "assertion_failed"),
        ];
        for (code, stable) in expected {
            assert_eq!(code.as_str(), stable);
        }
    }

    #[test]
    fn error_code_str_matches_variant_mapping() {
        let err = AedbError::NotFound {
            resource_type: ResourceType::Table,
            resource_id: "p.s.users".into(),
        };
        assert_eq!(err.code(), AedbErrorCode::TableNotFound);
        assert_eq!(err.code_str(), "table_not_found");
        assert_eq!(err.class(), AedbErrorClass::Validation);
    }

    #[test]
    fn error_code_classes_describe_caller_behavior() {
        assert_eq!(AedbErrorCode::QueueFull.class(), AedbErrorClass::Retryable);
        assert_eq!(
            AedbErrorCode::AssertionFailed.class(),
            AedbErrorClass::Conflict
        );
        assert_eq!(
            AedbErrorCode::PermissionDenied.class(),
            AedbErrorClass::Permission
        );
        assert_eq!(
            AedbErrorCode::IntegrityError.class(),
            AedbErrorClass::Integrity
        );
        assert_eq!(
            AedbErrorCode::Unavailable.class(),
            AedbErrorClass::Unavailable
        );
        assert!(AedbErrorCode::Timeout.is_retryable());
    }
}