vercel/next.js · #101796

turbo-persistence: keep used keys across intermediate merges

sokra · merged Nov 15, 20263 files · 167 + / 6 −
turbopack/crates/turbo-persistence/README.md2 + / 2 −
@@ -78,7 +78,7 @@ A meta file can contain metadata about multiple SST files. The metadata is store   - 4 bytes end of AMQF offset relative to start of all AMQF data of the "used key hashes" AMQF - foreach described SST file   - serialized AMQF-- serialized "used key hashes" AMQF: the keys read since the previous commit (only in meta files written by a commit)+- serialized "used key hashes" AMQF: the keys read since the previous commit in a meta file written by a commit, or the used keys carried forward by intermediate merges in a meta file written by compaction  ### SST file @@ -421,7 +421,7 @@ The key space of each family is split into a power-of-two number of shards by th - A bottom merge merges all files of a shard into a new bottom run, dropping superseded entries and tombstones. It runs when the files above the bottom run exceed `max_space_amplification_percent` of the bottom run, counting each tombstone as an average bottom entry since it deletes one. This bounds the space amplification. - An intermediate merge merges files above the bottom run when there are more than `max_files_above_bottom`, to bound the number of files a lookup consults. Like RocksDB's universal compaction, it takes the newest file and then each next older one that is at most `size_ratio_percent` larger than the files taken so far (but at least the two newest), so small files from small commits are merged with each other without rewriting larger files written before them. -A bottom merge writes the entries of recently read keys (the union of the "used key hashes" AMQFs of all meta files) into separate hot SST files, and the rest into cold ones. Processes tend to read the same keys again, so this packs them into fewer blocks, which matters on storage where reads are expensive. Since a bottom merge always includes the whole shard, hot and cold files are merged together and every version of a key meets. The used keys are never copied into the meta files written by compaction, so they expire once all SST files of the commit that recorded them are merged.+A bottom merge writes the entries of recently read keys (the union of the "used key hashes" AMQFs of all meta files) into separate hot SST files, and the rest into cold ones. Processes tend to read the same keys again, so this packs them into fewer blocks, which matters on storage where reads are expensive. Since a bottom merge always includes the whole shard, hot and cold files are merged together and every version of a key meets. The used keys expire once all SST files of the commit that recorded them are bottom merged: an intermediate merge (e.g. of a shard whose bottom merge was left for later by the rewrite quota or `max_merge_jobs`) copies the used keys of the meta files of its input files into the meta file written by the compaction, so they expire once that meta file's SST files are merged. When that meta file also describes bottom merge or move outputs of the same compaction, the used keys live until those are merged too. A bottom merge doesn't copy them.  Bottom merges are paced by the fresh (not yet compacted) files of the family: they are scheduled until they rewrote `rewrite_per_fresh_byte` times the size of those files (the last one may go past it, and the first one always runs), so compaction cost follows the amount of new data. Since keys are hashes, shards grow at the same rate; the rewrite quota spreads their bottom merges over multiple compactions. A skipped compaction leaves the fresh files in place, which increases the next quota. The default is 3: a bottom merge at the 50% trigger rewrites 1.5 times the bytes above the bottom run for each 0.5 of them, so in steady state a written byte is copied about 3 times. A shard over twice the trigger, or with over twice `max_files_above_bottom` files above its bottom run, is bottom merged even when the quota is reached, which bounds how far a shard can fall behind (e.g. after a GC purge, whose small tombstone files give a small quota). 
turbopack/crates/turbo-persistence/src/db.rs33 + / 4 −
@@ -1681,8 +1681,9 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>                     };                      // The keys read recently: the used keys of the meta files written by commits-                    // that are still alive, i.e. whose SST files were not all merged yet. We only-                    // capture this for bottom compactions.+                    // that are still alive, i.e. whose SST files were not all merged yet, and the+                    // ones carried forward by intermediate merges (see below). We only capture+                    // this for bottom compactions.                     let used_key_hashes = if merge_jobs.iter().any(|job| {                         job.bottom                             && (job.members.len() > 1 || !sst_strictly_in_shard(job.members[0]))@@ -1692,6 +1693,29 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>                         None                     }; +                    // An intermediate merge can merge the last SST file of a commit that recorded+                    // used keys, which retires its meta file, while the merged entries are not+                    // bottom merged yet, e.g. when the rewrite quota or `max_merge_jobs` leaves+                    // the bottom merge of their shard for later. The new meta file therefore+                    // carries the used keys of the meta files of all intermediate merge inputs+                    // forward, so that a later bottom merge still knows them. They are carried+                    // even if such a meta file stays alive, as it can be retired later by a merge+                    // of other files, e.g. by the bottom merge of another shard, while the outputs+                    // still need them. When the new meta file also describes bottom merge or move+                    // outputs, the used keys live until those are merged too, which only makes+                    // some cold entries hot for longer.+                    let carried_used_key_hashes = {+                        let mut meta_indices = merge_jobs+                            .iter()+                            .filter(|job| !job.bottom)+                            .flat_map(|job| job.members.iter())+                            .map(|&index| ssts_with_ranges[index].meta_index)+                            .collect::<Vec<_>>();+                        meta_indices.sort_unstable();+                        meta_indices.dedup();+                        union_used_key_hashes(meta_indices.into_iter().map(|i| &meta_files[i]))?+                    };+                     // Later we will remove the merged files. Capture each one's size now (we know                     // exactly which SST it is) so `commit` can report deleted bytes without a scan.                     let sst_files_to_delete = merge_jobs@@ -2192,6 +2216,9 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>                     for f in sst_files_to_delete.iter() {                         meta_file_builder.add_obsolete_sst_file(f.seq);                     }+                    if let Some(used_key_hashes) = carried_used_key_hashes {+                        meta_file_builder.set_used_key_hashes_amqf(used_key_hashes);+                    }                      let new_meta_file = {                         let _span = tracing::trace_span!("write meta file").entered();@@ -2806,9 +2833,11 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> const USED_KEYS_FINGERPRINT_BITS: u8 = 32;  /// The union of the used keys recorded in the meta files, or `None` if there are none.-fn union_used_key_hashes(meta_files: &[MetaFile]) -> Result<Option<qfilter::Filter>> {+fn union_used_key_hashes<'l>(+    meta_files: impl IntoIterator<Item = &'l MetaFile>,+) -> Result<Option<qfilter::Filter>> {     let filters = meta_files-        .iter()+        .into_iter()         .filter_map(|meta_file| meta_file.deserialize_used_key_hashes_amqf().transpose())         .collect::<Result<Vec<_>>>()?         .into_iter()
turbopack/crates/turbo-persistence/src/tests.rs132 + / 0 −
@@ -3192,6 +3192,138 @@ fn used_keys_live_as_long_as_the_meta_file_that_recorded_them(#[case] mmap: bool     Ok(()) } +/// How [`used_keys_survive_intermediate_merges`] leaves the bottom merge of a shard for later.+#[cfg(not(miri))]+#[derive(Clone, Copy, Debug)]+enum PartialCompaction {+    /// One pass bottom merges one shard and intermediate merges the other.+    SamePass,+    /// One pass bottom merges one shard, a later one intermediate merges the other.+    BottomFirst,+    /// One pass intermediate merges one shard, while the meta file that recorded the used keys is+    /// kept alive by the other shard's files. A later pass bottom merges that other shard, which+    /// retires it.+    IntermediateFirst,+}++/// An intermediate merge can retire the meta file that recorded the used keys before every shard+/// had its bottom merge, e.g. when the rewrite quota or `max_merge_jobs` leaves a shard's bottom+/// merge for later. The used keys then have to live on in the meta file written by the compaction,+/// until the merged entries are bottom merged.+#[cfg(not(miri))]+#[rstest]+fn used_keys_survive_intermediate_merges(+    #[values(true, false)] mmap: bool,+    #[values(+        PartialCompaction::SamePass,+        PartialCompaction::BottomFirst,+        PartialCompaction::IntermediateFirst+    )]+    partial: PartialCompaction,+) -> Result<()> {+    let tempdir = tempfile::tempdir()?;+    let path = tempdir.path();+    let config = two_shard_config(mmap)?;+    let db = open_db_with_config::<1>(path, config.clone())?;+    const KEYS: u32 = TWO_SHARD_KEYS;+    let put_all =+        |db: &TurboPersistence<RayonParallelScheduler, 1>, generation: u32| -> Result<()> {+            let batch = db.write_batch()?;+            for key in 0..KEYS {+                batch.put(+                    0,+                    key.to_be_bytes().to_vec(),+                    generation.to_be_bytes().to_vec().into(),+                )?;+            }+            db.commit_write_batch(batch)?;+            Ok(())+        };+    put_all(&db, 0)?;+    db.full_compact()?;+    for key in 0..KEYS {+        db.get(0, &key.to_be_bytes())?.unwrap();+    }+    // The first commit records the reads, the second one none. Each shard has two files above its+    // bottom run then.+    put_all(&db, 1)?;+    put_all(&db, 2)?;+    let intermediate_only = CompactConfig {+        max_space_amplification_percent: u16::MAX,+        max_files_above_bottom: 1,+        ..CompactConfig::full()+    };+    match partial {+        PartialCompaction::BottomFirst => {+            // Bottom merge only one shard. The other shard keeps the files of the commit that+            // recorded the used keys.+            db.compact(&CompactConfig {+                max_merge_jobs: 1,+                ..CompactConfig::full()+            })?;+            // Then the other shard gets an intermediate merge instead of a bottom merge, which+            // merges the last file of that commit.+            db.compact(&intermediate_only)?;+        }+        PartialCompaction::SamePass => {+            // The rewrite quota of 0 bottom merges only one shard, and the other one gets an+            // intermediate merge in the same pass, which merges the last file of that commit.+            db.compact(&CompactConfig {+                max_files_above_bottom: 1,+                rewrite_per_fresh_byte: 0.0,+                ..CompactConfig::full()+            })?;+        }+        PartialCompaction::IntermediateFirst => {+            // Intermediate merge only one shard. The commit that recorded the used keys still has+            // a file in the other shard.+            db.compact(&CompactConfig {+                max_merge_jobs: 1,+                ..intermediate_only+            })?;+            // Bottom merge only the other shard, which merges the last file of that commit. It+            // has two rewrites of all its keys above its bottom run, the merged shard only one.+            db.compact(&CompactConfig {+                max_space_amplification_percent: 150,+                max_files_above_bottom: 6,+                ..CompactConfig::full()+            })?;+        }+    }+    let (hot, _) = bottom_entry_counts(&db)?;+    assert!(hot > 0 && hot < KEYS as usize);+    // The carried used keys are persisted.+    db.shutdown();+    let db = open_db_with_config::<1>(path, config)?;+    // The bottom merge of the other shard still knows the read keys.+    db.full_compact()?;+    assert_eq!(bottom_entry_counts(&db)?, (KEYS as usize, 0));++    // Every file with entries of the read keys was bottom merged now, so the used keys expire. (No+    // key was read since, which the next commit would record again.)+    let mut generation = 3;+    if matches!(partial, PartialCompaction::SamePass) {+        // Except that the meta file carrying the used keys also describes the bottom run written+        // by the same pass for the first shard, which the full compaction above didn't merge, as+        // nothing was written into that shard since. So the next bottom merge still uses them,+        // which merges that bottom run and retires the meta file.+        put_all(&db, generation)?;+        db.full_compact()?;+        assert_eq!(bottom_entry_counts(&db)?, (KEYS as usize, 0));+        generation += 1;+    }+    put_all(&db, generation)?;+    db.full_compact()?;+    assert_eq!(bottom_entry_counts(&db)?, (0, KEYS as usize));+    for key in 0..KEYS {+        assert_eq!(+            &*db.get(0, &key.to_be_bytes())?.unwrap(),+            &generation.to_be_bytes()+        );+    }+    Ok(())+}+ #[cfg(not(miri))] #[rstest] #[case(true)]