Compaction

Compaction merges SSTables so that overwritten versions and deletes stop costing disk space and read fan-out. It lives in src/storage/compaction.rs (CompactionManager) and is driven from the engine's background flush loop and from VACUUM FULL (source: src/storage/compaction.rs, CompactionManager; src/storage/mod.rs, background_flush_loop, compact_full).

Compaction never edits a file. It writes a new SSTable with a fresh file number, records the swap in the manifest as one log record, and only then deletes the inputs (see Manifest).

Strategy and levels

The strategy is leveled. Level 0 holds flush output, whose key ranges overlap. Levels 1 to 6 hold compaction output. Each level has a trigger:

Level Trigger (needs_compaction) Default threshold
L0 File count >= max_files 4 files
L1 Total file_size > max_bytes 10 MiB
L2 same 100 MiB
L3 same 1,000 MiB
L4 same 10,000 MiB
L5 same 100,000 MiB
L6 (bottom) never compacted further  

max_bytes for level n >= 1 is 10 MiB x level_ratio^(n-1), with level_ratio 10 and num_levels 7 (source: src/storage/compaction.rs, CompactionManager::with_throttle, LevelConfig, needs_compaction; src/storage/mod.rs, StorageConfig::default). Neither level_ratio nor num_levels has a config-file key (see Overview).

The manifest always starts with 7 levels (VersionState::new(7)), independent of StorageConfig::num_levels. The compaction manager and load_sstables use the config value, while the bottom-level test for tombstones uses manifest.num_levels(). The two agree only because num_levels cannot be changed from the config file (source: src/storage/manifest.rs, Manifest::new; src/storage/compaction.rs, execute_compaction_throttled; src/storage/mod.rs, load_sstables_reusing).

Picking a job

maybe_schedule_compaction checks levels 0 to 5 in order. For each level over its trigger, pick_compaction builds a CompactionJob { level, inputs, overlapping }:

Source level inputs
L0 Every L0 file
L1 and below The first file the manifest lists at that level (the earliest added)

overlapping is every file at level + 1 whose key range may share a user key with any input (source: src/storage/compaction.rs, maybe_schedule_compaction, pick_compaction).

Overlap on user keys

File bounds in the manifest are encoded internal keys (user_key || sequence || op_type, see Keys and namespaces). Comparing those bytes directly could call two files disjoint when both hold the same user key at different sequences. key_ranges_overlap therefore compares conservative user-key bounds: the upper bound is the file's maximum encoded key, and the lower bound is user_key_lower_bound(min), which strips the 9-byte suffix and then cuts at the first 0x00 byte so that a shorter user key that is a prefix of the first one still counts. Two files are disjoint only when every possible user key of one sorts below every possible user key of the other (source: src/storage/compaction.rs, key_ranges_overlap, user_key_lower_bound). The code dates this to a 2026-06-11 review fix for deletes that came back after compaction. Tested by test_key_ranges_overlap and key_ranges_overlap_same_user_key_different_sequences (src/storage/compaction.rs, tests).

Scheduling and workers

flowchart TD F["background flush loop, 100 ms tick"] -->|"after a flush"| S["maybe_schedule_compaction"] O["StorageEngine::open"] -->|"once, at startup"| S S -->|"job per level over trigger"| Q["bounded channel, 100 jobs"] Q --> W1["worker 1"] Q --> W2["worker 2"] W1 --> L["compaction_lock"] W2 --> L L --> E["execute_compaction_throttled"] F -->|"every 50 ticks"| SA["maybe_compact_for_size_amp"] SA --> L V["VACUUM FULL: compact_full"] --> L
(source: src/storage/mod.rs, background_flush_loop, StorageEngine::open, maybe_compact_for_size_amp, compact_full; src/storage/compaction.rs, CompactionManager::start)
  • StorageEngine::open creates the manager with CompactionManager::new and starts 2 worker threads. Each worker waits on the job channel with a 100 ms timeout (source: src/storage/mod.rs, StorageEngine::open; src/storage/compaction.rs, start).
  • Jobs are queued after every flush that wrote something, and once at the end of open, so a store that reopens with an over-threshold level does not wait for the next flush (source: src/storage/mod.rs, background_flush_loop, StorageEngine::open).
  • The job channel is crossbeam_channel::bounded(100). maybe_schedule_compaction uses a blocking send, so with 100 jobs queued the caller (the flush loop) waits for a worker to take one (source: src/storage/compaction.rs, with_throttle, maybe_schedule_compaction).
  • Every execution takes compaction_lock, shared by both workers, the size-amplification trigger and the foreground force_compaction/compact_all. At most one compaction runs at a time; the second worker only shortens the wait between jobs. The lock exists because two concurrent compactions could pick the same L0 inputs and race on renaming them (source: src/storage/compaction.rs, compaction_lock).
  • A worker logs a failed job with eprintln! and takes the next one. There is no retry other than the next scheduling pass (source: src/storage/compaction.rs, start).

Stale jobs

A job is chosen when it is queued but runs later. Under the lock, execute_compaction_throttled returns without doing anything when any input or overlapping file no longer exists on disk, or when a source-level input is no longer listed at that level in the manifest (for example after a trivial move) (source: src/storage/compaction.rs, execute_compaction_throttled). The same L0 pile is often queued several times, one job per flush; all but the first become no-ops this way.

Executing a job

Trivial move

A job with one input, nothing overlapping at the next level, and a target level that is not the bottom level is settled with manifest.record_move: the file keeps its name and bytes and is re-recorded one level down. The bottom level is excluded because tombstones are dropped only when a file is rewritten into it. CompactionStats::trivial_moves counts these (source: src/storage/compaction.rs, execute_compaction_throttled; src/storage/manifest.rs, VersionEdit::MoveSSTable). Manifest replay of a move is tested by record_move_replays_from_log (src/storage/manifest.rs, tests). Not verified: no test asserts that a compaction takes the trivial-move path.

A trivial move does not change the number of SSTables, and the flush loop refreshes the engine's in-memory levels only when the manifest's file count differs from it. After a move, the in-memory level of that file (and the level_sstable_counts in StorageEngine::stats, which feed the synergydb_sst_files_total gauge) can lag the manifest until the next count change. Reads are unaffected because get and scan consult every SSTable whatever its level (source: src/storage/mod.rs, background_flush_loop, stats, get; src/observability/metrics.rs, update_storage_metrics).

Merge

  1. Open an SSTableReader for every input and overlapping file and add up their sizes as bytes_read.
  2. Call throttle.acquire(bytes_read) (see Throttling).
  3. Allocate a file number with manifest.next_file_number() and open SSTableWriter for sst-<16 hex>.sst with the user-key bloom filter.
  4. k-way merge. One CompactionCursor per input streams the file block by block with read_block_uncached (so compaction does not fill the block cache) and yields only the newest version of each user key in that file. A BinaryHeap of Reverse<MergeHeapEntry>, ordered by (user_key ASC, sequence DESC), holds one head per input; the newest version of each user key pops first.
  5. For each popped entry: refill from its cursor; if its user key equals the last emitted one, drop it (entries_dropped); if it is a tombstone eligible for dropping (below), drop it; otherwise writer.add it.
  6. Throttle every 1,000 processed entries on the bytes written since the last check, and once more at the end.
  7. writer.finish() fsyncs the new file and its directory.

(source: src/storage/compaction.rs, execute_compaction_throttled, CompactionCursor::next_newest, MergeHeapEntry)

Memory is bounded by one decoded block per input plus the heap heads. The comment on CompactionCursor records that the previous version pushed every entry of every input into one heap first, and that a process peaked at 6.2 GB compacting 38 L0 files after recovery (source: src/storage/compaction.rs, CompactionCursor).

Each job writes exactly one output SSTable at level + 1, whatever its size; there is no target file size and no splitting (source: src/storage/compaction.rs, execute_compaction_throttled).

An entry whose key does not decode as an InternalKey is skipped silently (source: src/storage/compaction.rs, execute_compaction_throttled).

Commit: two-phase delete

sequenceDiagram participant C as Compaction participant D as data_dir participant M as MANIFEST.log C->>D: write and fsync sst-NEW.sst C->>D: rename each input to NAME.delete (prepare) C->>M: append CompactionV2 inputs to outputs, fsync C->>D: unlink each NAME.delete (commit)
(source: src/storage/compaction.rs, TwoPhaseDeleteState, execute_compaction_throttled; src/storage/manifest.rs, record_compaction)
Failure point What happens
prepare fails Renames are rolled back, the output file is removed, the job returns the error
record_compaction fails Renames are rolled back, the output file is removed, the job returns the error
commit fails to unlink a file Logged as a warning and reported as success; the leftover .delete file is removed on the next open
Crash between prepare and the manifest record On open, reconcile_delete_files renames each .delete file the manifest still lists back to its name
Crash after the record, before the unlink On open, reconcile_delete_files deletes the unlisted .delete files
Crash before prepare The output is an SSTable the manifest does not list; purge_orphan_sstables deletes it on open

(source: src/storage/compaction.rs, TwoPhaseDeleteState::prepare, commit, rollback, reconcile_delete_files, purge_orphan_sstables; src/storage/mod.rs, StorageEngine::open)

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), and record_compaction_replays_atomically_from_log (src/storage/manifest.rs, tests). The open-time order is described in Crash recovery.

The same protocol (rename, one CompactionV2 record, unlink) is reused by replace_range_bulk and by the at-rest re-encryption rewrite (source: src/storage/mod.rs, replace_range_bulk; src/storage/at_rest.rs, record_compaction call).

Engine view after a compaction

Compaction changes only the manifest and the files. The engine's in-memory levels (the open SSTableReaders) are brought back in line by:

  • the flush loop, every tick, when the manifest's SSTable count differs from the in-memory count; it takes the compaction lock, then the flush lock, and calls load_sstables_reusing;
  • force_compaction, compact_all and compact_for_size_amp_now, which call refresh_levels_from_manifest while still holding the compaction lock.

load_sstables_reusing keeps the existing reader for every file still listed, so block-cache and column-cache entries keyed by reader id stay valid (source: src/storage/mod.rs, background_flush_loop, refresh_levels_from_manifest, load_sstables_reusing). Tested by refreshing_levels_keeps_readers_of_files_still_on_disk (src/storage/mod.rs, reader_reuse_tests).

Tombstones

A tombstone (delete) is written to the output like any other newest version, except when all of these hold:

  1. the job writes into the bottom level (job.level + 1 == manifest.num_levels() - 1, that is L5 to L6 by default), and
  2. no SSTable outside this job may contain the tombstone's user key. The test is exact in encoded-key space: a file spanning [min_enc, max_enc] may hold user key K if [K || 00 x 9, K || FF x 9] intersects that span.

When both hold, the tombstone and every older version of the key are dropped (source: src/storage/compaction.rs, execute_compaction_throttled, user_key_possibly_outside_job). Tested by tombstone_compacted_to_bottom_does_not_resurrect_unmerged_put (src/storage/compaction.rs, tests), overwrite_and_delete_survive_compaction_and_sstable_only_restart (src/storage/property_oracle_tests.rs) and dropped_namespace_data_purged_across_flush_compaction_and_restart (src/storage/namespaced.rs, tests).

Because tombstones are dropped only on the way into L6, and the per-level trigger for L5 is about 100,000 MiB, the background scheduler rarely reaches that step on its own. The forced paths below compact every level regardless of triggers and are what normally carries tombstones to the bottom (source: src/storage/compaction.rs, needs_compaction, force_compaction_locked; src/storage/mod.rs, compact_all).

MVCC versions

Compaction keeps exactly one version per user key: the newest. It does not read the snapshot watermark. The memtable keeps older versions while a snapshot older than the overwrite is live (MemTable::insert_versioned), and a flush writes those versions to L0, but the first compaction over that key drops them. A comment in the merge loop calls this the one unsupported case: a REPEATABLE READ or SERIALIZABLE snapshot that stays open across a compaction of a key it overwrote. The suggested fix (keep versions down to the newest one at or below the watermark) is deferred (source: src/storage/compaction.rs, execute_compaction_throttled; src/storage/memtable.rs, insert_versioned). See MVCC and Memtable. Not verified: no test runs a compaction under a live snapshot.

Forced and full compaction

Entry point Throttled What it runs
StorageEngine::force_compaction(level) No One pick_compaction(level) + merge, then refresh_levels_from_manifest
StorageEngine::compact_all() No One forced job for each level 0 to 5, in order, then refresh
StorageEngine::compact_full() (VACUUM FULL) No flush(), then compact_all up to 16 passes, stopping when the SSTable count stops falling; returns (before, after)
Size-amplification trigger Yes Up to 16 passes of a forced job per level, same stop rule
StorageEngine::compact_for_size_amp_now(min_garbage) Yes flush(), then the size-amplification check with no cooldown

(source: src/storage/mod.rs, force_compaction, compact_all, compact_full, compact_for_size_amp_now, maybe_compact_for_size_amp; src/storage/compaction.rs, force_compaction_locked, force_compaction_locked_throttled)

A forced job is taken whether or not the level is over its trigger, as long as the level has a file (source: src/storage/compaction.rs, force_compaction_locked, pick_compaction).

The PostgreSQL wire maps VACUUM FULL, VACUUM (FULL and VACUUM(FULL to compact_full and returns an empty result; other VACUUM forms are accepted and do nothing (source: src/query/engine.rs, the VACUUM FULL branch). Readers are not blocked during it.

CompactionManager::compact_all (the manager's own method, which loops while a level is over its trigger) has no caller in the engine; StorageEngine::compact_all drives the levels itself (source: src/storage/compaction.rs, compact_all; src/storage/mod.rs, compact_all).

Size-amplification trigger

Every 50 ticks of the flush loop (about 5 s), maybe_compact_for_size_amp computes over all manifest SSTables:

  • total bytes, largest file bytes, garbage = total - largest.

It runs a throttled full merge when all of these hold: compaction_size_amp_ratio > 0, at least 2 files, garbage >= 64 MiB (SIZE_AMP_MIN_GARBAGE_BYTES), garbage >= largest x ratio, and the cooldown since the previous merge has passed (source: src/storage/mod.rs, maybe_compact_for_size_amp, sstable_size_amplification, SIZE_AMP_MIN_GARBAGE_BYTES).

Cooldown: after a merge that reclaimed at least a quarter of garbage, 10 minutes (SIZE_AMP_BASE_COOLDOWN); otherwise double the previous cooldown, capped at 24 hours (SIZE_AMP_MAX_COOLDOWN). The cooldown is held in the flush loop, so it restarts with the process (source: src/storage/mod.rs, size_amp_next_cooldown, background_flush_loop). The doc comment explains the back-off: right after a bulk load the smaller files are live data, and one such merge ran 72 s to reclaim 11 MB.

The merge runs on the flush thread, so no memtable is flushed by the background loop while it runs; writers that fill the immutable queue flush synchronously (see Memtable) (source: src/storage/mod.rs, background_flush_loop, rotate_memtable_locked).

Tested by size_amplification_triggers_a_full_merge_and_keeps_the_data and ratio_zero_disables_the_trigger (tests/size_amp_compaction.rs) and size_amp_cooldown_backs_off_when_a_merge_does_not_pay (src/storage/mod.rs).

Throttling

CompactionThrottle is a token bucket. CompactionManager::new, which the engine uses, installs the default CompactionThrottleConfig:

Field Default Meaning
bytes_per_second 50 MiB/s Refill rate; 0 means unlimited
adaptive true Apply the peak-hours multiplier
peak_hours_multiplier 0.5 Rate factor during peak hours
peak_start_hour / peak_end_hour 9 / 17 Peak window in the server's local time (chrono::Local); a start after the end wraps midnight
min_bytes_per_second 1 MiB/s Floor for the adaptive rate

(source: src/storage/compaction.rs, CompactionThrottleConfig::default, CompactionThrottle::effective_rate)

So a background merge runs at up to 25 MiB/s from 09:00 to 17:00 local time and 50 MiB/s otherwise. The bucket holds at most one second of tokens. acquire(bytes) consumes the request in bucket-sized chunks, sleeping between 1 and 100 ms per wait; the comment records that a request larger than the bucket once made a worker sleep forever while holding the compaction lock (source: src/storage/compaction.rs, refill_tokens, acquire). Tested by test_throttle_config_default, test_throttle_unlimited, test_throttle_acquire and test_throttle_acquire_larger_than_bucket_completes (src/storage/compaction.rs, tests).

The throttle counts input bytes once up front and output bytes during the merge, so a job is charged for both (source: src/storage/compaction.rs, execute_compaction_throttled).

None of these fields has a config key or environment variable. set_throttle_config and without_throttle exist but have no caller outside compaction.rs (source: src/storage/compaction.rs, set_throttle_config, without_throttle). Not verified: the peak-hours behaviour has no test.

Configuration summary

Knob Default Where set
compaction_size_amp_ratio 0.5; 0 disables [storage] key, or SYNERGYDB_COMPACTION_SIZE_AMP
L0 file trigger 4 Code only (LevelConfig)
L1 size 10 MiB Code only
level_ratio 10 Code only
num_levels 7 Code only
Worker threads 2 (serialized by one lock) Code only (CompactionManager::start(2))
Job queue 100 Code only
Throttle 50 MiB/s, 25 MiB/s from 09:00 to 17:00 Code only
Size-amp floor / cooldown 64 MiB / 10 min to 24 h Code only
block_size, compression 4096, LZ4 [storage]; apply to compaction output too

(source: src/config.rs, StorageConfigFile::to_storage_config; src/storage/mod.rs, StorageConfig::default, StorageEngine::open; src/storage/compaction.rs)

Observability

CompactionStats (via StorageEngine::compaction_stats()) counts compactions, bytes read and written, entries processed and dropped, trivial moves, and time spent throttled. Each merged job (not a trivial move) also updates the Prometheus metrics synergydb_compactions_total, synergydb_compaction_duration_seconds, synergydb_bytes_read_total and synergydb_bytes_written_total (source: src/storage/compaction.rs, CompactionStats; src/storage/mod.rs, compaction_stats; src/observability/metrics.rs, record_compaction). compaction_stats() has no caller outside the storage module. Size-amplification merges and VACUUM FULL log one info line each with before and after file counts.

Not wired

Not wired: MergeIterator (used only by test_merge_iterator), has_orphaned_delete_files, CompactionManager::compact_all, set_throttle_config and without_throttle have no caller outside src/storage/compaction.rs (source: src/storage/compaction.rs).

Tests

Besides the tests named above: flushed_and_compacted_sstables_reopen_intact (src/storage/mod.rs, durability_review_fix_tests), lsm_oracle_thorough_wal_drop_and_compaction (src/storage/property_oracle_tests.rs), large_storage_compaction_correctness (tests/large_data.rs) and upgrade_sstable_compaction_preserves_data (tests/upgrade_path.rs). STATUS.md lists "LSM compaction under load" as correctness ok, performance untested (source: STATUS.md).