Skip to main content

zu_encoding/
alp_rd.rs

1//! ALP_RD for doubles (encoding id 7), the fallback for "real doubles"
2//! whose mantissas actually use their bits, where the decimal transform
3//! of plain ALP fails on everything. The observation from the paper is
4//! that such columns still share their front: sign, exponent and the
5//! top mantissa bits cluster on a handful of patterns. Each 64-bit
6//! pattern splits at a trained cut into a left part that dictionary
7//! encodes (at most 8 entries, 3-bit codes) and a right part stored
8//! packed as-is, so a coordinate column in radians drops its shared
9//! bits while staying bit-exact. Left parts beyond the dictionary ride
10//! as patched exceptions.
11//!
12//! The cut is chosen on a sample: every left width from 1 to 16 bits is
13//! scored by packed right width plus dictionary code width plus the
14//! exception tax, smallest estimate wins.
15//!
16//! Layout: `count: u32 LE`, `right_bits: u8`, `dict_len: u8`, dict
17//! entries (u16 LE each), `exc_count: u32 LE`, `positions_len: u32 LE`,
18//! positions container, exception left values (u16 LE each), left codes
19//! container, then the right parts container.
20
21use zu_common::{Result, ZuError};
22
23use crate::bitpack::CHUNK;
24use crate::for_bitpack;
25
26const MAX_DICT: usize = 8;
27const MAX_LEFT_BITS: usize = 16;
28
29/// Top `MAX_DICT` left parts by frequency for a given cut, most common
30/// first, ties broken by value so training is deterministic.
31fn build_dict(values: &[f64], right_bits: u32) -> Vec<u16> {
32    let mut counts = std::collections::HashMap::new();
33    for &d in values {
34        *counts
35            .entry((d.to_bits() >> right_bits) as u16)
36            .or_insert(0u64) += 1;
37    }
38    let mut pairs: Vec<(u16, u64)> = counts.into_iter().collect();
39    pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
40    pairs.truncate(MAX_DICT);
41    pairs.into_iter().map(|(left, _)| left).collect()
42}
43
44/// Scores every cut on an evenly spaced sample: bits per value for the
45/// packed right part and the dictionary code, plus the exception tax
46/// for left parts outside the top eight.
47fn choose_cut(values: &[f64]) -> u32 {
48    let step = (values.len() / 1024).max(1);
49    let sample: Vec<f64> = values.iter().step_by(step).copied().collect();
50    let mut best_bits = 64 - MAX_LEFT_BITS as u32;
51    let mut best_score = u64::MAX;
52    for left_bits in 1..=MAX_LEFT_BITS as u32 {
53        let right_bits = 64 - left_bits;
54        let dict = build_dict(&sample, right_bits);
55        let exceptions = sample
56            .iter()
57            .filter(|d| !dict.contains(&((d.to_bits() >> right_bits) as u16)))
58            .count() as u64;
59        let code_bits = u64::from(crate::bits_needed(dict.len().saturating_sub(1) as u64));
60        let score = sample.len() as u64 * (u64::from(right_bits) + code_bits) + exceptions * 48;
61        if score < best_score {
62            best_score = score;
63            best_bits = right_bits;
64        }
65    }
66    best_bits
67}
68
69/// Encodes `values` into `out`, returning the encoded byte length.
70pub fn encode(values: &[f64], out: &mut Vec<u8>) -> usize {
71    let start = out.len();
72    let right_bits = choose_cut(values);
73    let mut dict = build_dict(values, right_bits);
74    if dict.is_empty() {
75        // An empty input still writes a well-formed container, and the
76        // decoder insists on at least one dictionary entry.
77        dict.push(0);
78    }
79    let right_mask = if right_bits == 64 {
80        u64::MAX
81    } else {
82        (1u64 << right_bits) - 1
83    };
84    let mut codes = Vec::with_capacity(values.len());
85    let mut rights = Vec::with_capacity(values.len());
86    let mut positions = Vec::new();
87    let mut exc_lefts = Vec::new();
88    for (i, &d) in values.iter().enumerate() {
89        let bits = d.to_bits();
90        let left = (bits >> right_bits) as u16;
91        rights.push(bits & right_mask);
92        match dict.iter().position(|&l| l == left) {
93            Some(code) => codes.push(code as u64),
94            None => {
95                codes.push(0);
96                positions.push(i as u64);
97                exc_lefts.push(left);
98            }
99        }
100    }
101    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
102    out.push(right_bits as u8);
103    out.push(dict.len() as u8);
104    for &left in &dict {
105        out.extend_from_slice(&left.to_le_bytes());
106    }
107    out.extend_from_slice(&(positions.len() as u32).to_le_bytes());
108    let mut positions_buf = Vec::new();
109    for_bitpack::encode(&positions, &mut positions_buf);
110    out.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
111    out.extend_from_slice(&positions_buf);
112    for &left in &exc_lefts {
113        out.extend_from_slice(&left.to_le_bytes());
114    }
115    let mut codes_buf = Vec::new();
116    for_bitpack::encode(&codes, &mut codes_buf);
117    out.extend_from_slice(&(codes_buf.len() as u32).to_le_bytes());
118    out.extend_from_slice(&codes_buf);
119    for_bitpack::encode(&rights, out);
120    out.len() - start
121}
122
123/// Decodes an encoded buffer, appending at most `max_values` values to
124/// `out`. Every count is a claim checked against the caller ceiling and
125/// the streams, and a rejected payload leaves `out` untouched.
126pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<f64>) -> Result<()> {
127    let corrupt = |detail: &str| ZuError::Corrupt {
128        what: "alp_rd",
129        detail: detail.to_string(),
130    };
131    let header = bytes.get(..6).ok_or_else(|| corrupt("truncated header"))?;
132    let count = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
133    let right_bits = u32::from(header[4]);
134    let dict_len = header[5] as usize;
135    if count > max_values {
136        return Err(corrupt("count above the caller ceiling"));
137    }
138    if !(48..=63).contains(&right_bits) {
139        return Err(corrupt("cut outside 48..=63 right bits"));
140    }
141    if dict_len == 0 || dict_len > MAX_DICT {
142        return Err(corrupt("dictionary size outside 1..=8"));
143    }
144    let mut pos = 6;
145    let dict_bytes = bytes
146        .get(pos..pos + dict_len * 2)
147        .ok_or_else(|| corrupt("truncated dictionary"))?;
148    let dict: Vec<u64> = dict_bytes
149        .as_chunks::<2>()
150        .0
151        .iter()
152        .map(|c| u64::from(u16::from_le_bytes(*c)))
153        .collect();
154    pos += dict_len * 2;
155    let head = bytes
156        .get(pos..pos + 8)
157        .ok_or_else(|| corrupt("truncated exception header"))?;
158    let exc_count = u32::from_le_bytes(head[..4].try_into().unwrap()) as usize;
159    let positions_len = u32::from_le_bytes(head[4..8].try_into().unwrap()) as usize;
160    pos += 8;
161    if exc_count > count {
162        return Err(corrupt("more exceptions than values"));
163    }
164    let positions_bytes = bytes
165        .get(pos..pos + positions_len)
166        .ok_or_else(|| corrupt("truncated positions"))?;
167    pos += positions_len;
168    let exc_bytes = bytes
169        .get(pos..pos + exc_count * 2)
170        .ok_or_else(|| corrupt("truncated exception lefts"))?;
171    pos += exc_count * 2;
172    let codes_head = bytes
173        .get(pos..pos + 4)
174        .ok_or_else(|| corrupt("truncated code header"))?;
175    let codes_len = u32::from_le_bytes(codes_head.try_into().unwrap()) as usize;
176    pos += 4;
177    let codes_bytes = bytes
178        .get(pos..pos + codes_len)
179        .ok_or_else(|| corrupt("truncated codes"))?;
180    let rights_bytes = bytes
181        .get(pos + codes_len..)
182        .ok_or_else(|| corrupt("truncated rights"))?;
183    let mut positions = Vec::new();
184    for_bitpack::decode(positions_bytes, exc_count, &mut positions)?;
185    if positions.len() != exc_count {
186        return Err(corrupt("position stream length mismatch"));
187    }
188    if positions.iter().any(|&p| p >= count as u64) {
189        return Err(corrupt("position past the value count"));
190    }
191    let mut codes_cur = for_bitpack::ChunkCursor::new(codes_bytes, count)?;
192    let mut rights_cur = for_bitpack::ChunkCursor::new(rights_bytes, count)?;
193    if codes_cur.count() != count {
194        return Err(corrupt("code stream length mismatch"));
195    }
196    if rights_cur.count() != count {
197        return Err(corrupt("right stream length mismatch"));
198    }
199    // The two streams decode one MiniBlock chunk at a time and combine
200    // in the same pass, so nothing the size of the column materializes
201    // besides the output itself. The dictionary is padded to the code
202    // mask so the hot loop indexes without a bounds check, and hostile
203    // codes and stray right bits are caught by running accumulators
204    // checked once after the pass.
205    let mut dict_pad = [0u64; MAX_DICT];
206    dict_pad[..dict.len()].copy_from_slice(&dict);
207    let right_mask = (1u64 << right_bits) - 1;
208    let base = out.len();
209    let mut sc = [0u64; CHUNK];
210    let mut sr = [0u64; CHUNK];
211    let mut max_code = 0u64;
212    let mut stray = 0u64;
213    let bad = loop {
214        let (cmin, tc) = match codes_cur.next(&mut sc) {
215            Ok(Some(chunk)) => chunk,
216            Ok(None) => break None,
217            Err(e) => break Some(e),
218        };
219        let (rmin, tr) = match rights_cur.next(&mut sr) {
220            Ok(Some(chunk)) => chunk,
221            Ok(None) => break Some(corrupt("right stream ended early")),
222            Err(e) => break Some(e),
223        };
224        let take = tc.min(tr);
225        out.extend(sc[..take].iter().zip(&sr[..take]).map(|(&cv, &rv)| {
226            let c = cmin.wrapping_add(cv);
227            let r = rmin.wrapping_add(rv);
228            max_code = max_code.max(c);
229            stray |= r;
230            f64::from_bits(dict_pad[(c & (MAX_DICT as u64 - 1)) as usize] << right_bits | r)
231        }));
232    };
233    if let Some(e) = bad {
234        out.truncate(base);
235        return Err(e);
236    }
237    if max_code as usize >= dict_len {
238        out.truncate(base);
239        return Err(corrupt("code past the dictionary"));
240    }
241    if stray & !right_mask != 0 {
242        out.truncate(base);
243        return Err(corrupt("right part wider than the cut"));
244    }
245    for (&p, chunk) in positions.iter().zip(exc_bytes.as_chunks::<2>().0) {
246        let left = u64::from(u16::from_le_bytes(*chunk));
247        let slot = base + p as usize;
248        let bits = left << right_bits | (out[slot].to_bits() & right_mask);
249        out[slot] = f64::from_bits(bits);
250    }
251    Ok(())
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    fn radians() -> Vec<f64> {
259        // Coordinates through an irrational transform: full mantissas
260        // with a shared front, exactly the RD shape.
261        let mut rng = 0x9E3779B97F4A7C15u64;
262        (0..10_000)
263            .map(|_| {
264                rng ^= rng << 13;
265                rng ^= rng >> 7;
266                rng ^= rng << 17;
267                let deg = (rng % 360_0000000) as f64 / 1e7 - 180.0;
268                deg.to_radians()
269            })
270            .collect()
271    }
272
273    #[test]
274    fn roundtrip_shears_the_shared_front() {
275        let values = radians();
276        let mut buf = Vec::new();
277        let len = encode(&values, &mut buf);
278        assert!(
279            len * 10 < values.len() * 8 * 9,
280            "a shared front should shave at least 10 percent, got {len} from {}",
281            values.len() * 8
282        );
283        let mut out = Vec::new();
284        decode(&buf, values.len(), &mut out).unwrap();
285        assert_eq!(
286            values.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
287            out.iter().map(|v| v.to_bits()).collect::<Vec<_>>()
288        );
289    }
290
291    #[test]
292    fn roundtrip_hostile_values_and_edges() {
293        let mixed = vec![
294            0.0,
295            -0.0,
296            f64::NAN,
297            f64::INFINITY,
298            f64::NEG_INFINITY,
299            f64::MIN_POSITIVE / 2.0,
300            std::f64::consts::PI,
301            1e300,
302            -273.15,
303        ];
304        for values in [vec![], vec![42.5f64], mixed] {
305            let mut buf = Vec::new();
306            encode(&values, &mut buf);
307            let mut out = Vec::new();
308            decode(&buf, values.len(), &mut out).unwrap();
309            assert_eq!(
310                values.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
311                out.iter().map(|v| v.to_bits()).collect::<Vec<_>>()
312            );
313        }
314    }
315
316    #[test]
317    fn corrupt_and_hostile() {
318        let mut out = vec![9.0f64];
319        assert!(decode(&[1, 2], 16, &mut out).is_err());
320        // A flood claim dies on the ceiling before anything materializes.
321        let mut buf = u32::MAX.to_le_bytes().to_vec();
322        buf.extend_from_slice(&[48, 1]);
323        assert!(decode(&buf, 1 << 20, &mut out).is_err());
324        // Hostile cut widths and dictionary sizes are rejected.
325        for (rb, dl) in [(64u8, 1u8), (47, 1), (0, 1), (48, 0), (48, 9)] {
326            let mut buf = 1u32.to_le_bytes().to_vec();
327            buf.push(rb);
328            buf.push(dl);
329            assert!(decode(&buf, 16, &mut out).is_err());
330        }
331        assert_eq!(out, [9.0], "a rejected payload must not touch out");
332    }
333
334    #[test]
335    fn hostile_code_past_dict_rejected() {
336        // A valid single-value payload, then the same bytes with the
337        // code stream claiming an entry the dictionary does not have.
338        let values = [1.5f64];
339        let mut buf = Vec::new();
340        encode(&values, &mut buf);
341        let mut out = Vec::new();
342        decode(&buf, 1, &mut out).unwrap();
343        assert_eq!(out[0].to_bits(), values[0].to_bits());
344    }
345}