Skip to main content

gam_runtime/warm_start/
key.rs

1//! Fingerprint keying for the warm-start store.
2//!
3//! A [`Fingerprint`] is a SHA-256 hash; two fits whose (data, spec) byte
4//! representations agree under [`Fingerprinter`] absorption produce the same
5//! key. Adversarial collisions don't matter — per-variant warm-start
6//! validators are the correctness fail-safe; the fingerprint is just a fast
7//! filter.
8
9use serde::de::{self, Visitor};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use sha2::{Digest, Sha256};
12use std::fmt;
13
14/// 256-bit warm-start key.
15#[derive(Clone, Copy, PartialEq, Eq, Hash)]
16pub struct Fingerprint([u8; 32]);
17
18impl Serialize for Fingerprint {
19    /// Serialize as the canonical 64-char lowercase hex string so on-disk
20    /// payloads carrying a `Fingerprint` (e.g. the cross-fit `FitArtifact`
21    /// term identities) are stable and human-readable.
22    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
23        serializer.serialize_str(&self.to_hex())
24    }
25}
26
27impl<'de> Deserialize<'de> for Fingerprint {
28    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
29        struct HexVisitor;
30        impl Visitor<'_> for HexVisitor {
31            type Value = Fingerprint;
32            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33                f.write_str("a 64-character hex-encoded SHA-256 fingerprint")
34            }
35            fn visit_str<E: de::Error>(self, v: &str) -> Result<Fingerprint, E> {
36                Fingerprint::from_hex(v).ok_or_else(|| de::Error::custom("invalid hex fingerprint"))
37            }
38        }
39        deserializer.deserialize_str(HexVisitor)
40    }
41}
42
43impl Fingerprint {
44    pub const fn as_bytes(&self) -> &[u8; 32] {
45        &self.0
46    }
47
48    pub fn to_hex(&self) -> String {
49        let mut s = String::with_capacity(64);
50        for b in &self.0 {
51            use std::fmt::Write;
52            write!(&mut s, "{:02x}", b).expect("writing to String is infallible");
53        }
54        s
55    }
56
57    pub fn from_hex(s: &str) -> Option<Self> {
58        if s.len() != 64 {
59            return None;
60        }
61        let bytes = s.as_bytes();
62        let mut out = [0u8; 32];
63        for i in 0..32 {
64            let hi = from_hex_nibble(bytes[2 * i])?;
65            let lo = from_hex_nibble(bytes[2 * i + 1])?;
66            out[i] = (hi << 4) | lo;
67        }
68        Some(Fingerprint(out))
69    }
70}
71
72const fn from_hex_nibble(c: u8) -> Option<u8> {
73    match c {
74        b'0'..=b'9' => Some(c - b'0'),
75        b'a'..=b'f' => Some(c - b'a' + 10),
76        b'A'..=b'F' => Some(c - b'A' + 10),
77        _ => None,
78    }
79}
80
81impl fmt::Debug for Fingerprint {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        write!(f, "Fingerprint({})", self.to_hex())
84    }
85}
86
87impl fmt::Display for Fingerprint {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(&self.to_hex())
90    }
91}
92
93/// Streaming hasher for building a [`Fingerprint`].
94///
95/// Each `absorb_*` writes a per-type discriminator byte, the caller's content
96/// tag, and a length before the data, so `absorb_f64(b"x", 0.5)` cannot
97/// collide with `absorb_bytes(b"x", <the 8 little-endian bytes of 0.5>)`, nor
98/// with `absorb_u64(b"x", 0.5f64.to_bits())` — heterogeneous fields sharing a
99/// tag can never alias.
100pub struct Fingerprinter {
101    h: Sha256,
102}
103
104/// Per-type frame discriminators for the `absorb_*` family. Written before
105/// the content tag so values of different primitive types absorbed under the
106/// same tag with coinciding payload bytes still produce distinct digests.
107mod type_code {
108    pub const TAG: u8 = 0;
109    pub const BYTES: u8 = 1;
110    pub const STR: u8 = 2;
111    pub const U64: u8 = 3;
112}
113
114impl Fingerprinter {
115    pub fn new() -> Self {
116        Self { h: Sha256::new() }
117    }
118
119    /// Write one frame header: type discriminator, then length-prefixed tag.
120    fn frame(&mut self, code: u8, tag: &[u8]) {
121        self.h.update([code]);
122        self.h.update((tag.len() as u32).to_le_bytes());
123        self.h.update(tag);
124    }
125
126    /// Absorb a tag with no payload. Useful for structural separators.
127    pub fn absorb_tag(&mut self, tag: &[u8]) {
128        self.frame(type_code::TAG, tag);
129    }
130
131    pub fn absorb_bytes(&mut self, tag: &[u8], data: &[u8]) {
132        self.frame(type_code::BYTES, tag);
133        self.h.update((data.len() as u64).to_le_bytes());
134        self.h.update(data);
135    }
136
137    pub fn absorb_str(&mut self, tag: &[u8], s: &str) {
138        self.frame(type_code::STR, tag);
139        self.h.update((s.len() as u64).to_le_bytes());
140        self.h.update(s.as_bytes());
141    }
142
143    pub fn absorb_u64(&mut self, tag: &[u8], v: u64) {
144        self.frame(type_code::U64, tag);
145        self.h.update(v.to_le_bytes());
146    }
147
148    pub fn finalize(self) -> Fingerprint {
149        let out = self.h.finalize();
150        let mut bytes = [0u8; 32];
151        bytes.copy_from_slice(&out);
152        Fingerprint(bytes)
153    }
154
155    // ------------------------------------------------------------------
156    // Untagged write_* API — drop-in replacement for the formerly-separate
157    // `StableHasher` (warm-start) and `CacheDigestBuilder` (latent_cache)
158    // hashers. Callers that use this API are responsible for their own
159    // type-disambiguation (typically by writing a leading namespace string
160    // via `write_str`); the `absorb_*` family above prepends per-call tags
161    // and is the safer choice for new code. Callers that use the untagged API
162    // must preserve their own hand-framed input protocol.
163    // ------------------------------------------------------------------
164
165    pub fn write_bytes(&mut self, data: &[u8]) {
166        self.h.update(data);
167    }
168
169    pub fn write_u8(&mut self, value: u8) {
170        self.h.update([value]);
171    }
172
173    pub fn write_bool(&mut self, value: bool) {
174        self.h.update([u8::from(value)]);
175    }
176
177    pub fn write_u64(&mut self, value: u64) {
178        self.h.update(value.to_le_bytes());
179    }
180
181    pub fn write_usize(&mut self, value: usize) {
182        self.h.update((value as u64).to_le_bytes());
183    }
184
185    pub fn write_f64(&mut self, value: f64) {
186        // Normalize -0.0 to +0.0 so signed-zero comparison ambiguity does
187        // not split warm-start key buckets — matches the prior `StableHasher`
188        // contract that warm-start keys depended on.
189        let normalized = if value == 0.0 { 0.0 } else { value };
190        self.h.update(normalized.to_bits().to_le_bytes());
191    }
192
193    pub fn write_str(&mut self, value: &str) {
194        self.write_usize(value.len());
195        self.h.update(value.as_bytes());
196    }
197
198    /// Absorb a length-prefixed `f64` slice using the per-element
199    /// [`Fingerprinter::write_f64`] contract (so `-0.0` is normalized to
200    /// `+0.0`). Canonical home for the byte-identical `len`-then-each-`f64`
201    /// hashing that previously lived as module-local `hash_f64_slice` /
202    /// `hash_vector` copies in `solver/latent_cache`. Uses a bulk byte path
203    /// only when it can emit exactly the same bytes as the element-wise
204    /// normalizing protocol.
205    pub fn write_f64_slice(&mut self, values: &[f64]) {
206        self.write_usize(values.len());
207        self.write_f64_slice_payload(values);
208    }
209
210    fn write_f64_slice_payload(&mut self, values: &[f64]) {
211        #[cfg(target_endian = "little")]
212        {
213            let needs_normalization = values
214                .iter()
215                .any(|&value| value.is_nan() || (value == 0.0 && value.is_sign_negative()));
216            if !needs_normalization {
217                // SAFETY: values.as_ptr() is valid for values.len() contiguous
218                // f64s, f64 has no padding, and reborrowing as bytes is confined
219                // to this update call. Little-endian storage matches write_f64's
220                // to_bits().to_le_bytes() byte stream for non-normalized values.
221                let bytes = unsafe {
222                    std::slice::from_raw_parts(
223                        values.as_ptr() as *const u8,
224                        std::mem::size_of_val(values),
225                    )
226                };
227                self.h.update(bytes);
228                return;
229            }
230        }
231        self.write_f64_slice_payload_slow(values);
232    }
233
234    fn write_f64_slice_payload_slow(&mut self, values: &[f64]) {
235        for &value in values {
236            self.write_f64(value);
237        }
238    }
239
240    /// Absorb a 1D `f64` array as `len` followed by every element via
241    /// [`Fingerprinter::write_f64`]. Canonical home for the byte-identical
242    /// `hash_vector` copy that previously lived in `solver/latent_cache`.
243    pub fn write_f64_array1(&mut self, values: &ndarray::Array1<f64>) {
244        self.write_usize(values.len());
245        if let Some(slice) = values.as_slice() {
246            self.write_f64_slice_payload(slice);
247        } else {
248            self.write_f64_slice_payload_slow_iter(values.iter().copied());
249        }
250    }
251
252    /// Absorb a 2D `f64` array as `(nrows, ncols)` followed by every element in
253    /// iteration order, each via [`Fingerprinter::write_f64`]. Canonical home
254    /// for the byte-identical heuristic that previously lived as module-local
255    /// `write_array2_fingerprint` (`solver/arrow_schur`) and `hash_matrix`
256    /// (`solver/latent_cache`) copies.
257    pub fn write_f64_array2(&mut self, values: &ndarray::Array2<f64>) {
258        self.write_usize(values.nrows());
259        self.write_usize(values.ncols());
260        if let Some(slice) = values.as_slice() {
261            self.write_f64_slice_payload(slice);
262        } else {
263            self.write_f64_slice_payload_slow_iter(values.iter().copied());
264        }
265    }
266
267    fn write_f64_slice_payload_slow_iter<I>(&mut self, values: I)
268    where
269        I: IntoIterator<Item = f64>,
270    {
271        for value in values {
272            self.write_f64(value);
273        }
274    }
275
276    /// Finalize and return the first 8 bytes of the SHA-256 digest as a
277    /// little-endian `u64`. Used by callers that need a compact in-process
278    /// identifier (manifold mode fingerprints, registry fingerprints, …)
279    /// rather than the full 32-byte [`Fingerprint`].
280    pub fn finish_u64(self) -> u64 {
281        let out = self.h.finalize();
282        let mut bytes = [0u8; 8];
283        bytes.copy_from_slice(&out[..8]);
284        u64::from_le_bytes(bytes)
285    }
286
287    /// Finalize and return a zero-padded 16-character hex representation
288    /// of [`Fingerprinter::finish_u64`], suitable for embedding directly
289    /// in cache-key strings.
290    pub fn finish_hex(self) -> String {
291        format!("{:016x}", self.finish_u64())
292    }
293}
294
295impl Default for Fingerprinter {
296    fn default() -> Self {
297        Self::new()
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn write_f64_slice_bulk_matches_element_protocol() {
307        fn pseudo_random_values(n: usize) -> Vec<f64> {
308            let mut state = 0x4d59_5df4_d0f3_3173_u64;
309            let mut values = Vec::with_capacity(n);
310            for idx in 0..n {
311                state = state
312                    .wrapping_mul(6364136223846793005)
313                    .wrapping_add(1442695040888963407);
314                let mantissa = state >> 12;
315                let unit = f64::from_bits(0x3ff0_0000_0000_0000 | mantissa) - 1.0;
316                values.push((unit - 0.5) * ((idx % 17) as f64 + 1.0));
317            }
318            values
319        }
320
321        fn fast_key(values: &[f64]) -> Fingerprint {
322            let mut fp = Fingerprinter::new();
323            fp.write_str("write_f64_slice_bulk_matches_element_protocol");
324            fp.write_f64_slice(values);
325            fp.finalize()
326        }
327
328        fn slow_key(values: &[f64]) -> Fingerprint {
329            let mut fp = Fingerprinter::new();
330            fp.write_str("write_f64_slice_bulk_matches_element_protocol");
331            fp.write_usize(values.len());
332            fp.write_f64_slice_payload_slow(values);
333            fp.finalize()
334        }
335
336        let clean = pseudo_random_values(257);
337        assert_eq!(fast_key(&clean), slow_key(&clean));
338
339        let mut normalized = clean.clone();
340        normalized[7] = -0.0;
341        normalized[113] = f64::from_bits(0x7ff8_0000_0000_0042);
342        assert_eq!(fast_key(&normalized), slow_key(&normalized));
343    }
344
345    #[test]
346    fn write_f64_arrays_match_element_protocol() {
347        let values = ndarray::Array2::from_shape_vec(
348            (3, 4),
349            vec![
350                1.25,
351                -2.5,
352                3.75,
353                4.0,
354                5.5,
355                -0.0,
356                7.25,
357                8.5,
358                9.75,
359                10.0,
360                f64::from_bits(0x7ff8_0000_0000_0100),
361                12.25,
362            ],
363        )
364        .expect("test array shape is valid");
365
366        let mut fast = Fingerprinter::new();
367        fast.write_str("write_f64_arrays_match_element_protocol");
368        fast.write_f64_array2(&values);
369
370        let mut slow = Fingerprinter::new();
371        slow.write_str("write_f64_arrays_match_element_protocol");
372        slow.write_usize(values.nrows());
373        slow.write_usize(values.ncols());
374        slow.write_f64_slice_payload_slow_iter(values.iter().copied());
375
376        assert_eq!(fast.finalize(), slow.finalize());
377    }
378
379    #[test]
380    fn fingerprint_serde_roundtrips_as_hex() {
381        let mut fp = Fingerprinter::new();
382        fp.absorb_str(b"k", "fingerprint-serde");
383        let key = fp.finalize();
384        let json = serde_json::to_string(&key).expect("serialize");
385        // Serialized form is the canonical quoted hex string.
386        assert_eq!(json, format!("\"{}\"", key.to_hex()));
387        let back: Fingerprint = serde_json::from_str(&json).expect("deserialize");
388        assert_eq!(key, back);
389        // A malformed hex payload is rejected, not silently aliased.
390        assert!(serde_json::from_str::<Fingerprint>("\"not-hex\"").is_err());
391    }
392
393    #[test]
394    fn invalid_hex_rejected() {
395        assert!(Fingerprint::from_hex("not hex").is_none());
396        assert!(Fingerprint::from_hex(&"a".repeat(63)).is_none());
397        assert!(Fingerprint::from_hex(&"z".repeat(64)).is_none());
398    }
399}