grafeo icon indicating copy to clipboard operation
grafeo copied to clipboard

Crash-safe persistence and one storage format

Open StevenBtw opened this issue 2 months ago • 4 comments

Summary

Persistence has confirmed durability holes and structural limits.

Durability holes

  • A checkpoint overwrites the previous image in place, so a checkpoint that fails midway (for example on a full disk) leaves the file unreadable.
  • A crash after wal_checkpoint() duplicates edges on reopen, because recovery replays records that are already in the checkpoint and replay is not idempotent.
  • In WAL-directory databases, wal_checkpoint() deletes rotated WAL files that exist nowhere else, and two processes can open the same database and overwrite each other's data (#405).
  • Some DDL reports success without effect: DROP CONSTRAINT does nothing, constraints and graph type changes are lost on WAL replay, and CREATE GRAPH ... AS COPY OF creates an empty graph.

Structural limits

  1. Section block offsets and lengths are 32-bit, so a section over 4 GiB cannot be written (#392). One large embedding column or named graph is enough to hit it.
  2. A checkpoint builds every section in memory before writing, and opening a database reads whole sections into memory, so peak RAM is two to three times the database size.
  3. Every checkpoint rewrites every section.
  4. There are two on-disk layouts (a .grafeo file and a WAL directory) with different recovery behavior, and vector and text index definitions do not survive a reopen in WAL mode (#401).

This epic closes the holes first without a format change (0.5.44), then replaces the format in one bump so users migrate once (0.6.0), and makes checkpoints incremental on top of the compact-core store in the same release. Old files stay readable through a one-way migration on open.

Goals

  • Checkpoints are crash-safe: the new image is written and synced before the WAL is truncated, the previous image stays valid until the switch, and WAL replay is idempotent.
  • Only one process can open a database for writing; a second one gets a clear "database locked" error.
  • DDL does what it reports and survives a reopen.
  • One on-disk layout: a .grafeo file plus a sidecar WAL, used by default for new paths. WAL-directory databases migrate on open.
  • WAL v2: a log sequence number (LSN) and transaction id on every record, typed catalog and index records that carry full definitions (index definitions, type default values and parent types, graph type bindings and named constraints survive reopen), streaming recovery that does not hold the whole log in memory, and strict corruption handling (recovery never skips past a damaged record and applies later ones).
  • Container v3: the checkpoint LSN is stored in the header, sections are split into chunks with 64-bit offsets, and the number of blocks is unbounded.
  • Memory during checkpoint and open is bounded by one chunk per section, not by the database size.
  • Checkpoints are taken from a consistent snapshot, and automatic checkpoint triggers (WAL size, interval) are configurable from every binding.
  • Full backups compute their checksum while streaming instead of re-reading the file (#362, first part).
  • Checkpoints write only the chunks that changed.
  • Golden fixtures for every shipped format, and a migration test that covers indexes, schema and named graphs.

Non-goals

  • Transaction grouping of WAL records: see the "Transactions own their changes" epic.
  • Online full backup from an MVCC read view (#362, second part): 0.7.x.

Design

0.5.44, crash safety without a format change: write the new image to a temporary file (or new sections), sync it, switch atomically, and only then truncate the WAL. Recovery skips records already contained in the checkpoint. wal_checkpoint() in directory mode no longer truncates. A LOCK file in the database directory is held exclusively for read-write and shared for read-only opens. DDL replay uses typed records and calls the same code as the live statement; the WAL keeps its string encoding, so old WAL files still replay. Constraints get names (#420): a .grafeo file stores them by appending them after the version 1 catalog section, which older versions ignore. This is a stopgap that the 0.6.0 catalog format replaces. This needs a crash test on Windows as well as Linux, since atomic replace differs there.

0.6.0, the format bump (one change, so users migrate once):

  • Container v3. A 4 KiB file header (magic, format 3, page size, creator version, a random database id, an encryption flag), two 4 KiB database headers, then page-aligned chunks and directory blocks. A database header holds its iteration, the checkpoint LSN (the last WAL position the image contains), the epoch and last transaction id, the location and CRC of the root directory block, node and edge counts, and its own CRC. The valid header with the higher iteration is active.
  • Directory. Chained blocks of fixed 48-byte entries, so the number of chunks is unbounded: section type and version, chunk kind, codec, graph id, column id, first row and row count, 64-bit offset and length, CRC. Named graphs are chunk sets tagged with a graph id: no nested sections and no 127-section limit. Each section has a small metadata chunk with its column catalog, rows per chunk and byte cap.
  • Chunks. Tables are split by id range into chunks of at most 64Ki rows and 1 MiB (a value larger than the cap gets a chunk of its own), each with its own CRC and zone map. A column chunk is a presence bitmap plus a typed codec, the encoding compact() uses since #542; it is also the compact-core store's cold-chunk encoding (#432). Space is allocated in runs of contiguous 4 KiB pages, so small databases stay small.
  • Copy-on-write checkpoints. A checkpoint takes a snapshot at epoch E, which covers the WAL up to LSN L; streams the changed chunks into free page runs, never over a page the active header reaches; writes the directory, which points unchanged chunks at their existing pages; syncs; writes the inactive header with L and the new root; syncs (the switch); then truncates the WAL to L. Pages only the old directory used become free. Free space is every page the directory does not use, derived from it at open, so it cannot disagree with the directory; free space at the end of the file is trimmed. There is no second copy of the file and no rename. A checkpoint that writes every chunk is the case where every chunk is dirty, so incremental checkpoints (#430) need dirty-chunk tracking, not a second write path.
  • Streaming section API. Section::write_to(&mut dyn SectionSink) and read_from(&dyn SectionSource) push and pull one chunk at a time, so memory during a checkpoint and an open is bounded by one chunk per section. The traits live in grafeo-common and grafeo-storage implements them, so the crate boundaries stay as they are. Chunks and directory blocks are encrypted one by one; the headers hold no data.
  • WAL v2. Segments wal_<first LSN>.log in the sidecar directory <file>.wal/, each starting with a header (magic, version 2, database id, first LSN); a WAL with another database id is refused. The LSN is the byte position in the log. A frame is [length u32][crc32 u32][lsn u64][transaction id u64][flags u8][payload]; lengths are checked before allocating and when writing. A transaction is one contiguous group of frames (FIRST to LAST) written in the commit critical section, so only the last group can be incomplete, and aborted transactions never reach the WAL. Records are typed and closed, every change names its graph, catalog records carry full definitions (#517), index records replay (#401), and replay calls the same apply functions as the live statement.
  • Recovery. Replays the frames after the checkpoint LSN, applying a group once its LAST frame is found ahead, so memory is bounded by one frame. A torn tail (an incomplete frame at the end of the last segment, followed by nothing or zeros) is cut off; any other damage fails the open with the file and offset (#425). Opening up to the last intact transaction is an explicit opt-in.
  • Catalog v2. One explicit, versioned structure: schemas; node, edge and graph types with default values, parent types, endpoints and key labels; graph type bindings; named constraints; the indexes of every graph with their names; procedures; the stored configuration. Snapshots move to version 5 and embed the same structure; import keeps reading version 4.
  • Stored configuration (#551). The file stores what defines or protects the database: graph model, backward edges, schema constraints, WAL and durability mode, memory limit, section tier overrides, and the spill path when it is relative to the database. Thread count and absolute paths are not stored. open(path) and read_only(path) apply the stored values; an explicit value on open applies to that open only, and changing a stored value is an explicit call.
  • Migration on open. A 0.5.x database (container format 1 or 2, a WAL without segment headers, or a WAL directory) migrates on its first read-write open. Under <path>.migrate.lock, the 0.5.x reader loads it, a complete v3 file is written to <path>.migrating and synced, the old database is renamed to <path>.pre-0.6 (with its sidecar WAL; a WAL directory as a whole), and <path>.migrating becomes <path>. Nothing is copied, the old database is never modified, and a crash at any step is resolved from the files present at the next open. A WAL directory becomes a single file at the same path. A read-only open reads the 0.5.x format without writing. New paths without an extension are single files; StorageFormat::WalDirectory only opens existing directories and is removed in 0.7.0 together with the 0.5.x readers (0.7.0 asks to open such a database with 0.6 first). What the old files never held cannot be migrated: default values, parent types and edge endpoints of types defined only in a 0.5.x WAL, constraint names in 0.5.43 files, and graph switches in 0.5.43 WAL directories.

Order. Each step merges into the release branch on its own, and databases written by released versions keep opening after every step: migration and container v3 (existing sections behind an adapter); every section on the streaming API (chunked LPG and RDF, catalog v2, the index and compact sections); WAL v2; stored configuration and snapshot v5; golden fixtures of the final formats and the release notes; incremental checkpoints, checkpoint triggers (#426), backup checksums (#362) and the size and memory tests (#428, #429).

Tests. The golden fixtures of every shipped format (#427) migrate, with their .pre-0.6 copy byte-identical to the fixture; golden fixtures of container v3 and WAL v2; crash injection at every checkpoint and migration step, on Linux and Windows; an injected tiny chunk cap, so the multi-chunk, multi-directory-block and free-run reuse paths run in normal CI; torn tails at every byte of the last group, damage in the middle of a segment, a WAL from another database; random round trips with and without crashes.

Breaking changes: the on-disk format and the snapshot format (migrated automatically; 0.5.x cannot open the new files, and 0.7.0 removes the 0.5.x readers), StorageFormat::WalDirectory (deprecated, removed in 0.7.0), and the internal Section trait.

Affected profiles

  • [x] embedded (facade, Python, Node.js, C and friends)
  • [ ] edge (WASM, grafeo-web)
  • [x] server (grafeo-server)

Target

0.5.44 to 0.6.0 (finishes in 0.6.0)

Sub-issues

0.5.44

  • #405
  • #344
  • #417
  • #418
  • #419
  • #420
  • #421
  • #422
  • #423
  • #424

0.6.0

  • #392
  • #401
  • #362
  • #425
  • #426
  • #427
  • #428
  • #429
  • #517
  • #430
  • #551
  • #555
  • #556
  • #557

StevenBtw avatar Sep 27 '26 18:09 StevenBtw

Maybe it's worth to bump version to 0.6.x to avoid silent existing db's rewrites when version is set to 0.5 in cargo.toml?

stiff avatar Oct 04 '26 14:10 stiff

Maybe it's worth to bump version to 0.6.x to avoid silent existing db's rewrites when version is set to 0.5 in cargo.toml?

Hi @stiff That's actually not a bad idea, I will consider this for 0.5.45. which I will release next week.

StevenBtw avatar Oct 04 '26 14:10 StevenBtw

Maybe it's worth to bump version to 0.6.x to avoid silent existing db's rewrites when version is set to 0.5 in cargo.toml?

0.6.0 it is, it's a week out, but I will also add some other imminent braking changes. Thanks for the suggestion @stiff!

StevenBtw avatar Oct 04 '26 17:10 StevenBtw

Glad to see progress on the cool project

stiff avatar Oct 05 '26 08:10 stiff