nodedb-types 0.4.0

Portable type definitions shared between NodeDB Origin and NodeDB-Lite
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// SPDX-License-Identifier: Apache-2.0

//! Vector-primary collection configuration types, plus partition-strategy
//! metadata.
//!
//! `PrimaryEngine` is a parallel attribute to `CollectionType` that tells the
//! planner which engine is the primary access path for a collection.
//! Vectors remain an index — not a collection type — but a `primary = 'vector'`
//! attribute means the vector index is the hot path and the document store is
//! a metadata sidecar.
//!
//! `PartitionStrategy` records HOW a collection is distributed across vShards.
//! It is the single authoritative source for partition metadata; future routing
//! and resharding layers read this field instead of inferring from engine type.

use crate::collection::CollectionType;
use crate::columnar::{ColumnarProfile, DocumentMode};
use crate::vector_ann::VectorQuantization;
use crate::vector_distance::DistanceMetric;
use crate::vector_dtype::VectorStorageDtype;

/// Which engine serves as the primary access path for a collection.
///
/// This is independent of `CollectionType` — it is an optimizer hint that
/// instructs the planner and executor to use the named engine as the hot path.
/// The default is inferred from `CollectionType` so existing collections need
/// no migration.
#[repr(u8)]
#[derive(
    Debug,
    Clone,
    Copy,
    Default,
    PartialEq,
    Eq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    zerompk::ToMessagePack,
    zerompk::FromMessagePack,
)]
#[non_exhaustive]
pub enum PrimaryEngine {
    /// Schemaless document (MessagePack). The historic default.
    #[default]
    Document = 0,
    /// Strict document (Binary Tuples).
    Strict = 1,
    /// Key-Value hash store.
    KeyValue = 2,
    /// Columnar / plain-analytics.
    Columnar = 3,
    /// Columnar with spatial profile.
    Spatial = 4,
    /// Vector-primary: HNSW is the hot path; document store is a metadata sidecar.
    Vector = 10,
}

impl PrimaryEngine {
    /// Infer the primary engine from a `CollectionType`.
    ///
    /// Used when reading catalog entries that predate the `primary` field —
    /// guarantees that existing collections behave as before.
    pub fn infer_from_collection_type(ct: &CollectionType) -> Self {
        match ct {
            CollectionType::Document(DocumentMode::Schemaless) => Self::Document,
            CollectionType::Document(DocumentMode::Strict(_)) => Self::Strict,
            CollectionType::Columnar(ColumnarProfile::Plain) => Self::Columnar,
            CollectionType::Columnar(ColumnarProfile::Timeseries { .. }) => Self::Columnar,
            CollectionType::Columnar(ColumnarProfile::Spatial { .. }) => Self::Spatial,
            CollectionType::KeyValue(_) => Self::KeyValue,
        }
    }
}

/// Configuration for a vector-primary collection.
///
/// Stored in `StoredCollection::vector_primary` when `primary == PrimaryEngine::Vector`.
/// All options correspond to HNSW construction parameters and codec selection for the
/// primary vector index.
#[derive(
    Debug,
    Clone,
    PartialEq,
    serde::Serialize,
    serde::Deserialize,
    zerompk::ToMessagePack,
    zerompk::FromMessagePack,
)]
pub struct VectorPrimaryConfig {
    /// The name of the column that holds vector data (must be of type VECTOR(n)).
    pub vector_field: String,
    /// Vector dimensionality.
    pub dim: u32,
    /// Quantization codec for the primary HNSW index.
    pub quantization: VectorQuantization,
    /// HNSW `M` parameter (number of connections per node).
    pub m: u8,
    /// HNSW `ef_construction` parameter (beam width during index construction).
    pub ef_construction: u16,
    /// Distance metric used for similarity search.
    pub metric: DistanceMetric,
    /// Native storage dtype for vector values. Controls whether incoming
    /// f32 components are stored as-is (F32), downsized to half precision
    /// (F16), or brain-float (BF16) to halve memory at the cost of reduced
    /// mantissa precision. Quantization codecs (RaBitQ, BBQ, SQ8 …) apply
    /// on top and are orthogonal to this setting.
    pub storage_dtype: VectorStorageDtype,
    /// Payload field names that receive in-memory bitmap indexes for fast
    /// pre-filtering, paired with the storage kind (Equality / Range /
    /// Boolean). The DDL handler infers the kind from the column type:
    /// numeric / timestamp / decimal → Range; bool → Boolean; everything
    /// else → Equality.
    pub payload_indexes: Vec<(String, PayloadIndexKind)>,
}

impl Default for VectorPrimaryConfig {
    fn default() -> Self {
        Self {
            vector_field: String::new(),
            dim: 0,
            quantization: VectorQuantization::default(),
            m: 16,
            ef_construction: 200,
            metric: DistanceMetric::Cosine,
            storage_dtype: VectorStorageDtype::F32,
            payload_indexes: Vec::new(),
        }
    }
}

/// Storage kind for a payload bitmap index. Equality fields use a
/// `HashMap<key, bitmap>` (O(1) lookup); Range fields use a `BTreeMap`
/// for sorted range scans; Boolean is a low-cardinality equality variant.
#[derive(
    Debug,
    Clone,
    Copy,
    Default,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    zerompk::ToMessagePack,
    zerompk::FromMessagePack,
)]
#[non_exhaustive]
pub enum PayloadIndexKind {
    #[default]
    Equality,
    Range,
    Boolean,
}

/// A single payload-bitmap predicate atom emitted by the SQL planner and
/// consumed by the vector search handler. The handler ANDs all atoms in
/// `VectorOp::Search::payload_filters`; each atom may itself be a
/// disjunction (`In`).
#[derive(
    Debug,
    Clone,
    PartialEq,
    serde::Serialize,
    serde::Deserialize,
    zerompk::ToMessagePack,
    zerompk::FromMessagePack,
)]
#[non_exhaustive]
pub enum PayloadAtom {
    /// `field = value` — single equality bitmap lookup.
    Eq(String, crate::Value),
    /// `field IN (v1, v2, ...)` — union of per-value bitmaps.
    In(String, Vec<crate::Value>),
    /// `field >= low AND field <= high` — sorted range scan over a
    /// `PayloadIndexKind::Range` index. Either bound being `None` means
    /// open on that side.
    Range {
        field: String,
        low: Option<crate::Value>,
        low_inclusive: bool,
        high: Option<crate::Value>,
        high_inclusive: bool,
    },
}

/// Names WHAT a key-partitioned collection hashes to derive its vShard.
///
/// Defined as substrate for future routing and array layers; not yet populated
/// at create time for those paths — only `PartitionStrategy::CollectionHomed`
/// is used at create time in this release.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    zerompk::ToMessagePack,
    zerompk::FromMessagePack,
)]
pub enum KeySpec {
    /// Graph edge endpoint node-id string (hashed via VShardId::from_key).
    NodeId,
    /// Array name ‖ tile-id (array tile routing).
    ArrayTile,
}

/// How a collection's rows are distributed across vShards.
///
/// This is the authoritative per-collection partition metadata. Future routing,
/// Calvin, and resharding layers read this field instead of inferring
/// distribution from engine type.
#[derive(
    Debug,
    Clone,
    Default,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    zerompk::ToMessagePack,
    zerompk::FromMessagePack,
)]
pub enum PartitionStrategy {
    /// All rows live on one owning vShard derived from (db_id, collection).
    ///
    /// Every base collection is collection-homed today: Document (schemaless
    /// and strict), Columnar (plain, timeseries, spatial), and Key-Value all
    /// route to a single vShard that owns the collection. Graph edge-key
    /// partitioning and Array tile partitioning are operation-level concerns
    /// handled separately and are NOT reflected here at create time.
    #[default]
    CollectionHomed,
    /// Rows routed by hashing a key field. Reserved for future key-partitioned
    /// collections; not populated at create time in this release.
    KeyPartitioned { key: KeySpec },
}

impl PartitionStrategy {
    /// Derive the create-time default strategy from a [`CollectionType`].
    ///
    /// Every base engine is collection-homed today:
    /// - `Document` (schemaless and strict): single-vShard B-tree ownership.
    /// - `Columnar` (plain, timeseries, spatial): single-vShard segment
    ///   ownership; timeseries append partitioning is a write-path concern,
    ///   not a metadata-level partition strategy.
    /// - `KeyValue`: single-vShard hash-index ownership; per-key routing is
    ///   internal to the engine, not exposed at the collection layer.
    ///
    /// Graph edge-key and Array tile partitioning are operation-level and are
    /// handled separately — they are NOT set here at collection create time.
    pub fn default_for_collection_type(ct: &CollectionType) -> Self {
        match ct {
            CollectionType::Document(DocumentMode::Schemaless) => Self::CollectionHomed,
            CollectionType::Document(DocumentMode::Strict(_)) => Self::CollectionHomed,
            CollectionType::Columnar(ColumnarProfile::Plain) => Self::CollectionHomed,
            CollectionType::Columnar(ColumnarProfile::Timeseries { .. }) => Self::CollectionHomed,
            CollectionType::Columnar(ColumnarProfile::Spatial { .. }) => Self::CollectionHomed,
            CollectionType::KeyValue(_) => Self::CollectionHomed,
        }
    }

    /// Stable lowercase tag for catalog and SHOW output.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::CollectionHomed => "collection_homed",
            Self::KeyPartitioned { .. } => "key_partitioned",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn primary_engine_default_is_document() {
        assert_eq!(PrimaryEngine::default(), PrimaryEngine::Document);
    }

    #[test]
    fn infer_from_collection_type_document_schemaless() {
        let ct = CollectionType::document();
        assert_eq!(
            PrimaryEngine::infer_from_collection_type(&ct),
            PrimaryEngine::Document
        );
    }

    #[test]
    fn infer_from_collection_type_document_strict() {
        use crate::columnar::{ColumnDef, ColumnType, StrictSchema};
        let schema = StrictSchema::new(vec![
            ColumnDef::required("id", ColumnType::Int64).with_primary_key(),
        ])
        .unwrap();
        let ct = CollectionType::strict(schema);
        assert_eq!(
            PrimaryEngine::infer_from_collection_type(&ct),
            PrimaryEngine::Strict
        );
    }

    #[test]
    fn infer_from_collection_type_columnar_plain() {
        let ct = CollectionType::columnar();
        assert_eq!(
            PrimaryEngine::infer_from_collection_type(&ct),
            PrimaryEngine::Columnar
        );
    }

    #[test]
    fn infer_from_collection_type_columnar_timeseries() {
        let ct = CollectionType::timeseries("ts", "1h");
        assert_eq!(
            PrimaryEngine::infer_from_collection_type(&ct),
            PrimaryEngine::Columnar
        );
    }

    #[test]
    fn infer_from_collection_type_columnar_spatial() {
        let ct = CollectionType::spatial("geom");
        assert_eq!(
            PrimaryEngine::infer_from_collection_type(&ct),
            PrimaryEngine::Spatial
        );
    }

    #[test]
    fn infer_from_collection_type_kv() {
        use crate::columnar::{ColumnDef, ColumnType, StrictSchema};
        let schema = StrictSchema::new(vec![
            ColumnDef::required("k", ColumnType::String).with_primary_key(),
        ])
        .unwrap();
        let ct = CollectionType::kv(schema);
        assert_eq!(
            PrimaryEngine::infer_from_collection_type(&ct),
            PrimaryEngine::KeyValue
        );
    }

    #[test]
    fn primary_engine_serde_roundtrip() {
        for variant in [
            PrimaryEngine::Document,
            PrimaryEngine::Strict,
            PrimaryEngine::KeyValue,
            PrimaryEngine::Columnar,
            PrimaryEngine::Spatial,
            PrimaryEngine::Vector,
        ] {
            let json = sonic_rs::to_string(&variant).unwrap();
            let back: PrimaryEngine = sonic_rs::from_str(&json).unwrap();
            assert_eq!(back, variant);
        }
    }

    #[test]
    fn primary_engine_msgpack_roundtrip() {
        for variant in [
            PrimaryEngine::Document,
            PrimaryEngine::Strict,
            PrimaryEngine::KeyValue,
            PrimaryEngine::Columnar,
            PrimaryEngine::Spatial,
            PrimaryEngine::Vector,
        ] {
            let bytes = zerompk::to_msgpack_vec(&variant).unwrap();
            let back: PrimaryEngine = zerompk::from_msgpack(&bytes).unwrap();
            assert_eq!(back, variant);
        }
    }

    #[test]
    fn vector_primary_config_serde_roundtrip() {
        let cfg = VectorPrimaryConfig {
            vector_field: "embedding".to_string(),
            dim: 1024,
            quantization: VectorQuantization::RaBitQ,
            m: 32,
            ef_construction: 200,
            metric: DistanceMetric::Cosine,
            storage_dtype: VectorStorageDtype::F32,
            payload_indexes: vec![
                ("category".to_string(), PayloadIndexKind::Equality),
                ("timestamp".to_string(), PayloadIndexKind::Range),
            ],
        };
        let json = sonic_rs::to_string(&cfg).unwrap();
        let back: VectorPrimaryConfig = sonic_rs::from_str(&json).unwrap();
        assert_eq!(back, cfg);
    }

    #[test]
    fn vector_primary_config_msgpack_roundtrip() {
        let cfg = VectorPrimaryConfig {
            vector_field: "vec".to_string(),
            dim: 512,
            quantization: VectorQuantization::Bbq,
            m: 16,
            ef_construction: 100,
            metric: DistanceMetric::L2,
            storage_dtype: VectorStorageDtype::F32,
            payload_indexes: vec![],
        };
        let bytes = zerompk::to_msgpack_vec(&cfg).unwrap();
        let back: VectorPrimaryConfig = zerompk::from_msgpack(&bytes).unwrap();
        assert_eq!(back, cfg);
    }
}