Skip to content

Compact the data log by writing its next generation - #131

Merged
saworbit merged 6 commits into
mainfrom
format/compaction
Nov 12, 2026
Merged

saworbit merged 6 commits into
mainfrom
format/compaction

Conversation

@saworbit

Copy link
Copy Markdown
Owner

Description

Fixes #108

Stacked on #130, which is stacked on #129, #128 and #127. Merge those first. Until then this diff also shows their commits; this PR's change is b961c18.

This implements generation-swap compaction from on-disk format 1 (spec §9.1; PR 4 in §14). NvramLog::compact had three problems:

  • It rewrote the log in place while holding every lock, so reads and writes waited for the whole copy.
  • It read every live segment into memory before writing any of them.
  • A crash part way left a log that open refused until someone removed the .compacting marker by hand, with nothing to check the data against.

What changed:

  • Compaction writes the next generation (crates/nvram-sim/src/lib.rs):
    1. Holding the file lock, it notes the live segments and where the log ends. A segment is live while its ref count is above 0, which covers open writes and GETs still reading a capsule an overwrite dropped.
    2. Without the log's locks, it copies those records unchanged into space.nvram.compact, a buffer at a time. Records hold no offsets, so their checksums stay valid.
    3. Under the locks, it copies records appended meanwhile, plus any segment that gained references, writes the next generation's FILE record, fsyncs, closes the old file and renames the new one into place. If the rename fails, the old file is reopened and nothing changes.
  • Crash recovery needs no manual step: open deletes a leftover space.nvram.compact, because the log it would have replaced is intact. A .compacting marker from the in-place compaction of earlier builds is still refused.
  • Segment ids are never reused: the FILE record's segment_id_floor is one past every id the log has held, including ones compaction removed. Opening a pipeline raises the allocator to that floor, so those ids aren't handed out again after space.db is lost.
  • Appends and the snapshot agree: appends keep the file lock until their records are in the segment map, so compaction never sees a record without its map entry. A log with nothing to reclaim is left alone, and only one compaction runs at a time.

Type

  • Bug fix
  • New feature
  • Breaking change
  • Refactor / cleanup
  • Docs / comments only

Checklist

Quality gates

  • cargo fmt --all
  • cargo clippy --all-targets -- -D warnings (run with --workspace)
  • Tests pass (cargo test --workspace): 333 passed, 0 failed
  • cargo xtask audit (if touching crates, deps, or features): not available in this tree; no dependency changes
  • Docs compile: RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps

Documentation

  • I updated relevant docs (or no user-facing changes)
  • CHANGELOG.md updated (for features, fixes, breaking changes)

Security

  • No hardcoded secrets, tokens, or keys introduced
  • External inputs are validated (if applicable)
  • No new unsafe blocks (or they are justified and documented)

Dependency changes (skip if none)

None.

What a reviewer should know

  • Where the code differs from §9.1 (all recorded in the spec's §14):
    • Step 1 takes no pipeline lock. Open writes and readers hold segments through the data log's in-memory reference counts, so the log can note the live set itself.
    • The floor is the log's own, rather than the allocator's next id.
    • The catch-up also copies any segment that gained references after step 1. Nothing should revive a dead segment, because nothing can find one to dedup against, but the copy costs nothing when there are none.
  • Lock order in the data log is file, next_offset, segment_map. Appends now hold file slightly longer, until their map entries are in.
  • Windows: the old file is closed before the rename, and the new one is renamed while open, relying on std opening files with FILE_SHARE_DELETE. The tests exercise this on Windows.
  • Crash testing: a crash is simulated by a test-only hook that stops compaction at a step and leaves the files as they are, after which the test reopens the log. A real kill during compaction isn't tested, because nothing outside tests and the Rust API calls compaction yet.
  • Mutation checks: reverting the registry to the old max_segment_id + 1 floor fails the id-reuse test, and skipping the catch-up copy fails the concurrent test.
  • Still open: nothing schedules compaction, and there's no spacectl compact or gc. That's the rest of Interrupted writes leave orphaned segments that nothing ever reclaims #97, listed as PR 5 in the spec. Pipeline::garbage_collect still doesn't know about the segments a GET holds, as Move S3 buckets and keys onto the capsule journal #130 noted.

Add docs/on-disk-format.md, a draft spec (not implemented) for making
every durable fact rebuildable from append-only files:

- A 48-byte checksummed frame on every record.
- SEGMENT records that carry their write-once descriptor next to the
  stored bytes, replacing the JSON sidecar.
- A separate capsule journal (CAPSULE manifests with a logical digest,
  DROP, NAMESPACE, BIND, UNBIND, atomic BATCH), with sled demoted to a
  rebuildable index and ref counts derived from live manifests.
- Torn-tail truncation, read-only open on mid-file corruption, and
  compaction by generation swap.

Targets #96, #97 and #108. Link it from docs/README.md as a draft.
Implement the data-log half of on-disk format 1. The NVRAM log no longer
needs a sidecar: losing space.nvram.segments made every capsule
unreadable (#96), and the file was rewritten whole on every append and
ref-count change without an fsync.

- common::format: codec for the 48-byte record frame (BLAKE3 head and
  body checksums), the FILE record and the SEGMENT descriptor, with
  byte layouts defined field by field.
- nvram-sim: the log starts with a FILE record and every append writes
  one framed record per segment. open() scans the log to rebuild the
  segment map, truncates a record cut short at the end, and opens
  read-only when invalid bytes are followed by valid records. Stores
  from before format 1 are refused with a message saying so.
- Ref counts are no longer stored. Opening a registry pipeline recounts
  them from the capsules in space.db, so an interrupted dedup write
  can't leave an inflated count (part of #97). Compaction refuses to
  run until counts have been recounted.
- Deletes and GC now change only the in-memory map; a removed segment's
  record comes back with no references on reopen until compaction
  drops it. integration_test is updated for that.
- Tests: codec layouts and checksums, truncation of the last record at
  every byte offset, mid-log damage, compaction after a recount, and
  registry-level reopen, dedup-crash and torn-append cases.
- Docs: capsule.md, the S3 quick start, dedup and encryption notes,
  SECURITY.md, nvram-sim.md and CHANGELOG describe the new log. The spec
  now records that only the last body is checksummed on open, that an
  all-zero content hash means none, a forward-search limitation, and
  how this stands in until the journal exists.

Breaking: existing space.nvram stores can't be opened.

Closes #96.
Implement the capsule-journal half of on-disk format 1. Capsule records
lived only in sled, so losing space.db lost the capsule list, and a
crashed write could leave a content-index entry for a segment that
compaction later removed.

- common::format: codecs for CAPSULE manifests (segment entries with
  plain length and content hash, BLAKE3 digest, dedupe and
  requires-encryption flags, write-time policy), DROP and BATCH.
  Capsule gains a digest field.
- nvram_sim::record_file: the open, scan and torn-tail logic from the
  data log, now shared with the journal.
- capsule-registry: space.journal next to space.db. A write commits by
  appending and fsyncing a CAPSULE record, a delete by a DROP. Each
  record is applied to sled in one transaction with the journal
  position. On open, records past that position are replayed; a missing
  or mismatched index is rebuilt; a space.db from before the journal is
  refused. sled keeps per-segment reference counts and which segment
  each indexed hash belongs to.
- New segments' hashes wait in an in-memory pending index and reach the
  durable content index only when their capsule commits.
- The pipeline builds the manifest and digest as it writes, commits a
  delete before releasing segments, and read_capsule checks the digest.
- Pipeline opens pair the journal with the data log's store id (a new
  journal adopts it; a mismatch is refused), keep the segment allocator
  above every id in the log, and set the log's ref counts from sled.
- Tests: journal codecs; index rebuilt after deleting space.db; records
  an older index missed replayed; torn journal tail; crashed write
  leaves no index entry; store id mismatch and adoption; digest. Two
  integration tests move from fixed paths in the crate folder to unique
  temp directories.
- Docs: capsule.md, the S3 quick start, dedup notes and CHANGELOG
  describe the journal; the spec records PR 2 as done and where the code
  differs from it.

S3 buckets and keys still live only in sled.

Part of #97.
Implement the names half of on-disk format 1. S3 buckets and keys lived
only in sled, so losing space.db lost them, and an S3 overwrite bound
the new key and deleted the old capsule in separate steps, so a crash in
between could leave the old capsule alive with no key pointing at it.

- common::format: codecs for NAMESPACE, BIND and UNBIND. A namespace
  can't be empty or contain NUL, checked on encode and decode. BATCH
  sub-records drop their frame (kind, version, reserved, header_len,
  header): embedded whole records made a torn batch look like damage in
  the middle of the journal, which then refused to open.
- CapsuleCatalog has one commit(records) that commits several records
  as a BATCH and returns the capsules its DROPs removed;
  create_capsule and delete_capsule are built on it.
- capsule-registry: commit checks CAPSULE and DROP records against the
  index under the journal lock, so a DROP of a capsule that isn't live
  fails the whole commit and nothing is written. sled indexes names in
  namespaces and names trees; the s3_buckets and s3_objects trees and
  the MetadataLog that wrote them are gone. A pre-journal space.db
  holding S3 buckets is refused like one holding capsules, and a
  rebuild drops the old trees. The index version goes to 2.
- pipeline: finish_write_with commits a write together with other
  records, commit commits records alone, and release frees a dropped
  capsule's segments, so a caller can hold them while a reader
  finishes. stage_from_reader leaves a streamed write for the caller to
  commit.
- protocol-s3: buckets are namespaces "s3:<bucket>" and keys are names.
  PUT commits the capsule, its key, the bucket if new and the drop of
  the replaced capsule as one batch; DELETE commits the unbind and the
  drop as one. Overwrites and DELETEs commit at once; a GET in flight
  holds the dropped capsule's segments until it ends, instead of
  delaying the delete. A failed PUT no longer creates its bucket.
- Tests: name codecs and namespace rules; a batch cut at every byte is
  dropped as a torn tail; names rebuilt after deleting space.db; a
  refused commit writes nothing; a torn overwrite batch leaves the old
  key; pre-journal S3 names refused or dropped; S3 keys survive a lost
  index; the GET-during-overwrite test now checks segments stay pinned.
- Docs: the spec records PR 3 as done, the new BATCH layout and where
  the code differs; capsule.md, the S3 quick start, streaming reads,
  dedup notes and CHANGELOG describe names in the journal.

Part of #97.
Implement generation-swap compaction from on-disk format 1 (spec 9.1).
NvramLog::compact rewrote the log in place while holding every lock,
read all live segments into memory first, and a crash part way left a
log that open refused until someone removed the .compacting marker by
hand.

- nvram-sim: compact notes the live segments (ref count above 0, which
  covers open writes and GETs still reading a dropped capsule) and the
  log's end while holding the file lock, then copies those records
  unchanged into space.nvram.compact a buffer at a time without the
  log's locks. Under the locks it copies records appended meanwhile and
  any segment that gained references, writes the FILE record for the
  next generation, fsyncs, closes the old file and renames the new one
  into place. If the rename fails the old file is reopened.
- Open deletes a leftover space.nvram.compact: the log it would have
  replaced is intact. A .compacting marker from the in-place compaction
  of earlier builds is still refused.
- The FILE record now carries a segment id floor: one past every id
  the log has held, including ones compaction removed. Opening a
  pipeline raises the allocator to it, so those ids aren't handed out
  again after space.db is lost.
- Appends keep the file lock until their records are in the segment
  map, so compaction never sees a record without its map entry. A log
  with nothing to reclaim is left alone, and only one compaction runs
  at a time.
- Tests: next generation and id floor across reopens; nothing to
  reclaim; a crash at each step (after the copy, after the fsync,
  after the rename) reopens and compacts again; appends, releases and a
  revived segment during the copy; ids not reused after compaction and
  a lost index; an open write's segments kept; an S3 GET finishing
  while compaction runs under it.
- Docs: capsule.md, the dedup notes and CHANGELOG describe the new
  compaction; the spec records PR 4 as done, where it differs from 9.1,
  and scheduling as PR 5.

Nothing schedules compaction yet; that is the rest of #97.

Closes #108.
@saworbit
saworbit merged commit ac0964e into main Nov 12, 2026
2 checks passed
@saworbit
saworbit deleted the format/compaction branch November 12, 2026 20:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Storage] Make NvramLog::compact bounded-memory and crash-safe

1 participant