use miette::{IntoDiagnostic, Result}; use std::cell::RefCell; use std::collections::HashSet; use super::schema::Sampler; use super::{Db, registry}; impl Db { pub fn train_dict(&self, ks_name: &str) -> Result<()> { let Some((name, cfg)) = registry::trainable() .into_iter() .find(|(name, _)| *name == ks_name) else { miette::bail!("unknown keyspace for training: {ks_name}"); }; let ks = self .keyspace_by_name(name) .expect("trainable keyspace is registered"); tracing::info!("collecting training samples for keyspace {ks_name}..."); let samples: Vec> = match cfg.sampler { Sampler::PerCollectionCap(per_collection_limit) => { use lsm_tree::SampleVerdict; // prefix-hop by collection: seek to the start of each collection, // take up to `per_collection_limit` blocks, then seek past it. // blocks past the cap are never read, unlike a sequential scan // with a rejecting predicate (which decompresses every block). let mut samples: Vec> = Vec::new(); let mut start: Option> = None; let mut last_log = std::time::Instant::now(); while samples.len() < cfg.samples { let prefix = RefCell::new(Option::>::None); let remaining = cfg.samples - samples.len(); let batch = ks .sample_data_blocks_from( start.as_deref(), per_collection_limit.min(remaining), |first, _last| { let Some(sep_idx) = first.iter().position(|&b| b == super::keys::SEP) else { return SampleVerdict::Exclude; }; let mut prefix = prefix.borrow_mut(); match &*prefix { None => { *prefix = Some(first[..=sep_idx].to_vec()); SampleVerdict::Include } Some(current) if first.starts_with(current) => { SampleVerdict::Include } Some(_) => SampleVerdict::Abort, } }, ) .into_diagnostic()?; if batch.is_empty() { break; } samples.extend(batch.into_iter().map(|s| s.to_vec())); let Some(prefix) = prefix.into_inner() else { break; }; // `{prefix}` ends in SEP; SEP + 1 sorts after every key of this // collection but before any later collection's keys let mut next = prefix; *next.last_mut().expect("prefix ends in SEP") += 1; start = Some(next); if last_log.elapsed() >= std::time::Duration::from_secs(5) { tracing::info!( "collected {}/{} samples for {ks_name}...", samples.len(), cfg.samples, ); last_log = std::time::Instant::now(); } } samples } Sampler::DedupKeys => { let mut seen_keys = HashSet::new(); let captured_keys = RefCell::new(Vec::new()); let progress = RefCell::new((std::time::Instant::now(), 0)); let new = ks .sample_data_blocks(cfg.samples, |first, last| { let passes = !seen_keys.contains(&(first.to_vec(), last.to_vec())); if passes { captured_keys .borrow_mut() .push((first.to_vec(), last.to_vec())); } let mut p = progress.borrow_mut(); if passes { p.1 += 1; } if p.0.elapsed() >= std::time::Duration::from_secs(5) { tracing::info!( "collected {}/{} samples for {}...", p.1, cfg.samples, ks_name ); p.0 = std::time::Instant::now(); } passes }) .into_diagnostic()?; new.into_iter() .zip(captured_keys.into_inner()) .filter_map(|(s, keys)| seen_keys.insert(keys).then_some(s.to_vec())) .collect() } }; if samples.is_empty() { miette::bail!("no samples found for keyspace {ks_name}, skipping training"); } tracing::info!( "training zstd dictionary for keyspace {ks_name} ({} samples, {} bytes limit)...", samples.len(), cfg.dict_size, ); let dict_bytes = lsm_tree::train_zstd_dict(&samples, cfg.dict_size as usize).into_diagnostic()?; let path = self.path.join(format!("dict_{ks_name}.bin")); std::fs::write(&path, &dict_bytes).into_diagnostic()?; tracing::info!( "saved zstd dictionary for keyspace {ks_name} ({} bytes) to {}. please restart the indexer to use the new dictionary.", dict_bytes.len(), path.display() ); Ok(()) } } #[cfg(all(test, feature = "indexer"))] mod tests { use crate::config::Config; use crate::db::{Db, keys}; use miette::{IntoDiagnostic, Result}; #[tokio::test] async fn test_train_dict_per_collection_seeking() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = Config { database_path: tmp.path().to_path_buf(), ..Config::default() }; let db = Db::open(&cfg)?; // stage blocks across two collections let mut batch = db.inner.batch(); for i in 0..10u8 { db.indexer.stage_block( &mut batch, keys::indexer::block_key("a.a.b.c", &[i]), vec![i; 64], ); db.indexer.stage_block( &mut batch, keys::indexer::block_key("z.z.y.x", &[i]), vec![100 + i; 64], ); } batch.commit().into_diagnostic()?; // sampling skips L0, so flush the memtable and compact everything down db.indexer .blocks .rotate_memtable_and_wait() .into_diagnostic()?; db.compact().await?; db.train_dict("blocks")?; assert!(tmp.path().join("dict_blocks.bin").exists()); Ok(()) } }