Crash recovery

There is no separate recovery mode. Every StorageEngine::open runs the same sequence: load the manifest, repair what an interrupted compaction or flush left in data_dir, open the SSTables, replay the WAL segments that hold data no SSTable has, flush what was replayed, and only then start the background threads (source: src/storage/mod.rs, StorageEngine::open). A clean shutdown and a kill -9 differ only in how much work that sequence finds.

The WAL format, commit markers and sync modes are on Write-ahead log; the manifest log is on Manifest.

Open sequence

flowchart TD K["load at-rest keys, install cipher and keyring"] --> D["create data_dir and wal_dir"] D --> L["take LOCK (flock / LockFileEx)"] L --> KC["verify ENCRYPTION key check"] KC --> M["Manifest::load: snapshot + replay MANIFEST.log, truncate torn tail"] M --> R["reconcile_delete_files"] R --> P["purge_orphan_sstables"] P --> S["load_sstables: open a reader per manifest file"] S --> H["sequence high water from SSTable footers"] H --> FN["advance_file_number_to(max sst id + 1)"] FN --> W["list wal-N.log segments, sort numerically, mark skippable ones"] W --> RP["replay each kept segment, flush as the memtable fills"] RP --> FL["flush the replayed tail to L0"] FL --> NW["open wal-SEQ.log for new writes"] NW --> RC["read WAL_BACKUP_HOLD, reclaim WAL"] RC --> BG["start compaction workers, set recovery_complete, start flush and fsync threads"] BG --> CS["schedule a compaction check"]
(source: src/storage/mod.rs, StorageEngine::open)
Step Failure behaviour
Key load and key check A wrong or missing key stops the open before any file is read (see Encryption at rest internals)
LOCK A second engine on the same directory is refused with LockNotAvailable
Manifest::load Wrong magic, unknown version, or a bad record with data after it: Error::Corruption, open fails. A torn last record is dropped and the log truncated
reconcile_delete_files Failure to restore a manifest-listed .delete file is fatal
load_sstables A manifest-listed file that cannot be opened fails the open
WAL segment read A key error fails the open; any other open or read error skips that segment with a warning (see below)
Recovery flush An error fails the open

(source: src/storage/mod.rs, StorageEngine::open, acquire_data_dir_lock; src/storage/manifest.rs, Manifest::load, replay_log; src/storage/compaction.rs, reconcile_delete_files)

Repairing the data directory

reconcile_delete_files and purge_orphan_sstables run after the manifest is loaded and before any SSTable is opened or the file-number scan runs:

Found on disk Manifest lists the base name Action Why it can exist
sst-X.sst.delete Yes Rename back to sst-X.sst (if sst-X.sst also exists, the .delete copy is removed) Crash after a compaction renamed its inputs, before its manifest record
sst-X.sst.delete No Delete Crash after the manifest record, before the unlink
sst-X.sst No Delete Flush or compaction output whose manifest record was lost, or a leftover from copying a directory

(source: src/storage/compaction.rs, reconcile_delete_files, purge_orphan_sstables)

The doc comment on purge_orphan_sstables gives the invariant that makes deleting an unlisted SSTable safe: a flush records its SSTable in the manifest before the WAL watermark passes it, and a compaction records its output before deleting its inputs, so an unlisted file is never the only copy of anything. Tested by manifest_referenced_delete_files_are_reconciled_on_open (src/storage/mod.rs, crash_reopen_durability_tests), reconcile_delete_files_restores_referenced_and_removes_unreferenced and purge_orphan_sstables_removes_only_unlisted_ssts (src/storage/compaction.rs, tests).

Sequence high water

The engine starts from the manifest's stored sequence, then for every opened SSTable reads max_sequence() (from the footer, or by scanning blocks outside the block cache for files written before the footer field existed) and raises the next sequence above it. sst_high_water is the highest sequence any SSTable holds, or None with no SSTables; WAL replay raises the next sequence above every replayed entry too (source: src/storage/mod.rs, StorageEngine::open, replay_committed_run; src/storage/sst.rs, max_sequence). This makes recovery independent of whether sync() ran before the stop. Tested by restart_without_sync_loses_writes_after_wal_drop and test_storage_engine_recovery_sequence_continuity (src/storage/property_oracle_tests.rs; tests/crash_recovery_test.rs).

WAL replay

Which segments are read

Segments named wal-<seq>.log are sorted by the number in the name, not by the string, and a legacy current.wal is replayed first. The comment notes that a name sort put wal-104.log after wal-10015395.log (source: src/storage/mod.rs, StorageEngine::open).

Segment i is skipped without being opened when all of these hold:

  • every segment name carries a sequence and there is no current.wal;
  • some SSTable exists (sst_high_water is Some(high));
  • segment i is not the last one, and the next segment's start sequence next is above 0;
  • high >= next - 1.

The reasoning, from the code: segment i holds exactly the sequences [start(i), start(i+1)), every entry of it was inserted into a memtable older than the rotation that opened segment i+1, and memtables flush oldest first, so once an SSTable holds sequence next - 1 everything in segment i is in SSTables. A directory with any unnumbered segment replays everything (source: src/storage/mod.rs, StorageEngine::open). The same rule decides WAL reclamation (see WAL). Tested by reopen_skips_fully_flushed_segments (src/storage/mod.rs, wal_replay_bounded_tests), which uses names that cross a digit-length boundary.

Before replay the engine logs a warning for any segment larger than max(4 x memtable_size, 256 MiB), and for a WAL directory over twice wal_retention_bytes, pointing at WAL_BACKUP_HOLD (source: src/storage/mod.rs, StorageEngine::open).

Reading a segment

WriteAheadLog::for_each_recoverable streams the segment through a 1 MiB BufReader and hands each valid entry to the replay callback with the byte offset of its end. It stops at the first of these:

Condition Treated as had_corruption
Fewer than 12 bytes left for a header, more than 0 Torn header true
All-zero 12-byte header Clean end (preallocated tail) false
key_len > 64 MiB or value_len > 1 GiB Corruption true
Entry extends past the end of the file Torn entry true
CRC mismatch Corruption true
CRC valid but the entry does not decrypt Key problem: Error::Config, the open fails  

(source: src/storage/wal.rs, for_each_recoverable, is_preallocated_tail, MAX_KEY_SIZE, MAX_VALUE_SIZE)

A file without the WLOG magic is read as headerless from offset 0 with a warning; an unknown version is an error (source: src/storage/wal.rs, for_each_recoverable).

Reading stops at the first bad entry, wherever it is. Entries after a bad entry in the middle of a segment are not read, and the truncation step below removes them; later segments are still replayed (source: src/storage/wal.rs, for_each_recoverable; src/storage/mod.rs, StorageEngine::open). Not verified: no test checks the result of a bad entry in the middle of a segment followed by committed batches and a later segment.

Applying committed runs

Replay buffers data entries in pending and acts on each commit marker:

stateDiagram-v2 [*] --> Buffering Buffering --> Buffering: data entry, push to pending Buffering --> Apply: commit marker, count equals pending length Buffering --> Discard: commit marker, count differs Apply --> Buffering: insert run into memtable, commit_boundary = end of marker Discard --> Buffering: clear pending, commit_boundary = end of marker Buffering --> EndWithMarkers: end of file, a marker was seen Buffering --> EndLegacy: end of file, no marker in this file EndWithMarkers --> [*]: drop pending (torn or unacknowledged batch) EndLegacy --> [*]: apply everything, commit_boundary = last valid offset
(source: src/storage/mod.rs, StorageEngine::open; src/storage/wal.rs, parse_commit_marker)
  • A batch is written as its data entries followed by one marker carrying the entry count, so a batch either recovers whole or not at all (see WAL).
  • A file with no marker at all is a WAL written before markers existed and is applied whole. Every new segment starts with a count-0 marker, so a current file is never mistaken for a legacy one (source: src/storage/wal.rs, WriteAheadLog::open; src/storage/mod.rs, StorageEngine::open).
  • replay_committed_run inserts with MemTable::insert (newest version only), skips any stray marker and any key that does not decode, and when the memtable reaches memtable_size flushes it to an L0 SSTable through the normal flush path and starts a new one (source: src/storage/mod.rs, replay_committed_run).

Memory during replay is bounded by one memtable plus one in-flight batch, however large the segment. A crash during recovery leaves the SSTables already flushed, which raise sst_high_water, so the next open skips more (source: src/storage/mod.rs, StorageEngine::open). Tested by recovery_flushes_incrementally_and_is_resumable and recovery_streams_one_large_segment (src/storage/mod.rs, wal_replay_bounded_tests).

Tested by committed_multiwrite_batch_recovers_atomically, torn_marker_less_tail_is_discarded_all_or_nothing and commit_marker_is_not_mistaken_for_data (src/storage/mod.rs, crash_atomicity_tests).

Truncating the torn tail

After a segment is read, if commit_boundary (the end of the last marker, or for a legacy file the last valid offset) is below the file length, the file is truncated to it with truncate_at, which also fsyncs. A tail that is only zero preallocation is logged at debug level; anything else as a warning (source: src/storage/mod.rs, StorageEngine::open; src/storage/wal.rs, truncate_at).

This step exists because the engine next opens wal-<next sequence>.log for new writes, which is the same file as the torn segment when nothing was applied from it. Without the truncation, the next batch's marker would land after the discarded entries and commit them on the following recovery. The marker count check is a second guard against the same case (source: src/storage/mod.rs, StorageEngine::open). Tested by torn_tail_not_resurrected_by_later_append_to_same_wal (src/storage/mod.rs, crash_atomicity_tests).

A segment whose magic is damaged is read headerless from offset 0; the first "entry" is then the header bytes, which fail the length or CRC check, so nothing is applied and the truncation step cuts the file to 0 bytes. Data in that segment that is not already in an SSTable is lost (source: src/storage/wal.rs, for_each_recoverable; src/storage/mod.rs, StorageEngine::open). Not verified: this reading of the code has no engine-level test; STATUS.md says a corrupt WAL magic recovers "with pre-committed data intact" without naming a test (source: STATUS.md).

Unreadable segments

If a segment cannot be opened or read for a reason other than a key problem, the engine logs a warning, sets wal_unreadable, and continues with the next segment. The open succeeds without that segment's data. wal_unreadable stops the flushed-sequence watermark from being advanced over the replayed range, so WAL reclamation will not delete the unread segment (source: src/storage/mod.rs, StorageEngine::open). Not verified: no test covers an unreadable segment.

After replay

  1. If the memtable holds replayed entries, flush it to L0 (one more recovery_flushes), so every replayed segment becomes reclaimable at once.
  2. Unless a segment was unreadable, raise max_flushed_seq to next sequence - 1.
  3. Store the next sequence and open wal-<next sequence>.log for new writes.
  4. Read WAL_BACKUP_HOLD (an unparsable file fails the open) and run cleanup_old_wal_files.
  5. Start the compaction manager (2 workers), set recovery_complete, start the flush thread (which waits for recovery_complete), the fsync worker and, if SYNERGYDB_STALL_DUMP=1, the watchdog.
  6. Queue a compaction check for levels left over the trigger by the previous run.

(source: src/storage/mod.rs, StorageEngine::open, background_flush_loop, read_wal_backup_hold, cleanup_old_wal_files)

Because recovery flushes everything it replayed, the active memtable is empty when the engine starts serving.

Recovery report

StorageEngine::recovery_report() returns what the open did, and the same values are logged at info level:

Field Meaning
wal_segments_found Segments in wal_dir, including current.wal
wal_segments_skipped Segments not opened because SSTables cover them
wal_entries_replayed Committed data entries inserted into the memtable
recovery_flushes SSTables written during recovery
sst_high_water Highest sequence in any SSTable at open; None with no SSTables
max_replay_buffered_entries Most data entries held at once waiting for a marker

(source: src/storage/mod.rs, RecoveryReport, recovery_report)

The wal_replay_bounded_tests assert on these values rather than on log lines; fresh_directory_reports_nothing_recovered checks the empty case.

What kill -9 does

kill -9 ends the process without running shutdown(): no final flush, no WAL sync, no manifest snapshot. What survives is what had reached the operating system:

State at the kill After restart
Durable write acknowledged under every_write Recovered: its batch and marker were fsynced before the call returned
Write acknowledged under periodic or no_sync Recovered, provided the batch's buffer was handed to the OS; kill -9 does not drop the OS page cache
put_unsynced / write_batch_unsynced data still in the WAL writer's buffer Lost; it never left the process
Batch whose marker was not written Discarded whole
Flush in progress The memtable's data is still in the WAL; a written but unlisted SSTable is deleted as an orphan
Compaction in progress Inputs restored or .delete files removed, according to the manifest
LOCK Released by the OS when the process dies; no stale lock
MANIFEST.log Replayed over the last snapshot (written only at creation and clean shutdown)

(source: src/storage/wal.rs, append_commit_marker_opts, DurabilityLevel; src/storage/mod.rs, join_group_commit, put_unsynced, acquire_data_dir_lock, shutdown; src/storage/compaction.rs, reconcile_delete_files, purge_orphan_sstables)

The difference between kill -9 and a power loss or OS crash is the page cache. Under every_write the fsync makes the difference irrelevant for acknowledged writes; under periodic and no_sync a power loss can lose acknowledged writes that a kill -9 keeps. Not verified: no test simulates power loss or an OS crash, as the guide also says (Operations; How it works). The comments on flushed_and_compacted_sstables_reopen_intact and writes_across_many_wal_rotations_survive_reopen state the same limit for the fsync ordering they guard.

Wire-level state that lives outside the storage engine has its own crash behaviour (Memcached write-behind, MySQL AUTO_INCREMENT blocks, Redis and Bolt transactions); see Operations.

simulate_crash

In-process tests model a crash with StorageEngine::simulate_crash(self). It sets crash_mode, so Drop skips shutdown() (no flush, no sync, no manifest save), stops and joins the background threads, and discards bytes still in the WAL writer's buffer (discard_buffered_writes) before the next open (source: src/storage/mod.rs, simulate_crash, impl Drop for StorageEngine; src/storage/wal.rs). Like kill -9, it does not model loss of the OS page cache. Tested by crash_close_discards_buffered_wal_bytes (src/storage/wal.rs, tests).

Test coverage

Engine recovery tests

Test Location What it checks
committed_multiwrite_batch_recovers_atomically src/storage/mod.rs, crash_atomicity_tests A 50-entry batch written to the WAL as write_batch does recovers whole
torn_marker_less_tail_is_discarded_all_or_nothing same A batch without its marker is dropped; the earlier batch survives
torn_tail_not_resurrected_by_later_append_to_same_wal same A discarded tail is not committed by a later marker
commit_marker_is_not_mistaken_for_data same The marker never decodes as a user key
engine_opens_with_torn_trailing_manifest_log_record src/storage/mod.rs, crash_reopen_durability_tests Torn MANIFEST.log tail; WAL removed so data must come from SSTables
manifest_referenced_delete_files_are_reconciled_on_open same Compaction crash window
flushed_and_compacted_sstables_reopen_intact, writes_across_many_wal_rotations_survive_reopen, reads_never_go_backwards_while_flush_is_in_flight src/storage/mod.rs, durability_review_fix_tests Fsync ordering code paths, rotation, flush visibility
reopen_skips_fully_flushed_segments, recovery_flushes_incrementally_and_is_resumable, overwrite_heavy_load_keeps_wal_near_retention_target, concurrent_overwrites_with_rotation_lose_nothing, recovery_streams_one_large_segment, fresh_directory_reports_nothing_recovered src/storage/mod.rs, wal_replay_bounded_tests Bounded, resumable replay asserted through RecoveryReport
concurrent_durable_commits_all_complete_and_survive_reopen src/storage/mod.rs, group_commit_tests 16 threads of durable commits survive reopen
second_engine_on_same_data_dir_is_refused_while_first_is_open, lock_is_released_when_the_engine_drops src/storage/mod.rs, data_dir_lock_tests Directory lock
backup_wal_hold_survives_restart, corrupt_backup_wal_hold_refuses_to_open src/storage/mod.rs, wal_backup_hold_tests Backup hold file
lsm_oracle_matches_across_flush_and_restart, lsm_oracle_thorough_wal_drop_and_compaction, scan_resolves_multi_sstable_versions_by_sequence_after_restart, overwrite_and_delete_survive_compaction_and_sstable_only_restart, restart_without_sync_loses_writes_after_wal_drop src/storage/property_oracle_tests.rs Randomized programs with restarts compared with a model

tests/crash_recovery_test.rs

Three tests drive StorageEngine (test_storage_engine_crash_simulation, test_storage_engine_recovery_with_deletes, test_storage_engine_recovery_sequence_continuity): each writes, calls sync() and simulate_crash(), reopens and reads back.

The other tests in this file exercise CrashRecoveryManager from src/storage/recovery.rs, not the engine's recovery: partial headers, keys and values, CRC corruption, Strict against BestEffort mode, multiple segments, memtable rebuild, and SSTable verification.

Not wired: CrashRecoveryManager, RecoveryMode (Strict, BestEffort, Repair), validate_wal_integrity, needs_recovery, quarantine_corrupt_segments and truncate_wal_at_valid have no caller in the engine or the server; StorageEngine::open does its own replay. The manager accepts only WAL version 1 and has no notion of commit markers, so its results do not describe how the engine treats an encrypted WAL or a torn batch (source: src/storage/recovery.rs, CrashRecoveryManager, WAL_VERSION; src/storage/mod.rs, StorageEngine::open).

tests/failure_modes.rs

The mid_write_crash and corruption tests (failure_crash_partial_wal_entry, failure_corrupt_wal_crc_besteffort, failure_corrupt_wal_crc_detection, failure_truncated_wal_recovery and others) close the engine normally before damaging the last WAL file, so the data is already in SSTables when the WAL is truncated or a byte is flipped. They show that the engine opens over a damaged segment, and their assertions are loose (for example "at least 30 of 80" keys); they do not exercise replay of the damaged data (source: tests/failure_modes.rs; tests/protocol_helpers, open_storage, truncate_last_wal_bytes, corrupt_wal_crc).

Restart phase of the differential proof

The proof pack restarts SynergyDB with prove/sdb.sh restart, which sends kill -9 to the server process, waits for it to exit, starts it again on the same data directory and waits for its ports. PROVE_RESTART=graceful switches to SIGTERM and a clean shutdown (source: prove/sdb.sh, stop9, stop_graceful). Each suite's restart phase writes data, triggers that restart (the reference database gets a normal docker restart), then re-reads everything over a fresh connection and compares the answers with the reference (source: prove/wires.py; docs/proof/2026-11-30/proof-pack-a3232c9/report.md).

In the 2026-11-30 run (a3232c9, mode crash), the restart phases matched in full for PostgreSQL, MySQL, Neo4j/Cypher, Redis, Cassandra, ClickHouse, InfluxDB, Gremlin, S3, Kafka, Schema Registry and CouchDB. SQL Server matched 7/8 and Oracle 5/6; in both the one difference is in the column type metadata a view reports after the restart, not in the rows. The Memcached restart-durability check read back 9/23 items under the default write-behind mode. The MongoDB, DynamoDB and Elasticsearch suites in that report are single-connection only and have no restart phase (source: docs/proof/2026-11-30/proof-pack-a3232c9/report.md; docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt, logs/oracle-oracle-diff.txt). Per-wire counts are in How it works.

The proof restarts exercise the whole server, wires included, and the build used --features full (source: docs/proof/2026-11-30/README.md).