Skip to main content

relate_model/vector/
coords.rs

1//! The packed coordinate representation a `Vector` value carries
2//! (ADR-0706). One `Arc`-ed slice per coordinate family, exact for every
3//! `VectorCoordKind` it serves, produced only by the canonical
4//! constructors (`CypherValue::vector` / `Value::vector`) — never built by
5//! hand at a construction site.
6
7use std::fmt;
8
9use crate::value::CypherValue;
10use std::sync::Arc;
11
12/// A vector's coordinates, packed per coordinate family (ADR-0706):
13///
14/// - `Float16`/`BFloat16`/`Float32` → `F32`: every value of those kinds is
15///   exactly representable in `f32` (10/7/23 mantissa bits, all ⊂ `f32`),
16///   so the packing is lossless and the kernel's `f32 → f64` widen reads
17///   the same number the per-`Value` walk read.
18/// - `Float64` → `F64`.
19/// - `Int8`/`Int16`/`Int32`/`Int64` → `Int`: lossless as `i64`; the kind's
20///   width was validated when the coordinates were coerced.
21///
22/// Replaces `Vec<CypherValue>` (48 bytes per coordinate) at 4/8/8 bytes
23/// per coordinate — the value *is* the packed form, so nothing scan-side
24/// copies or invalidates it: a rewrite swaps the `Arc`, and the MVCC
25/// version chain hands every reader the exact buffer its snapshot should
26/// see.
27#[derive(Debug, Clone)]
28pub enum VectorCoords {
29    F32(Arc<[f32]>),
30    F64(Arc<[f64]>),
31    Int(Arc<[i64]>),
32}
33
34/// One coordinate of a packed vector, for display and encoding: the
35/// per-`Value` arms it replaces (`CypherValue::Int` / `CypherValue::Float`)
36/// had distinct renderings, so the packed read keeps the distinction.
37#[derive(Debug, Clone, Copy)]
38pub enum Coord {
39    F(f64),
40    I(i64),
41}
42
43impl fmt::Display for Coord {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        // One rendering: `text()` is the canonical spelling, so `Display`
46        // and every explicit call cannot drift.
47        f.write_str(&self.text())
48    }
49}
50
51/// The one coordinate equality — [`Coord::numeric_eq`], so the container
52/// (`VectorCoords`' `PartialEq`) and its elements cannot disagree.
53impl PartialEq for Coord {
54    fn eq(&self, other: &Self) -> bool {
55        Coord::numeric_eq(*self, *other)
56    }
57}
58
59impl Coord {
60    /// The coordinate's scalar text — the rendering the per-`Value` walk
61    /// produced (`Value::Float`'s `float_text`, `Value::Int`'s
62    /// `to_string`), identical for the literal and display walks.
63    pub fn text(&self) -> String {
64        match self {
65            Coord::F(v) => crate::value::float_text(*v),
66            Coord::I(i) => i.to_string(),
67        }
68    }
69
70    /// The scalar numeric equality — the one elementwise rule: same forms
71    /// by value, and the exact `eq_i64_f64` rule across `Int`/float (large
72    /// integers stay exact past 2^53). The float arm erases the family, so
73    /// the `F32` and `F64` spellings of one number compare equal and the
74    /// relation stays transitive.
75    pub(crate) fn numeric_eq(a: Coord, b: Coord) -> bool {
76        match (a, b) {
77            (Coord::I(x), Coord::I(y)) => x == y,
78            (Coord::F(x), Coord::F(y)) => x == y,
79            (Coord::I(x), Coord::F(y)) => crate::canonical_key::eq_i64_f64(x, y),
80            (Coord::F(x), Coord::I(y)) => crate::canonical_key::eq_i64_f64(y, x),
81        }
82    }
83
84    /// The coordinate's little-endian bytes — `i64`'s for an integer,
85    /// `f64`'s for a float (the two share the byte mix the hash walks
86    /// use, exactly as `Value::Int`/`Value::Float` always did).
87    pub fn to_le_bytes(self) -> [u8; 8] {
88        match self {
89            Coord::I(v) => v.to_le_bytes(),
90            Coord::F(v) => v.to_le_bytes(),
91        }
92    }
93}
94
95/// The one equality: [`VectorCoords::numeric_eq`] — the elementwise
96/// numeric rule every value type's vector comparison already applies, so
97/// the derived variant-strict form cannot disagree with it anywhere.
98impl PartialEq for VectorCoords {
99    fn eq(&self, other: &Self) -> bool {
100        self.numeric_eq(other)
101    }
102}
103
104/// One coordinate against its kind — the family/kind pairing and the
105/// per-coordinate width/precision rules, spelled once (ADR-0706). The
106/// `Int` family is legal under every kind (its equality with the float
107/// spelling is the exact numeric rule): under a float kind it takes the
108/// full `i64` range, under an integer kind the kind's width.
109fn coord_conforms(kind: crate::value::VectorCoordKind, c: Coord) -> Result<(), String> {
110    match (c, kind) {
111        (Coord::I(n), kind) if kind.is_integer() => {
112            if kind.holds_int(n) {
113                Ok(())
114            } else {
115                Err(format!(
116                    "coordinate {n} out of {} range",
117                    kind.canonical_name()
118                ))
119            }
120        }
121        // The `Int` family under a float kind is legal at full range.
122        (Coord::I(_), _) => Ok(()),
123        // One float rule (F-10-1): finite, and exactly representable in
124        // the kind — `is_exact` answers every float kind, the message
125        // names the failure the value shows.
126        (Coord::F(f), kind) if !kind.is_integer() => {
127            if f.is_finite() && kind.is_exact(f) {
128                Ok(())
129            } else if !f.is_finite() {
130                Err(format!(
131                    "non-finite {} coordinate {f}",
132                    kind.canonical_name()
133                ))
134            } else {
135                Err(format!(
136                    "coordinate {f} loses precision in {}",
137                    kind.canonical_name()
138                ))
139            }
140        }
141        (Coord::F(f), kind) => Err(format!(
142            "float coordinate {f} under integer kind {}",
143            kind.canonical_name()
144        )),
145    }
146}
147
148/// The buffer's family, the one pairing fact the invariant checks
149/// (ADR-0706): `F32` for the reduced float kinds, `F64` for FLOAT,
150/// `Int` for the integer kinds.
151fn family_of(coords: &VectorCoords) -> &'static str {
152    match coords {
153        VectorCoords::F32(_) => "F32",
154        VectorCoords::F64(_) => "F64",
155        VectorCoords::Int(_) => "Int",
156    }
157}
158
159fn kind_family(kind: crate::value::VectorCoordKind) -> &'static str {
160    use crate::value::VectorCoordKind;
161    match kind {
162        k if k.is_f32_family() => "F32",
163        VectorCoordKind::Float64 => "F64",
164        _ => "Int",
165    }
166}
167
168impl VectorCoords {
169    /// The `f32` family: `Float16`, `BFloat16`, `Float32`.
170    pub fn from_f32(coords: impl Into<Arc<[f32]>>) -> Self {
171        VectorCoords::F32(coords.into())
172    }
173
174    /// The `f64` family: `Float64`.
175    pub fn from_f64(coords: impl Into<Arc<[f64]>>) -> Self {
176        VectorCoords::F64(coords.into())
177    }
178
179    /// The integer family: `Int8`–`Int64`, held losslessly as `i64`.
180    pub fn from_int(coords: impl Into<Arc<[i64]>>) -> Self {
181        VectorCoords::Int(coords.into())
182    }
183
184    pub fn len(&self) -> usize {
185        match self {
186            VectorCoords::F32(xs) => xs.len(),
187            VectorCoords::F64(xs) => xs.len(),
188            VectorCoords::Int(xs) => xs.len(),
189        }
190    }
191
192    pub fn is_empty(&self) -> bool {
193        self.len() == 0
194    }
195
196    /// The family's element width in bytes — the one width table the
197    /// memory charges read, never re-spelled 4/8/8 at a use site.
198    pub fn element_bytes(&self) -> u64 {
199        match self {
200            VectorCoords::F32(_) => 4,
201            VectorCoords::F64(_) | VectorCoords::Int(_) => 8,
202        }
203    }
204
205    /// The family's slice bytes — `len × element_bytes()`.
206    pub fn byte_len(&self) -> u64 {
207        (self.len() as u64) * self.element_bytes()
208    }
209
210    /// The family buffer's address — the dedup meters' identity key,
211    /// family-agnostic so no meter enumerates the three arms.
212    pub fn arc_id(&self) -> *const u8 {
213        match self {
214            VectorCoords::F32(xs) => xs.as_ptr() as *const u8,
215            VectorCoords::F64(xs) => xs.as_ptr() as *const u8,
216            VectorCoords::Int(xs) => xs.as_ptr() as *const u8,
217        }
218    }
219
220    /// The family buffer's strong count — the ownership meters' holders
221    /// figure, family-agnostic.
222    pub fn arc_strong_count(&self) -> usize {
223        match self {
224            VectorCoords::F32(xs) => Arc::strong_count(xs),
225            VectorCoords::F64(xs) => Arc::strong_count(xs),
226            VectorCoords::Int(xs) => Arc::strong_count(xs),
227        }
228    }
229
230    /// Whether this value is the family buffer's sole owner — the
231    /// unique-heap meters' one test, over the one holders figure.
232    pub fn is_unique(&self) -> bool {
233        self.arc_strong_count() == 1
234    }
235
236    /// Every coordinate widened to `f64` — the query-side and conversion
237    /// widenings' one loop.
238    pub fn to_f64_vec(&self) -> Vec<f64> {
239        match self {
240            VectorCoords::F32(xs) => xs.iter().map(|&x| f64::from(x)).collect(),
241            VectorCoords::F64(xs) => xs.to_vec(),
242            VectorCoords::Int(xs) => xs.iter().map(|&x| x as f64).collect(),
243        }
244    }
245
246    /// The elementwise numeric equality — [`Coord::numeric_eq`] over the
247    /// two buffers, gated on length. The one vector-equality policy,
248    /// shared by `CypherValue::eq` and the core value's `eq_non_null`
249    /// (and by `PartialEq`).
250    pub fn numeric_eq(&self, other: &VectorCoords) -> bool {
251        self.len() == other.len()
252            && self
253                .iter()
254                .zip(other.iter())
255                .all(|(a, b)| Coord::numeric_eq(a, b))
256    }
257
258    /// The `i`th coordinate, for display and encoding. Panics only when
259    /// out of bounds — callers bound by [`VectorCoords::len`].
260    pub fn coord_at(&self, i: usize) -> Coord {
261        match self {
262            VectorCoords::F32(xs) => Coord::F(xs[i] as f64),
263            VectorCoords::F64(xs) => Coord::F(xs[i]),
264            VectorCoords::Int(xs) => Coord::I(xs[i]),
265        }
266    }
267
268    /// The `i`th coordinate widened to `f64` — the similarity kernels'
269    /// one read. The per-`Value` walk this replaces could return `None`
270    /// for a non-number coordinate; the packed form is homogeneous and
271    /// numeric by construction, so the skip contract it fed cannot arise.
272    /// Panics only when out of bounds.
273    pub fn coord_f64(&self, i: usize) -> f64 {
274        match self {
275            VectorCoords::F32(xs) => xs[i] as f64,
276            VectorCoords::F64(xs) => xs[i],
277            VectorCoords::Int(xs) => xs[i] as f64,
278        }
279    }
280
281    /// Every coordinate in order, for encoding walks (serde, wire).
282    pub fn iter(&self) -> impl Iterator<Item = Coord> + '_ {
283        let len = self.len();
284        (0..len).map(move |i| self.coord_at(i))
285    }
286
287    /// Decoded or coerced coordinates packed per family — the ONE
288    /// family-selection policy (ADR-0706): every bridge that holds
289    /// already-converted coordinates (the serde decoder, the core JSON
290    /// codecs, the FFI parameter bridge, `vector()`'s coercion) classifies
291    /// its elements and lands here, so the family mapping, the empty
292    /// vector, and the one-family-per-vector rule have one spelling.
293    /// `None` when an element does not conform to the kind or the
294    /// coordinates mix families (the caller maps that to its own typed
295    /// error); the canonical constructors re-assert the invariant
296    /// regardless.
297    ///
298    /// The `Coord::I` token under a float kind packs as the `Int` family
299    /// at full `i64` range (its equality with the float spelling is the
300    /// exact numeric rule, which widening would round away past 2^53).
301    pub fn from_coords(
302        coord: crate::value::VectorCoordKind,
303        coords: impl Iterator<Item = Coord>,
304    ) -> Option<VectorCoords> {
305        use crate::value::VectorCoordKind;
306        let tokens = coords.collect::<Vec<_>>();
307        // One verdict per coordinate — `coord_conforms` owns the rule;
308        // this policy adds only the family selection on top.
309        for c in &tokens {
310            coord_conforms(coord, *c).ok()?;
311        }
312        let mut ints: Option<Vec<i64>> = None;
313        let mut floats: Option<Vec<f64>> = None;
314        for c in tokens {
315            match c {
316                Coord::I(n) => ints.get_or_insert_with(Vec::new).push(n),
317                Coord::F(f) => floats.get_or_insert_with(Vec::new).push(f),
318            }
319        }
320        match (ints, floats) {
321            // The empty vector takes its kind's own family.
322            (None, None) if coord == VectorCoordKind::Float64 => {
323                Some(VectorCoords::from_f64(Vec::new()))
324            }
325            (None, None) if coord.is_integer() => Some(VectorCoords::from_int(Vec::new())),
326            (None, None) => Some(VectorCoords::from_f32(Vec::new())),
327            (Some(xs), None) => Some(VectorCoords::from_int(xs)),
328            (None, Some(xs)) if coord == VectorCoordKind::Float64 => {
329                Some(VectorCoords::from_f64(xs))
330            }
331            (None, Some(xs)) => Some(VectorCoords::from_f32(
332                xs.iter().map(|&f| f as f32).collect::<Vec<_>>(),
333            )),
334            // The engine writes homogeneous coordinates — a family mix is
335            // a crafted document.
336            _ => None,
337        }
338    }
339
340    /// [`from_coords`](VectorCoords::from_coords) over already-coerced
341    /// `CypherValue`s — the FFI parameter bridge's thin adapter. A
342    /// non-number element rejects directly (`None`), never through a
343    /// sentinel the policy would have to reject incidentally.
344    pub fn from_cypher_values(
345        coord: crate::value::VectorCoordKind,
346        values: &[CypherValue],
347    ) -> Option<VectorCoords> {
348        let tokens = values
349            .iter()
350            .map(|v| match v {
351                CypherValue::Int(n) => Some(Coord::I(*n)),
352                CypherValue::Float(f) => Some(Coord::F(*f)),
353                _ => None,
354            })
355            .collect::<Option<Vec<_>>>()?;
356        Self::from_coords(coord, tokens.into_iter())
357    }
358
359    /// The family/kind pairing and per-coordinate exactness invariant the
360    /// canonical constructors assert (ADR-0706) — one spelling shared by
361    /// the model and core constructors. `Err` carries the invariant
362    /// message; user-input rejection stays typed at the coercion
363    /// boundaries, so this firing is an engine bug, not a data condition.
364    ///
365    /// The `Int` family is legal under *every* kind, not only the integer
366    /// kinds: a float-kind vector may carry integer coordinates (the
367    /// decoded form of integers a persisted store held), and its equality
368    /// with the float-family vector of the same numbers is the exact
369    /// numeric elementwise rule (`eq_i64_f64`), which widening a large
370    /// `i64` to `f64` would round away. Range is still the kind's own
371    /// (`holds_int`).
372    /// Assert this buffer conforms to `coord` — the constructors' one
373    /// panicking invariant check (the data-side rejection shape is
374    /// [`VectorCoords::from_coords`]'s `Option`, the only fallible form).
375    pub fn assert_conforms(&self, coord: crate::value::VectorCoordKind) {
376        if let Err(message) = self.invariant_violation(coord) {
377            panic!("{message}");
378        }
379    }
380
381    pub fn invariant_violation(&self, coord: crate::value::VectorCoordKind) -> Result<(), String> {
382        // The buffer/kind pairing first — a float family under the wrong
383        // float kind (an `F32` buffer under FLOAT, `F64` under FLOAT32)
384        // is a family mismatch even when every coordinate survives the
385        // kind's precision check. The `Int` family is legal under every
386        // kind (its equality with the float spelling is the exact
387        // numeric rule), so only float buffers are gated.
388        if family_of(self) != kind_family(coord) && family_of(self) != "Int" {
389            return Err(format!(
390                "vector coordinate family does not match kind {}",
391                coord.canonical_name()
392            ));
393        }
394        for c in self.iter() {
395            coord_conforms(coord, c)?;
396        }
397        Ok(())
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    #[test]
406    fn f32_family_round_trips_losslessly() {
407        let coords = VectorCoords::from_f32(vec![0.25f32, -1.5, 3.0]);
408        assert_eq!(coords.len(), 3);
409        assert_eq!(coords.coord_f64(0), 0.25);
410        assert_eq!(coords.coord_f64(1), -1.5);
411        assert_eq!(coords.coord_f64(2), 3.0);
412    }
413
414    #[test]
415    fn int_family_reads_as_f64_like_the_value_walk_did() {
416        let coords = VectorCoords::from_int(vec![7i64, -2]);
417        assert_eq!(coords.coord_f64(0), 7.0);
418        assert_eq!(coords.coord_f64(1), -2.0);
419        assert_eq!(coords.coord_at(0).to_string(), "7");
420    }
421
422    #[test]
423    fn display_keeps_the_int_float_distinction() {
424        let ints = VectorCoords::from_int(vec![5]);
425        let floats = VectorCoords::from_f32(vec![5.0]);
426        assert_eq!(ints.coord_at(0).to_string(), "5");
427        assert_eq!(floats.coord_at(0).to_string(), "5.0");
428    }
429
430    #[test]
431    fn equality_is_the_numeric_policy_like_the_value_walk() {
432        assert_eq!(
433            VectorCoords::from_f32(vec![0.5f32, 1.0]),
434            VectorCoords::from_f32(vec![0.5f32, 1.0])
435        );
436        // The `Int` family equals its float spelling — the elementwise
437        // numeric rule, not a variant-strict comparison.
438        assert_eq!(
439            VectorCoords::from_int(vec![1]),
440            VectorCoords::from_f64(vec![1.0])
441        );
442    }
443}