Skip to main content

ledger_engine/
coldversions.rs

1//! Measures what an index "object to the ledgers that changed it" over cold
2//! history would take, and how an object at an old ledger reads through it.
3//! Writes nothing to the store.
4//!
5//! The candidate format stores, for each key, the ledgers as ascending deltas in
6//! varints. A ledger number is enough to find the row, so no pointer into a
7//! segment is kept: the price is decoding that row on every read, and this
8//! measures the price too.
9
10use std::collections::HashMap;
11use std::io::Write;
12use std::time::Instant;
13
14use serde_json::{Value, json};
15
16use crate::cold::Cold;
17use crate::varint;
18
19type Hash = [u8; 32];
20
21/// Size of the blocks the encoded index is compressed in, as it would be read.
22const BLOCK: usize = 64 << 10;
23/// What a pointer into a segment costs per version: segment and offset.
24const POINTER: u64 = 12;
25
26/// Appends ascending `seqs` as deltas in varints; the first is absolute.
27pub fn put_list(out: &mut Vec<u8>, seqs: &[u32]) {
28    let mut last = 0;
29    for &s in seqs {
30        varint::put(out, u64::from(s - last));
31        last = s;
32    }
33}
34
35/// The ledger that holds a key's version at `at`: the last one not after it.
36pub fn version_at(seqs: &[u32], at: u32) -> Option<u32> {
37    match seqs.partition_point(|&s| s <= at) {
38        0 => None,
39        n => Some(seqs[n - 1]),
40    }
41}
42
43/// How many partitions of `every` ledgers a key's ascending list touches.
44pub fn partitions_of(seqs: &[u32], every: u32) -> u64 {
45    let mut n = 0;
46    let mut last = None;
47    for s in seqs {
48        let p = s / every;
49        if last != Some(p) {
50            n += 1;
51            last = Some(p);
52        }
53    }
54    n
55}
56
57/// Small deterministic generator: a measurement should be repeatable.
58struct Rng(u64);
59
60impl Rng {
61    fn below(&mut self, n: u64) -> u64 {
62        self.0 ^= self.0 << 13;
63        self.0 ^= self.0 >> 7;
64        self.0 ^= self.0 << 17;
65        self.0 % n.max(1)
66    }
67}
68
69fn percentiles(mut ms: Vec<f64>) -> Value {
70    ms.sort_unstable_by(f64::total_cmp);
71    let at = |q: f64| {
72        ms.get(((ms.len() as f64 * q) as usize).min(ms.len().saturating_sub(1)))
73            .copied()
74            .unwrap_or(0.0)
75    };
76    json!({
77        "n": ms.len(),
78        "p50_ms": at(0.5),
79        "p90_ms": at(0.9),
80        "p99_ms": at(0.99),
81        "max_ms": ms.last().copied().unwrap_or(0.0),
82    })
83}
84
85/// What to measure.
86#[derive(Debug, Clone, Copy)]
87pub struct Window {
88    /// First ledger.
89    pub from: u32,
90    /// Last ledger.
91    pub to: u32,
92    /// Ledgers read at random before the pass, while they are the least cached.
93    pub random_reads: usize,
94    /// Objects read through the index after the pass.
95    pub lookups: usize,
96    /// Size of the partitions whose cost is reported.
97    pub partition: u32,
98}
99
100/// Measures one window. `sample` gets each object read through the index: key,
101/// ledger asked, ledger found and the object, empty if deleted there.
102pub fn measure(
103    cold: &Cold,
104    w: Window,
105    mut sample: impl FnMut(&Hash, u32, u32, &[u8]),
106) -> Result<Value, String> {
107    if w.from > w.to || !cold.contains(w.from) || !cold.contains(w.to) {
108        return Err(format!("{}..={} is not in the cold history", w.from, w.to));
109    }
110    let span = u64::from(w.to - w.from) + 1;
111    let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ u64::from(w.from));
112
113    let mut times = Vec::with_capacity(w.random_reads);
114    for _ in 0..w.random_reads {
115        let seq = w.from + rng.below(span) as u32;
116        let t = Instant::now();
117        cold.patches(seq)?
118            .ok_or(format!("ledger {seq} is missing"))?;
119        times.push(t.elapsed().as_secs_f64() * 1e3);
120    }
121    let random = percentiles(times);
122
123    let t = Instant::now();
124    let mut lists: HashMap<Hash, Vec<u32>> = HashMap::new();
125    let mut versions = 0u64;
126    let mut data = 0u64;
127    for seq in w.from..=w.to {
128        let (_, patches) = cold
129            .patches(seq)?
130            .ok_or(format!("ledger {seq} is missing"))?;
131        versions += patches.len() as u64;
132        for (key, object) in patches {
133            data += object.len() as u64;
134            lists.entry(key).or_default().push(seq);
135        }
136        if u64::from(seq - w.from + 1).is_multiple_of(500_000) {
137            eprintln!("{seq}: {versions} versions, {} keys", lists.len());
138        }
139    }
140    let pass = t.elapsed().as_secs_f64();
141
142    let mut keys: Vec<Hash> = lists.keys().copied().collect();
143    keys.sort_unstable();
144
145    let t = Instant::now();
146    let mut seq_bytes = 0u64;
147    let mut partition_keys = 0u64;
148    let mut stream = Vec::with_capacity(BLOCK * 2);
149    let mut compressed = 0u64;
150    let mut counts = Vec::with_capacity(keys.len());
151    let mut flush = |stream: &mut Vec<u8>| -> Result<(), String> {
152        let mut z = zstd::Encoder::new(Vec::new(), 3).map_err(|e| e.to_string())?;
153        z.write_all(stream).map_err(|e| e.to_string())?;
154        compressed += z.finish().map_err(|e| e.to_string())?.len() as u64;
155        stream.clear();
156        Ok(())
157    };
158    let mut list = Vec::new();
159    for key in &keys {
160        let seqs = &lists[key];
161        counts.push(seqs.len() as u64);
162        partition_keys += partitions_of(seqs, w.partition);
163        list.clear();
164        put_list(&mut list, seqs);
165        seq_bytes += list.len() as u64;
166        stream.extend_from_slice(key);
167        varint::put(&mut stream, seqs.len() as u64);
168        stream.extend_from_slice(&list);
169        if stream.len() >= BLOCK {
170            flush(&mut stream)?;
171        }
172    }
173    flush(&mut stream)?;
174    let encode = t.elapsed().as_secs_f64();
175    counts.sort_unstable();
176    let count_at = |q: f64| {
177        counts
178            .get(((counts.len() as f64 * q) as usize).min(counts.len().saturating_sub(1)))
179            .copied()
180            .unwrap_or(0)
181    };
182
183    let mut times = Vec::with_capacity(w.lookups);
184    let mut sizes = Vec::with_capacity(w.lookups);
185    for _ in 0..w.lookups {
186        let Some(key) = keys.get(rng.below(keys.len() as u64) as usize) else {
187            break;
188        };
189        let seqs = &lists[key];
190        let at = seqs[0] + rng.below(u64::from(w.to - seqs[0]) + 1) as u32;
191        let t = Instant::now();
192        let seq = version_at(seqs, at).ok_or("no version")?;
193        let (_, patches) = cold
194            .patches(seq)?
195            .ok_or(format!("ledger {seq} is missing"))?;
196        let object = patches
197            .iter()
198            .find(|(k, _)| k == key)
199            .ok_or(format!("ledger {seq} has no change of a key listed for it"))?;
200        times.push(t.elapsed().as_secs_f64() * 1e3);
201        sizes.push(patches.len() as f64);
202        sample(key, at, seq, &object.1);
203    }
204
205    let k = keys.len() as u64;
206    Ok(json!({
207        "from": w.from,
208        "to": w.to,
209        "versions": versions,
210        "keys": k,
211        "object_bytes": data,
212        "pass_seconds": pass,
213        "encode_seconds": encode,
214        "versions_per_key": {
215            "p50": count_at(0.5),
216            "p90": count_at(0.9),
217            "p99": count_at(0.99),
218            "p999": count_at(0.999),
219            "max": counts.last().copied().unwrap_or(0),
220        },
221        "sizes": {
222            "seq_varint_bytes": seq_bytes,
223            "keys_32_bytes": k * 32,
224            "raw_list_format": seq_bytes + k * 32,
225            "zstd_64k_blocks": compressed,
226            "with_pointers": versions * POINTER + k * 32,
227            "partition_ledgers": w.partition,
228            "partition_key_entries": partition_keys,
229            "per_version": {
230                "raw_list_format": (seq_bytes + k * 32) as f64 / versions.max(1) as f64,
231                "zstd_64k_blocks": compressed as f64 / versions.max(1) as f64,
232                "with_pointers": (versions * POINTER + k * 32) as f64 / versions.max(1) as f64,
233            },
234        },
235        "random_row_read": random,
236        "object_read_through_index": percentiles(times),
237        "patches_in_rows_read": percentiles(sizes),
238    }))
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn varints_take_the_expected_room() {
247        let mut out = Vec::new();
248        put_list(&mut out, &[100, 101, 400, 400 + (1 << 14)]);
249        // 100, then 1, then 299 in two bytes, then 2^14 in three.
250        assert_eq!(out, [100, 1, 0xAB, 0x02, 0x80, 0x80, 0x01]);
251    }
252
253    #[test]
254    fn the_version_at_a_ledger_is_the_last_not_after_it() {
255        let seqs = [10, 20, 30];
256        assert_eq!(version_at(&seqs, 9), None);
257        assert_eq!(version_at(&seqs, 10), Some(10));
258        assert_eq!(version_at(&seqs, 29), Some(20));
259        assert_eq!(version_at(&seqs, 31), Some(30));
260    }
261
262    #[test]
263    fn partitions_are_counted_once_each() {
264        assert_eq!(partitions_of(&[1, 2, 99, 100, 250], 100), 3);
265        assert_eq!(partitions_of(&[], 100), 0);
266    }
267}