Skip to main content

aft_store/vector/
model.rs

1//! Which model produced a vector, and the keys vectors and chunk maps are
2//! stored under.
3
4use std::fmt;
5
6use crate::ids::{ContentKey, Digest128};
7use crate::le::{u16_at, u32_at};
8
9/// Everything that decides what vector an embedder returns for a text.
10///
11/// Two identities that differ in any field never share vectors: a new model
12/// revision, another dimension or a changed text template means every
13/// vector must be embedded again.
14#[derive(Clone, PartialEq, Eq, Hash, Debug)]
15pub struct ModelIdentity {
16    /// The model's name as its backend reports it, such as
17    /// `sentence-transformers/all-MiniLM-L6-v2`.
18    pub name: String,
19    /// The model's revision or weights digest; empty when the backend has
20    /// none.
21    pub revision: String,
22    pub dimensions: u32,
23    /// Whether the backend returns vectors scaled to unit length. Scoring is
24    /// cosine either way; a backend that changes this returns different
25    /// vectors.
26    pub normalized: bool,
27    /// Version of the template that builds the text sent to the embedder.
28    pub text_template: u32,
29    /// Version of the rules that cut a file into chunks. Chunk maps depend
30    /// on it; vectors depend only on the text they were given.
31    pub chunk_template: u32,
32}
33
34/// Fingerprints are refused when their strings are longer than this, so a
35/// damaged length cannot ask for an absurd allocation.
36const MAX_IDENTITY_STRING: usize = 4096;
37
38impl ModelIdentity {
39    /// The identity as stored in a segment.
40    ///
41    /// # Panics
42    ///
43    /// When the name or revision is longer than 4,096 bytes.
44    #[must_use]
45    pub fn encode(&self) -> Vec<u8> {
46        assert!(
47            self.name.len() <= MAX_IDENTITY_STRING && self.revision.len() <= MAX_IDENTITY_STRING,
48            "model name and revision must be at most {MAX_IDENTITY_STRING} bytes"
49        );
50        let mut out = Vec::with_capacity(17 + self.name.len() + self.revision.len());
51        out.extend_from_slice(&self.dimensions.to_le_bytes());
52        out.push(u8::from(self.normalized));
53        out.extend_from_slice(&self.text_template.to_le_bytes());
54        out.extend_from_slice(&self.chunk_template.to_le_bytes());
55        for text in [&self.name, &self.revision] {
56            let len = u16::try_from(text.len()).expect("checked above");
57            out.extend_from_slice(&len.to_le_bytes());
58            out.extend_from_slice(text.as_bytes());
59        }
60        out
61    }
62
63    /// Reads an identity back; `None` when the bytes are not one.
64    #[must_use]
65    pub fn decode(bytes: &[u8]) -> Option<Self> {
66        if bytes.len() < 13 {
67            return None;
68        }
69        let normalized = match bytes[4] {
70            0 => false,
71            1 => true,
72            _ => return None,
73        };
74        let mut at = 13;
75        let mut strings = Vec::with_capacity(2);
76        for _ in 0..2 {
77            if bytes.len() < at + 2 {
78                return None;
79            }
80            let len = usize::from(u16_at(bytes, at));
81            at += 2;
82            if len > MAX_IDENTITY_STRING || bytes.len() < at + len {
83                return None;
84            }
85            strings.push(String::from_utf8(bytes[at..at + len].to_vec()).ok()?);
86            at += len;
87        }
88        if at != bytes.len() {
89            return None;
90        }
91        let revision = strings.pop()?;
92        let name = strings.pop()?;
93        Some(Self {
94            name,
95            revision,
96            dimensions: u32_at(bytes, 0),
97            normalized,
98            text_template: u32_at(bytes, 5),
99            chunk_template: u32_at(bytes, 9),
100        })
101    }
102
103    /// The identity's digest, the model half of every vector key.
104    #[must_use]
105    pub fn id(&self) -> ModelId {
106        let mut hasher = blake3::Hasher::new_derive_key("aft-store 2026-11 vector model identity");
107        hasher.update(&self.encode());
108        ModelId(Digest128::from_hash(&hasher.finalize()))
109    }
110}
111
112/// The digest of a [`ModelIdentity`].
113#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
114pub struct ModelId(Digest128);
115
116impl ModelId {
117    #[must_use]
118    pub const fn digest(&self) -> Digest128 {
119        self.0
120    }
121}
122
123impl fmt::Display for ModelId {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        self.0.fmt(f)
126    }
127}
128
129impl fmt::Debug for ModelId {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        write!(f, "ModelId({})", self.0)
132    }
133}
134
135/// The digest of the exact bytes sent to the embedder for one chunk. With
136/// the model's identity it is the key of one vector.
137///
138/// The embedded text includes the file's path, so the same symbol at two
139/// paths has two keys; the same path and text in any checkout of the family
140/// shares one.
141#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
142pub struct TextDigest(Digest128);
143
144impl TextDigest {
145    /// The key of the embedded text `bytes`.
146    #[must_use]
147    pub fn of(bytes: &[u8]) -> Self {
148        Self(Digest128::of(bytes))
149    }
150
151    /// A digest read back from storage.
152    #[must_use]
153    pub const fn from_digest(digest: Digest128) -> Self {
154        Self(digest)
155    }
156
157    #[must_use]
158    pub const fn digest(&self) -> Digest128 {
159        self.0
160    }
161}
162
163impl fmt::Display for TextDigest {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        self.0.fmt(f)
166    }
167}
168
169impl fmt::Debug for TextDigest {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        write!(f, "TextDigest({})", self.0)
172    }
173}
174
175/// The key of one file's chunk map: the file's content and the path it is
176/// at. The path is part of the key because the embedded text includes it.
177#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
178pub struct ChunkMapKey {
179    content: ContentKey,
180    path: Digest128,
181}
182
183impl ChunkMapKey {
184    pub(crate) const LEN: usize = 2 * Digest128::LEN;
185
186    #[must_use]
187    pub fn new(content: ContentKey, path: &[u8]) -> Self {
188        let mut hasher = blake3::Hasher::new_derive_key("aft-store 2026-11 chunk map path");
189        hasher.update(path);
190        Self {
191            content,
192            path: Digest128::from_hash(&hasher.finalize()),
193        }
194    }
195
196    #[must_use]
197    pub const fn content(&self) -> ContentKey {
198        self.content
199    }
200
201    pub(crate) fn to_bytes(self) -> [u8; Self::LEN] {
202        let mut out = [0; Self::LEN];
203        out[..Digest128::LEN].copy_from_slice(self.content.digest().as_bytes());
204        out[Digest128::LEN..].copy_from_slice(self.path.as_bytes());
205        out
206    }
207
208    /// A key read back from a chunk map table; `None` when the bytes are
209    /// not one.
210    pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
211        if bytes.len() != Self::LEN {
212            return None;
213        }
214        Some(Self {
215            content: ContentKey::from_digest(Digest128::from_bytes(crate::le::array(bytes, 0))),
216            path: Digest128::from_bytes(crate::le::array(bytes, Digest128::LEN)),
217        })
218    }
219}
220
221crate::heap_bytes_none!(ModelId, TextDigest, ChunkMapKey);
222crate::heap_bytes_of_fields!(ModelIdentity {
223    name,
224    revision,
225    dimensions,
226    normalized,
227    text_template,
228    chunk_template,
229});