selene-db-core 1.3.0

Foundation types for the selene-db ISO/IEC 39075:2024 GQL property graph engine.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! In-memory GQL value representation per spec 02 section 3.
//!
//! The [`Value`] variant order is canonical and append-only. Reordering,
//! removing, or inserting variants in the middle is a major-version and
//! durability-format change. The serde/postcard and rkyv serialization
//! derives are part of the same durability contract.

use std::sync::Arc;

use serde::{Deserialize, Deserializer, Serialize};
use smallvec::SmallVec;

use crate::db_string::DbString;
use crate::error::{CoreError, CoreResult};
use crate::extension_type_ids::ExtensionTypeId;
use crate::identity::{BindingTableId, EdgeId, GraphId, NodeId, RecordTypeId};
use crate::json_value::JsonValue;

/// Maximum component count for a native dense vector value.
///
/// The cap keeps dimensions representable in a compact `u16` slot for future
/// vector-index metadata while allowing common embedding sizes.
pub const MAX_VECTOR_DIMENSION: usize = u16::MAX as usize;

/// In-memory representation of a GQL value.
///
/// IA001: default floating-point arithmetic is IEEE 754 binary64; `Float32`
/// remains distinct for schema storage. Rust equality preserves GQL's
/// `+0.0 == -0.0` behavior, while NaN ordering is handled by query-engine
/// `ORDER BY` logic outside this crate.
///
/// Value equality matches IEEE 754 for non-NaN AND treats all NaN bit-patterns
/// as equal for round-trip integrity. This is the internal Rust-level equality
/// used by `PropertyMap` serde round-trip and snapshot diffs. The GQL `=`
/// operator is intercepted at the runtime layer (`runtime::value_compare`)
/// and preserves ISO 3VL semantics — `NaN = NaN` returns NULL there.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub enum Value {
    /// Boolean value.
    Bool(bool),
    /// Signed integer up to 64 bits.
    Int(i64),
    /// Unsigned integer up to 64 bits.
    Uint(u64),
    /// Signed 128-bit integer.
    Int128(#[serde(with = "serde_i128_le")] i128),
    /// Unsigned 128-bit integer.
    Uint128(#[serde(with = "serde_u128_le")] u128),
    /// Default floating-point value.
    Float(f64),
    /// Distinct 32-bit floating-point value.
    Float32(f32),
    /// Fixed-precision decimal value.
    Decimal(#[serde(with = "serde_decimal_str")] rust_decimal::Decimal),
    /// String value.
    String(DbString),
    /// Byte-string value.
    Bytes(Arc<[u8]>),
    /// List value.
    List(Vec<Value>),
    /// Open record value.
    Record(Box<Record>),
    /// Closed record value tied to a graph-type-defined record type.
    RecordTyped(Box<RecordTyped>),
    /// Path value.
    ///
    /// Boxed (CORE-06): an inline `Path` is 120 B and was the `size_of::<Value>`
    /// ceiling. Paths are ephemeral traversal results, rarely stored, so moving
    /// one behind a pointer shrinks every `Value` clone/move to a pointer copy.
    Path(Box<Path>),
    /// Node reference value.
    NodeRef(NodeId),
    /// Edge reference value.
    EdgeRef(EdgeId),
    /// Graph reference value.
    GraphRef(GraphId),
    /// Binding-table reference value.
    TableRef(BindingTableId),
    /// Zoned datetime value.
    ///
    /// Boxed (CORE-06): `jiff::Zoned` is 40 B; temporal values are uncommon in
    /// hot graph data, so the indirection is paid only on temporal access.
    ZonedDateTime(Box<jiff::Zoned>),
    /// Local datetime value.
    LocalDateTime(jiff::civil::DateTime),
    /// Date value.
    Date(jiff::civil::Date),
    /// Zoned time value.
    ///
    /// `jiff` 0.2 has no dedicated zoned-time type, so selene-core uses
    /// `jiff::Zoned`; date components are ignored at the GQL boundary.
    ///
    /// Boxed (CORE-06): see [`Value::ZonedDateTime`].
    ZonedTime(Box<jiff::Zoned>),
    /// Local time value.
    LocalTime(jiff::civil::Time),
    /// Duration value.
    ///
    /// Boxed (CORE-06): `jiff::Span` is 64 B (the largest time variant); boxing
    /// it keeps the post-`Path` ceiling off `Value`.
    Duration(Box<jiff::Span>),
    /// Extension-owned opaque payload.
    Extended {
        /// Registered extension type ID.
        type_id: ExtensionTypeId,
        /// Extension-owned byte payload.
        payload: Arc<[u8]>,
    },
    /// Null value.
    Null,
    /// UUID value.
    Uuid(uuid::Uuid),
    /// Native dense vector value.
    Vector(VectorValue),
    /// Native JSON value.
    Json(JsonValue),
}

/// Compile-time ceiling on `size_of::<Value>` — a zero-cost re-bloat tripwire.
///
/// `Value` is moved and cloned on every property read, `PropertyMap` copy, and
/// binding-table row, so its in-memory size is a hot-path cost multiplier (see
/// the `value_clone` bench). CORE-06 boxed the four oversized variants —
/// `Path` (120 B, which a `size_of` profile proved was the real former ceiling,
/// **not** the time variants the design doc assumed), `Duration(jiff::Span)`
/// (64 B), and the two `jiff::Zoned` variants (40 B) — bringing `Value` from
/// 128 B down to 32 B. The current ceiling is set by 24-byte payload families
/// such as `List(Vec)`, plus the discriminant and 16-byte alignment from the
/// `i128`/`Decimal` variants. This assert fails the build if a future variant
/// regrows the enum; box the offending payload or lift the ceiling
/// deliberately.
const _: () = assert!(core::mem::size_of::<Value>() <= 32);

impl Value {
    /// Factory table with one sample value for each [`Value`] variant.
    ///
    /// The table is used by tests as an append-only ANCHOR: adding a new
    /// variant requires adding one factory here so the source-of-truth crate
    /// owns the variant census.
    pub const ALL: &[fn() -> Self] = &[
        || Self::Bool(false),
        || Self::Int(0),
        || Self::Uint(0),
        || Self::Int128(0),
        || Self::Uint128(0),
        || Self::Float(0.0),
        || Self::Float32(0.0),
        || Self::Decimal(rust_decimal::Decimal::ZERO),
        || Self::String(value_variant_string("value.all.string")),
        || Self::Bytes(Arc::from([0_u8])),
        || Self::List(Vec::new()),
        || Self::Record(Box::new(Record::Open(SmallVec::new()))),
        || {
            Self::RecordTyped(Box::new(RecordTyped {
                type_id: RecordTypeId::new(1),
                values: SmallVec::new(),
            }))
        },
        || {
            Self::Path(Box::new(Path {
                graph: GraphId::new(1),
                start: NodeId::new(1),
                segments: SmallVec::new(),
            }))
        },
        || Self::NodeRef(NodeId::new(1)),
        || Self::EdgeRef(EdgeId::new(1)),
        || Self::GraphRef(GraphId::new(1)),
        || Self::TableRef(BindingTableId::new(1)),
        || Self::ZonedDateTime(Box::new(value_variant_zoned())),
        || Self::LocalDateTime("2024-01-01T00:00:00".parse().unwrap()),
        || Self::Date("2024-01-01".parse().unwrap()),
        || Self::ZonedTime(Box::new(value_variant_zoned())),
        || Self::LocalTime("00:00:00".parse().unwrap()),
        || Self::Duration(Box::new("PT1S".parse().unwrap())),
        || Self::Extended {
            type_id: ExtensionTypeId::FIRST_PARTY_MIN,
            payload: Arc::from([0_u8]),
        },
        || Self::Null,
        || Self::Uuid(uuid::Uuid::nil()),
        || Self::Vector(VectorValue::new(vec![0.0]).expect("fixture vector is valid")),
        || Self::Json(JsonValue::new(serde_json::json!({"fixture": true})).unwrap()),
    ];

    /// Number of known [`Value`] variants in this build.
    pub const VARIANT_COUNT: usize = Self::ALL.len();

    /// Stable telemetry name for this value variant.
    ///
    /// This match is exhaustive in `selene-core`, so a future variant addition
    /// forces the defining crate to choose the new public name once.
    #[must_use]
    pub fn variant_name(&self) -> &'static str {
        match self {
            Self::Bool(_) => "Bool",
            Self::Int(_) => "Int",
            Self::Uint(_) => "Uint",
            Self::Int128(_) => "Int128",
            Self::Uint128(_) => "Uint128",
            Self::Float(_) => "Float",
            Self::Float32(_) => "Float32",
            Self::Decimal(_) => "Decimal",
            Self::String(_) => "String",
            Self::Bytes(_) => "Bytes",
            Self::List(_) => "List",
            Self::Record(_) => "Record",
            Self::RecordTyped(_) => "RecordTyped",
            Self::Path(_) => "Path",
            Self::NodeRef(_) => "NodeRef",
            Self::EdgeRef(_) => "EdgeRef",
            Self::GraphRef(_) => "GraphRef",
            Self::TableRef(_) => "TableRef",
            Self::ZonedDateTime(_) => "ZonedDateTime",
            Self::LocalDateTime(_) => "LocalDateTime",
            Self::Date(_) => "Date",
            Self::ZonedTime(_) => "ZonedTime",
            Self::LocalTime(_) => "LocalTime",
            Self::Duration(_) => "Duration",
            Self::Extended { .. } => "Extended",
            Self::Null => "Null",
            Self::Uuid(_) => "Uuid",
            Self::Vector(_) => "Vector",
            Self::Json(_) => "Json",
        }
    }
}

fn value_variant_string(name: &str) -> DbString {
    crate::db_string(name).expect("Value::ALL fixture strings fit DB string cap")
}

fn value_variant_zoned() -> jiff::Zoned {
    jiff::Timestamp::new(0, 0)
        .expect("Value::ALL timestamp fixture is in range")
        .to_zoned(jiff::tz::TimeZone::UTC)
}

impl PartialEq for Value {
    fn eq(&self, rhs: &Self) -> bool {
        match (self, rhs) {
            (Self::Bool(lhs), Self::Bool(rhs)) => lhs == rhs,
            (Self::Int(lhs), Self::Int(rhs)) => lhs == rhs,
            (Self::Uint(lhs), Self::Uint(rhs)) => lhs == rhs,
            (Self::Int128(lhs), Self::Int128(rhs)) => lhs == rhs,
            (Self::Uint128(lhs), Self::Uint128(rhs)) => lhs == rhs,
            (Self::Float(lhs), Self::Float(rhs)) => lhs == rhs || (lhs.is_nan() && rhs.is_nan()),
            (Self::Float32(lhs), Self::Float32(rhs)) => {
                lhs == rhs || (lhs.is_nan() && rhs.is_nan())
            }
            (Self::Decimal(lhs), Self::Decimal(rhs)) => lhs == rhs,
            (Self::String(lhs), Self::String(rhs)) => lhs == rhs,
            (Self::Bytes(lhs), Self::Bytes(rhs)) => lhs == rhs,
            (Self::List(lhs), Self::List(rhs)) => lhs == rhs,
            (Self::Record(lhs), Self::Record(rhs)) => lhs == rhs,
            (Self::RecordTyped(lhs), Self::RecordTyped(rhs)) => lhs == rhs,
            (Self::Path(lhs), Self::Path(rhs)) => lhs == rhs,
            (Self::NodeRef(lhs), Self::NodeRef(rhs)) => lhs == rhs,
            (Self::EdgeRef(lhs), Self::EdgeRef(rhs)) => lhs == rhs,
            (Self::GraphRef(lhs), Self::GraphRef(rhs)) => lhs == rhs,
            (Self::TableRef(lhs), Self::TableRef(rhs)) => lhs == rhs,
            (Self::ZonedDateTime(lhs), Self::ZonedDateTime(rhs)) => lhs == rhs,
            (Self::LocalDateTime(lhs), Self::LocalDateTime(rhs)) => lhs == rhs,
            (Self::Date(lhs), Self::Date(rhs)) => lhs == rhs,
            (Self::ZonedTime(lhs), Self::ZonedTime(rhs)) => lhs == rhs,
            (Self::LocalTime(lhs), Self::LocalTime(rhs)) => lhs == rhs,
            (Self::Duration(lhs), Self::Duration(rhs)) => lhs.fieldwise() == rhs.fieldwise(),
            (
                Self::Extended {
                    type_id: lhs_type_id,
                    payload: lhs_payload,
                },
                Self::Extended {
                    type_id: rhs_type_id,
                    payload: rhs_payload,
                },
            ) => lhs_type_id == rhs_type_id && lhs_payload == rhs_payload,
            (Self::Null, Self::Null) => true,
            (Self::Uuid(lhs), Self::Uuid(rhs)) => lhs == rhs,
            (Self::Vector(lhs), Self::Vector(rhs)) => lhs == rhs,
            (Self::Json(lhs), Self::Json(rhs)) => lhs == rhs,
            _ => false,
        }
    }
}

/// Native dense vector payload stored as a first-class [`Value`].
///
/// `VectorValue` validates once at construction and deserialization so every
/// engine layer can assume a non-empty finite `f32` slice. NaN and infinity are
/// rejected because they make distance metrics, ordering fallbacks, hashing,
/// and approximate-nearest-neighbor indexes ambiguous.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(transparent)]
pub struct VectorValue {
    components: Arc<[f32]>,
}

impl VectorValue {
    /// Build a validated vector from owned components.
    pub fn new(components: impl Into<Vec<f32>>) -> CoreResult<Self> {
        let components = components.into();
        if components.is_empty() {
            return Err(CoreError::VectorEmpty);
        }
        if components.len() > MAX_VECTOR_DIMENSION {
            return Err(CoreError::VectorTooLarge {
                got: components.len(),
                max: MAX_VECTOR_DIMENSION,
            });
        }
        for (index, value) in components.iter().copied().enumerate() {
            if !value.is_finite() {
                return Err(CoreError::VectorComponentNotFinite { index, value });
            }
        }
        Ok(Self {
            components: Arc::from(components),
        })
    }

    /// Number of `f32` components in this vector.
    #[must_use]
    pub fn dimension(&self) -> usize {
        self.components.len()
    }

    /// Borrow the vector components.
    #[must_use]
    pub fn as_slice(&self) -> &[f32] {
        &self.components
    }

    /// Clone the shared component storage.
    #[must_use]
    pub fn as_arc(&self) -> Arc<[f32]> {
        Arc::clone(&self.components)
    }
}

impl TryFrom<Vec<f32>> for VectorValue {
    type Error = CoreError;

    fn try_from(value: Vec<f32>) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl From<VectorValue> for Vec<f32> {
    fn from(value: VectorValue) -> Self {
        value.components.as_ref().to_vec()
    }
}

impl<'de> Deserialize<'de> for VectorValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Vec::<f32>::deserialize(deserializer)
            .and_then(|components| Self::new(components).map_err(serde::de::Error::custom))
    }
}

/// Open record value.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[non_exhaustive]
pub enum Record {
    /// Open `RECORD` literal in expressions.
    Open(SmallVec<[(DbString, Value); 4]>),
}

/// Closed record value tied to a graph-type-defined record type.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct RecordTyped {
    /// Identifier pointing to a `RecordTypeDef` in the graph type catalog.
    pub type_id: RecordTypeId,
    /// Positional values aligned with the record type's field list.
    pub values: SmallVec<[Option<Value>; 4]>,
}

/// Path value.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct Path {
    /// Graph the path lives within.
    pub graph: GraphId,
    /// Starting node of the path.
    pub start: NodeId,
    /// Ordered segments traversed.
    pub segments: SmallVec<[PathSegment; 4]>,
}

/// One traversal step in a [`Path`].
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct PathSegment {
    /// Edge traversed in this step.
    pub edge: EdgeId,
    /// Direction of edge traversal.
    pub direction: EdgeDirection,
    /// Node reached after this step.
    pub node: NodeId,
}

/// Direction of edge traversal.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum EdgeDirection {
    /// Source-to-target traversal of a directed edge.
    Outgoing,
    /// Target-to-source traversal of a directed edge.
    Incoming,
    /// Undirected edge.
    Undirected,
}

mod serde_i128_le {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub(super) fn serialize<S>(value: &i128, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        value.to_le_bytes().serialize(serializer)
    }

    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<i128, D::Error>
    where
        D: Deserializer<'de>,
    {
        <[u8; 16]>::deserialize(deserializer).map(i128::from_le_bytes)
    }
}

mod serde_u128_le {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub(super) fn serialize<S>(value: &u128, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        value.to_le_bytes().serialize(serializer)
    }

    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<u128, D::Error>
    where
        D: Deserializer<'de>,
    {
        <[u8; 16]>::deserialize(deserializer).map(u128::from_le_bytes)
    }
}

mod serde_decimal_str {
    use std::str::FromStr;

    use serde::{Deserialize, Deserializer, Serializer};

    pub(super) fn serialize<S>(
        value: &rust_decimal::Decimal,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&value.to_string())
    }

    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<rust_decimal::Decimal, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        rust_decimal::Decimal::from_str(&value).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests;