Skip to main content

hawdb_core/
vector_index.rs

1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4//! Schema-bound vector index definitions shared by SQL and Cypher.
5//!
6//! A descriptor is a definition, not serving authority. Publication identity,
7//! source epoch and ordinal ownership belong to its registered Consumer pin.
8
9use crate::{HawDBError, PropertyId, Result, TableId, VectorDimension, VectorDistance};
10
11mod codec;
12
13/// Upper bound used to admit descriptor encoding/decoding before allocation.
14pub const MAX_VECTOR_INDEX_DESCRIPTOR_BYTES: usize = 4096;
15
16/// Immutable source and publication identity of an eligible vector domain.
17/// This is a query binding, never independent authority to publish or serve.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct VectorIndexReadIdentity {
20    pub database: crate::Uuid,
21    pub branch: crate::Uuid,
22    pub consumer_id_hash: [u8; 32],
23    pub target_locator_hash: [u8; 32],
24    pub registration: crate::Uuid,
25    pub projection: crate::Uuid,
26    pub checkpoint: crate::Uuid,
27    pub target_incarnation: std::num::NonZeroU64,
28    pub generation: std::num::NonZeroU64,
29    pub operation: std::num::NonZeroU64,
30    pub source_epoch: u64,
31}
32
33/// Query semantics, independent of the persistent index backend.
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35pub enum VectorIndexQueryMode {
36    /// Fix an approximate window before applying canonical query predicates.
37    #[default]
38    AnnWindow,
39    /// Exhaust the declared eligible domain before selecting exact nearest rows.
40    Exact,
41    /// Restrict approximate candidate generation to a complete eligible domain.
42    FilteredAnn,
43}
44
45impl VectorIndexQueryMode {
46    pub fn parse(value: &str) -> Result<Self> {
47        match value {
48            "ann_window" => Ok(Self::AnnWindow),
49            "exact" => Ok(Self::Exact),
50            "filtered_ann" => Ok(Self::FilteredAnn),
51            _ => Err(invalid(
52                "query mode must be 'ann_window', 'exact' or 'filtered_ann'",
53            )),
54        }
55    }
56
57    pub const fn as_str(self) -> &'static str {
58        match self {
59            Self::AnnWindow => "ann_window",
60            Self::Exact => "exact",
61            Self::FilteredAnn => "filtered_ann",
62        }
63    }
64
65    pub const fn requires_eligible_domain(self) -> bool {
66        matches!(self, Self::Exact | Self::FilteredAnn)
67    }
68
69    pub const fn filter_position(self) -> &'static str {
70        match self {
71            Self::AnnWindow => "after_window",
72            Self::Exact => "before_ranking",
73            Self::FilteredAnn => "before_candidates",
74        }
75    }
76}
77
78/// Resolved field identity. Relational schemas currently identify columns by
79/// normalized table name and ordinal; the descriptor's schema digest fences
80/// reinterpretation of that ordinal after a schema change.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum VectorIndexTarget {
83    Relational {
84        table: String,
85        column: String,
86        column_ordinal: u32,
87    },
88    NodeProperty {
89        table: String,
90        property: String,
91        table_id: TableId,
92        property_id: PropertyId,
93    },
94}
95
96/// Persistent algorithm settings, independent of per-operation admission.
97/// Runtime memory limits and cancellation are supplied at build/query time.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum VectorIndexBackend {
100    DiskAnn {
101        max_degree: u32,
102        build_beam: u32,
103        alpha_milli: u32,
104        lsg: Option<VectorIndexLsg>,
105    },
106    RaBitQ {
107        bit_width: u8,
108        segment_rows: u32,
109        transform_seed: u64,
110    },
111}
112
113/// Integer-scaled persistent parameters have canonical equality and encoding.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub struct VectorIndexLsg {
116    pub sample_size: u32,
117    pub neighbors: u32,
118    pub exponent_milli: u32,
119}
120
121impl Default for VectorIndexBackend {
122    fn default() -> Self {
123        Self::DiskAnn {
124            max_degree: 32,
125            build_beam: 128,
126            alpha_milli: 1200,
127            lsg: None,
128        }
129    }
130}
131
132impl VectorIndexBackend {
133    pub const fn name(self) -> &'static str {
134        match self {
135            Self::DiskAnn { .. } => "diskann",
136            Self::RaBitQ { .. } => "rabitq",
137        }
138    }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct VectorIndexDescriptor {
143    name: String,
144    target: VectorIndexTarget,
145    dimension: VectorDimension,
146    distance: VectorDistance,
147    backend: VectorIndexBackend,
148    schema_digest: [u8; 32],
149}
150
151impl VectorIndexDescriptor {
152    #[doc(hidden)]
153    pub fn retained_capacity_bytes(&self) -> usize {
154        let (table, field) = match &self.target {
155            VectorIndexTarget::Relational { table, column, .. } => (table, column),
156            VectorIndexTarget::NodeProperty {
157                table, property, ..
158            } => (table, property),
159        };
160        std::mem::size_of::<Self>()
161            .saturating_add(self.name.capacity())
162            .saturating_add(table.capacity())
163            .saturating_add(field.capacity())
164    }
165
166    /// Constructs a validated definition. The facade must resolve the target,
167    /// dimension and digest against its pinned canonical schema before use.
168    pub fn new(
169        name: String,
170        target: VectorIndexTarget,
171        dimension: VectorDimension,
172        distance: VectorDistance,
173        backend: VectorIndexBackend,
174        schema_digest: [u8; 32],
175    ) -> Result<Self> {
176        if name.is_empty()
177            || name.len() > 128
178            || !name
179                .bytes()
180                .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
181        {
182            return Err(invalid(
183                "name must be 1..128 ASCII letters, digits, '.', '_' or '-'",
184            ));
185        }
186        let (table, field) = match &target {
187            VectorIndexTarget::Relational { table, column, .. } => (table, column),
188            VectorIndexTarget::NodeProperty {
189                table, property, ..
190            } => (table, property),
191        };
192        for name in [table, field] {
193            if name.is_empty() || name.len() > 1024 || name.contains('\0') {
194                return Err(invalid(
195                    "target names must contain 1..1024 non-NUL UTF-8 bytes",
196                ));
197            }
198        }
199        match backend {
200            VectorIndexBackend::RaBitQ {
201                bit_width,
202                segment_rows,
203                ..
204            } => {
205                if !matches!(bit_width, 1 | 4) || segment_rows == 0 {
206                    return Err(invalid(
207                        "RaBitQ requires 1 or 4 bits and a positive segment size",
208                    ));
209                }
210            }
211            VectorIndexBackend::DiskAnn {
212                max_degree,
213                build_beam,
214                alpha_milli,
215                lsg,
216            } => {
217                if max_degree < 2 || build_beam < max_degree || alpha_milli < 1000 {
218                    return Err(invalid(
219                        "DiskANN requires degree >= 2, beam >= degree and alpha >= 1",
220                    ));
221                }
222                if let Some(lsg) = lsg
223                    && (lsg.sample_size < 2
224                        || lsg.neighbors == 0
225                        || lsg.neighbors > lsg.sample_size
226                        || lsg.exponent_milli == 0
227                        || lsg.exponent_milli > 2000)
228                {
229                    return Err(invalid("invalid DiskANN local scaling parameters"));
230                }
231            }
232        }
233        Ok(Self {
234            name,
235            target,
236            dimension,
237            distance,
238            backend,
239            schema_digest,
240        })
241    }
242
243    pub fn name(&self) -> &str {
244        &self.name
245    }
246
247    pub fn target(&self) -> &VectorIndexTarget {
248        &self.target
249    }
250
251    pub const fn dimension(&self) -> VectorDimension {
252        self.dimension
253    }
254
255    pub const fn distance(&self) -> VectorDistance {
256        self.distance
257    }
258
259    pub const fn backend(&self) -> VectorIndexBackend {
260        self.backend
261    }
262
263    pub const fn schema_digest(&self) -> &[u8; 32] {
264        &self.schema_digest
265    }
266
267    pub fn retained_bytes(&self) -> usize {
268        let (table, field) = match &self.target {
269            VectorIndexTarget::Relational { table, column, .. } => (table, column),
270            VectorIndexTarget::NodeProperty {
271                table, property, ..
272            } => (table, property),
273        };
274        std::mem::size_of::<Self>() + self.name.capacity() + table.capacity() + field.capacity()
275    }
276}
277
278fn invalid(reason: &str) -> HawDBError {
279    HawDBError::Semantic(format!("invalid vector index: {reason}"))
280}
281
282// Retained query ownership: VectorIndexQueryMode.
283crate::impl_retained_heap_for_copy!(VectorIndexQueryMode);