Skip to main content

reddb_engine/storage/
entity.rs

1//! Unified Entity Model
2//!
3//! Provides a single entity type that can represent table rows, graph nodes,
4//! graph edges, or vectors with seamless interoperability.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8
9use reddb_types::Value;
10
11/// The first entity-id handed to user-inserted data. Ids `1..FIRST_USER_ENTITY_ID`
12/// are reserved for the internal collection-descriptor and config-default entities
13/// the engine seeds at boot, so the first user-inserted `rid` is a STABLE,
14/// documented value regardless of how many config defaults a build ships.
15///
16/// Before this floor existed the offset drifted upward by one for every config
17/// default added (101 → 114 over time), silently breaking the documented
18/// file-format invariant (#1369). The boot sequence bumps the allocator up to
19/// this floor after seeding internals; it only ever raises the counter, so a
20/// database that already holds user data is untouched. Mirrors
21/// `FIRST_USER_LABEL_ID` in the graph label registry.
22pub const FIRST_USER_ENTITY_ID: u64 = 1024;
23
24pub use super::entity_id::EntityId;
25
26/// The kind of entity (what storage type it belongs to)
27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28pub enum EntityKind {
29    /// A row in a structured table (hot path — kept inline for cache performance)
30    TableRow { table: Arc<str>, row_id: u64 },
31    /// A node in the graph (boxed — saves ~56 bytes per entity for table rows)
32    GraphNode(Box<GraphNodeKind>),
33    /// An edge in the graph (boxed)
34    GraphEdge(Box<GraphEdgeKind>),
35    /// A vector in a collection
36    Vector { collection: String },
37    /// A time-series data point (boxed)
38    TimeSeriesPoint(Box<TimeSeriesPointKind>),
39    /// A queue message
40    QueueMessage { queue: String, position: u64 },
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct GraphNodeKind {
45    pub label: String,
46    pub node_type: String,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct GraphEdgeKind {
51    pub label: String,
52    pub from_node: String,
53    pub to_node: String,
54    pub weight: u32,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Hash)]
58pub struct TimeSeriesPointKind {
59    pub series: String,
60    pub metric: String,
61}
62
63impl EntityKind {
64    /// Get the storage type as a string
65    pub fn storage_type(&self) -> &'static str {
66        match self {
67            Self::TableRow { .. } => "table",
68            Self::GraphNode(_) => "graph_node",
69            Self::GraphEdge(_) => "graph_edge",
70            Self::Vector { .. } => "vector",
71            Self::TimeSeriesPoint(_) => "timeseries",
72            Self::QueueMessage { .. } => "queue",
73        }
74    }
75
76    /// Get the collection/table name
77    pub fn collection(&self) -> &str {
78        match self {
79            Self::TableRow { table, .. } => table,
80            Self::GraphNode(n) => &n.label,
81            Self::GraphEdge(e) => &e.label,
82            Self::Vector { collection } => collection,
83            Self::TimeSeriesPoint(ts) => &ts.series,
84            Self::QueueMessage { queue, .. } => queue,
85        }
86    }
87}
88
89/// The actual data content of an entity
90#[derive(Debug, Clone)]
91pub enum EntityData {
92    /// Table row data
93    Row(RowData),
94    /// Graph node data
95    Node(NodeData),
96    /// Graph edge data
97    Edge(EdgeData),
98    /// Vector data
99    Vector(VectorData),
100    /// Time-series data point
101    TimeSeries(TimeSeriesData),
102    /// Queue message data
103    QueueMessage(QueueMessageData),
104}
105
106impl EntityData {
107    /// Check if this is row data
108    pub fn is_row(&self) -> bool {
109        matches!(self, Self::Row(_))
110    }
111
112    /// Check if this is node data
113    pub fn is_node(&self) -> bool {
114        matches!(self, Self::Node(_))
115    }
116
117    /// Check if this is edge data
118    pub fn is_edge(&self) -> bool {
119        matches!(self, Self::Edge(_))
120    }
121
122    /// Check if this is vector data
123    pub fn is_vector(&self) -> bool {
124        matches!(self, Self::Vector(_))
125    }
126
127    /// Get as row data
128    pub fn as_row(&self) -> Option<&RowData> {
129        match self {
130            Self::Row(r) => Some(r),
131            _ => None,
132        }
133    }
134
135    /// Get as node data
136    pub fn as_node(&self) -> Option<&NodeData> {
137        match self {
138            Self::Node(n) => Some(n),
139            _ => None,
140        }
141    }
142
143    /// Get as edge data
144    pub fn as_edge(&self) -> Option<&EdgeData> {
145        match self {
146            Self::Edge(e) => Some(e),
147            _ => None,
148        }
149    }
150
151    /// Get as vector data
152    pub fn as_vector(&self) -> Option<&VectorData> {
153        match self {
154            Self::Vector(v) => Some(v),
155            _ => None,
156        }
157    }
158}
159
160/// Data for a table row
161#[derive(Debug, Clone)]
162pub struct RowData {
163    /// Column values in schema order
164    pub columns: Vec<Value>,
165    /// Named column access (optional, for convenience)
166    pub named: Option<HashMap<String, Value>>,
167    /// Shared column schema: column names in order (maps index → name).
168    /// When set, `columns` holds the values and `named` is None.
169    /// This saves ~60% memory vs per-row HashMap.
170    pub schema: Option<std::sync::Arc<Vec<String>>>,
171}
172
173impl RowData {
174    /// Create new row data from column values
175    pub fn new(columns: Vec<Value>) -> Self {
176        Self {
177            columns,
178            named: None,
179            schema: None,
180        }
181    }
182
183    /// Create row data with named columns
184    pub fn with_names(columns: Vec<Value>, names: Vec<String>) -> Self {
185        let named: HashMap<String, Value> =
186            names.into_iter().zip(columns.iter().cloned()).collect();
187        Self {
188            columns,
189            named: Some(named),
190            schema: None,
191        }
192    }
193
194    /// Replace a decoded named row with values in the authoritative schema's
195    /// order. Different dynamic shapes retain their named representation.
196    #[cfg(feature = "full")]
197    pub(crate) fn compact_with_schema(&mut self, schema: &std::sync::Arc<Vec<String>>) -> bool {
198        let Some(named) = &self.named else {
199            return false;
200        };
201        if named.len() != schema.len() || schema.iter().any(|name| !named.contains_key(name)) {
202            return false;
203        }
204        // Existing positional values are independently observable. Only drop
205        // their duplicate copy when the declared order agrees with them.
206        if !self.columns.is_empty()
207            && (self.columns.len() != schema.len()
208                || schema
209                    .iter()
210                    .zip(&self.columns)
211                    .any(|(name, value)| named.get(name) != Some(value)))
212        {
213            return false;
214        }
215        let mut named = self.named.take().expect("validated named row");
216        self.columns = schema
217            .iter()
218            .map(|name| named.remove(name).expect("validated schema field"))
219            .collect();
220        self.schema = Some(std::sync::Arc::clone(schema));
221        true
222    }
223
224    /// Get a named field value — checks named HashMap first, then schema+columns.
225    pub fn get_field(&self, name: &str) -> Option<&Value> {
226        // Fast path: named HashMap
227        if let Some(ref named) = self.named {
228            return named.get(name);
229        }
230        // Columnar path: use schema to find index
231        if let Some(ref schema) = self.schema {
232            if let Some(idx) = schema.iter().position(|s| s == name) {
233                return self.columns.get(idx);
234            }
235        }
236        None
237    }
238
239    /// Iterate over all (name, value) pairs — works for both named and columnar.
240    pub fn iter_fields(&self) -> Box<dyn Iterator<Item = (&str, &Value)> + '_> {
241        if let Some(ref named) = self.named {
242            Box::new(named.iter().map(|(k, v)| (k.as_str(), v)))
243        } else if let Some(ref schema) = self.schema {
244            Box::new(
245                schema
246                    .iter()
247                    .zip(self.columns.iter())
248                    .map(|(k, v)| (k.as_str(), v)),
249            )
250        } else {
251            Box::new(std::iter::empty())
252        }
253    }
254
255    /// Get column by index
256    pub fn get(&self, index: usize) -> Option<&Value> {
257        self.columns.get(index)
258    }
259
260    /// Get column by name
261    pub fn get_by_name(&self, name: &str) -> Option<&Value> {
262        self.named.as_ref()?.get(name)
263    }
264
265    /// Number of columns
266    pub fn len(&self) -> usize {
267        self.columns.len()
268    }
269
270    /// Check if empty
271    pub fn is_empty(&self) -> bool {
272        self.columns.is_empty()
273    }
274}
275
276/// Data for a graph node
277#[derive(Debug, Clone)]
278pub struct NodeData {
279    /// Node properties
280    pub properties: HashMap<String, Value>,
281}
282
283impl NodeData {
284    /// Create new node data
285    pub fn new() -> Self {
286        Self {
287            properties: HashMap::new(),
288        }
289    }
290
291    /// Create with properties
292    pub fn with_properties(properties: HashMap<String, Value>) -> Self {
293        Self { properties }
294    }
295
296    /// Set a property
297    pub fn set(&mut self, key: impl Into<String>, value: Value) {
298        self.properties.insert(key.into(), value);
299    }
300
301    /// Get a property
302    pub fn get(&self, key: &str) -> Option<&Value> {
303        self.properties.get(key)
304    }
305
306    /// Check if property exists
307    pub fn has(&self, key: &str) -> bool {
308        self.properties.contains_key(key)
309    }
310}
311
312impl Default for NodeData {
313    fn default() -> Self {
314        Self::new()
315    }
316}
317
318/// Data for a graph edge
319#[derive(Debug, Clone)]
320pub struct EdgeData {
321    /// Edge properties
322    pub properties: HashMap<String, Value>,
323    /// Edge weight (for weighted graphs)
324    pub weight: f32,
325}
326
327impl EdgeData {
328    /// Create new edge data
329    pub fn new(weight: f32) -> Self {
330        Self {
331            properties: HashMap::new(),
332            weight,
333        }
334    }
335
336    /// Create with properties
337    pub fn with_properties(weight: f32, properties: HashMap<String, Value>) -> Self {
338        Self { properties, weight }
339    }
340
341    /// Set a property
342    pub fn set(&mut self, key: impl Into<String>, value: Value) {
343        self.properties.insert(key.into(), value);
344    }
345
346    /// Get a property
347    pub fn get(&self, key: &str) -> Option<&Value> {
348        self.properties.get(key)
349    }
350}
351
352impl Default for EdgeData {
353    fn default() -> Self {
354        Self::new(1.0)
355    }
356}
357
358/// Data for a vector
359#[derive(Debug, Clone)]
360pub struct VectorData {
361    /// Dense vector (primary embedding)
362    pub dense: Vec<f32>,
363    /// Optional sparse vector
364    pub sparse: Option<SparseVector>,
365    /// Original content (if applicable)
366    pub content: Option<String>,
367}
368
369impl VectorData {
370    /// Create new vector data from dense vector
371    pub fn new(dense: Vec<f32>) -> Self {
372        Self {
373            dense,
374            sparse: None,
375            content: None,
376        }
377    }
378
379    /// Create with sparse vector
380    pub fn with_sparse(dense: Vec<f32>, sparse: SparseVector) -> Self {
381        Self {
382            dense,
383            sparse: Some(sparse),
384            content: None,
385        }
386    }
387
388    /// Set content
389    pub fn with_content(mut self, content: impl Into<String>) -> Self {
390        self.content = Some(content.into());
391        self
392    }
393
394    /// Get dimension
395    pub fn dimension(&self) -> usize {
396        self.dense.len()
397    }
398
399    /// Check if has sparse component
400    pub fn is_hybrid(&self) -> bool {
401        self.sparse.is_some()
402    }
403}
404
405/// Time-series data point
406#[derive(Debug, Clone)]
407pub struct TimeSeriesData {
408    /// Metric name (e.g., "cpu.idle")
409    pub metric: String,
410    /// Interned `(metric, canonical tags)` id for native time-series points.
411    pub series_id: Option<u64>,
412    /// Timestamp in nanoseconds since epoch
413    pub timestamp_ns: u64,
414    /// Metric value
415    pub value: f64,
416    /// Legacy/read-through dimensional tags (e.g., {"host": "srv1"}).
417    pub tags: std::collections::HashMap<String, String>,
418    /// Per-point fields that are not part of the immutable series identity.
419    pub fields: std::collections::HashMap<String, Value>,
420}
421
422/// Queue message data
423#[derive(Debug, Clone)]
424pub struct QueueMessageData {
425    /// Message payload
426    pub payload: Value,
427    /// Optional priority (higher = more urgent)
428    pub priority: Option<i32>,
429    /// Enqueue timestamp (nanoseconds)
430    pub enqueued_at_ns: u64,
431    /// Number of delivery attempts
432    pub attempts: u32,
433    /// Maximum delivery attempts before DLQ
434    pub max_attempts: u32,
435    /// Whether the message has been acknowledged
436    pub acked: bool,
437}
438
439/// Sparse vector representation
440#[derive(Debug, Clone)]
441pub struct SparseVector {
442    /// Indices of non-zero elements
443    pub indices: Vec<u32>,
444    /// Values at those indices
445    pub values: Vec<f32>,
446    /// Total dimension (may be larger than indices.len())
447    pub dimension: usize,
448}
449
450impl SparseVector {
451    /// Create new sparse vector
452    pub fn new(indices: Vec<u32>, values: Vec<f32>, dimension: usize) -> Self {
453        debug_assert_eq!(indices.len(), values.len());
454        Self {
455            indices,
456            values,
457            dimension,
458        }
459    }
460
461    /// Number of non-zero elements
462    pub fn nnz(&self) -> usize {
463        self.indices.len()
464    }
465
466    /// Sparsity ratio
467    pub fn sparsity(&self) -> f32 {
468        if self.dimension == 0 {
469            1.0
470        } else {
471            1.0 - (self.nnz() as f32 / self.dimension as f32)
472        }
473    }
474
475    /// Get value at index (0 if not present)
476    pub fn get(&self, index: u32) -> f32 {
477        self.indices
478            .iter()
479            .position(|&i| i == index)
480            .map(|pos| self.values[pos])
481            .unwrap_or(0.0)
482    }
483}
484
485/// A slot for embedding a specific aspect of an entity
486#[derive(Debug, Clone)]
487pub struct EmbeddingSlot {
488    /// Slot name (e.g., "content", "summary", "title", "code")
489    pub name: String,
490    /// The embedding vector
491    pub vector: Vec<f32>,
492    /// Model used to generate embedding
493    pub model: String,
494    /// Vector dimension
495    pub dimension: usize,
496    /// Generation timestamp
497    pub generated_at: u64,
498}
499
500use crate::clock::current_unix_secs;
501
502impl EmbeddingSlot {
503    /// Create a new embedding slot
504    pub fn new(name: impl Into<String>, vector: Vec<f32>, model: impl Into<String>) -> Self {
505        let dimension = vector.len();
506        Self {
507            name: name.into(),
508            vector,
509            model: model.into(),
510            dimension,
511            generated_at: current_unix_secs(),
512        }
513    }
514}
515
516/// A unified entity that can represent any storage type
517#[derive(Debug, Clone)]
518pub struct UnifiedEntity {
519    /// Unique entity identifier
520    pub id: EntityId,
521    /// Stable user-visible identity shared by all physical versions.
522    ///
523    /// `None` is the legacy encoding and resolves to `id`.
524    logical_id: Option<EntityId>,
525    /// What kind of entity this is
526    pub kind: EntityKind,
527    /// Creation timestamp
528    pub created_at: u64,
529    /// Last update timestamp
530    pub updated_at: u64,
531    /// The actual data content
532    pub data: EntityData,
533    /// Sequence ID for ordering/versioning
534    pub sequence_id: u64,
535    /// Field-name bloom filter (u64, zero-allocation).
536    ///
537    /// Each bit encodes one possible mid-character value: for field name `n`
538    /// the bit position is `n.as_bytes()[n.len()/2] & 63`. OR of all user
539    /// field names present in this entity. Cleared for schema-based bulk rows
540    /// (all rows share the same schema so bloom is segment-level).
541    ///
542    /// The compiled filter computes `required_bloom` from predicate field names
543    /// at compile time. If `entity.field_bloom & required_bloom != required_bloom`,
544    /// the entity cannot match and is skipped before any HashMap probe.
545    pub field_bloom: u64,
546    /// MVCC creation transaction ID (Phase 2.3 PG parity).
547    ///
548    /// `0` means "pre-MVCC" / auto-commit — visible to every snapshot. When
549    /// a BEGIN-wrapped INSERT runs, it stamps `xmin` with the transaction's
550    /// snapshot id so other concurrent transactions only see the row after
551    /// the writer commits (snapshot isolation semantics).
552    ///
553    /// Visibility rule: `xmin <= snapshot.xid && (xmax == 0 || xmax > snapshot.xid)`.
554    pub xmin: u64,
555    /// MVCC deletion transaction ID (Phase 2.3 PG parity).
556    ///
557    /// `0` means "live". Set to the deleting transaction's snapshot id on
558    /// DELETE/UPDATE (row is kept until VACUUM reclaims it). Snapshots with
559    /// `xid < xmax` still see the row; newer snapshots skip it.
560    pub xmax: u64,
561    /// Optional auxiliary data (embeddings, cross-refs).
562    /// None for most table rows — saves 40 bytes/entity.
563    aux: Option<Box<EntityAux>>,
564}
565
566/// Auxiliary entity data — only allocated when needed.
567#[derive(Debug, Clone, Default)]
568pub struct EntityAux {
569    /// Embedding slots (for multi-vector support)
570    pub embeddings: Vec<EmbeddingSlot>,
571    /// Cross-references to other entities
572    pub cross_refs: Vec<CrossRef>,
573}
574
575impl UnifiedEntity {
576    /// Normalize persisted runtime-owned collection identities while retaining
577    /// exact user collection names. This is idempotent and intentionally does
578    /// not rewrite graph labels, which are data rather than collection keys.
579    pub fn canonicalize_system_collection_names(&mut self) {
580        match &mut self.kind {
581            EntityKind::TableRow { table, .. } => {
582                if let Some(canonical) = super::system_collection_names::canonical_name(table) {
583                    *table = Arc::from(canonical);
584                }
585            }
586            EntityKind::Vector { collection } => {
587                if let Some(canonical) = super::system_collection_names::canonical_name(collection)
588                {
589                    *collection = canonical.to_owned();
590                }
591            }
592            EntityKind::TimeSeriesPoint(point) => {
593                if let Some(canonical) =
594                    super::system_collection_names::canonical_name(&point.series)
595                {
596                    point.series = canonical.to_owned();
597                }
598            }
599            EntityKind::QueueMessage { queue, .. } => {
600                if let Some(canonical) = super::system_collection_names::canonical_name(queue) {
601                    *queue = canonical.to_owned();
602                }
603            }
604            EntityKind::GraphNode(_) | EntityKind::GraphEdge(_) => {}
605        }
606        if let Some(aux) = &mut self.aux {
607            for reference in &mut aux.cross_refs {
608                if let Some(canonical) =
609                    super::system_collection_names::canonical_name(&reference.target_collection)
610                {
611                    reference.target_collection = canonical.to_owned();
612                }
613            }
614        }
615    }
616
617    /// Access embeddings (returns empty slice if no aux data).
618    pub fn embeddings(&self) -> &[EmbeddingSlot] {
619        self.aux
620            .as_ref()
621            .map(|a| a.embeddings.as_slice())
622            .unwrap_or(&[])
623    }
624
625    /// Access cross-references (returns empty slice if no aux data).
626    pub fn cross_refs(&self) -> &[CrossRef] {
627        self.aux
628            .as_ref()
629            .map(|a| a.cross_refs.as_slice())
630            .unwrap_or(&[])
631    }
632
633    /// Get mutable embeddings (allocates aux if needed).
634    pub fn embeddings_mut(&mut self) -> &mut Vec<EmbeddingSlot> {
635        &mut self.aux.get_or_insert_with(Default::default).embeddings
636    }
637
638    /// Get mutable cross-refs (allocates aux if needed).
639    pub fn cross_refs_mut(&mut self) -> &mut Vec<CrossRef> {
640        &mut self.aux.get_or_insert_with(Default::default).cross_refs
641    }
642
643    /// Check if entity has any auxiliary data.
644    pub fn has_aux(&self) -> bool {
645        self.aux.is_some()
646    }
647}
648
649/// Compute one bit of a field-name bloom filter.
650///
651/// Uses the mid-character trick from MongoDB's field-name bloom:
652/// the bit position is the mid-byte value clamped to 0..63. Zero-allocation,
653/// ~1.5% false-positive rate for ≤5 distinct field names.
654#[inline]
655pub fn field_name_bloom(name: &str) -> u64 {
656    let b = name.as_bytes();
657    if b.is_empty() {
658        return 0;
659    }
660    1u64 << (b[b.len() / 2] & 63)
661}
662
663/// Compute the combined field-name bloom for all user-level fields in `data`.
664/// Returns 0 for schema-based rows (all rows share the same schema, so the
665/// per-entity bloom would be identical — caller uses a segment-level bloom).
666pub fn compute_entity_field_bloom(data: &EntityData) -> u64 {
667    match data {
668        EntityData::Row(row) => {
669            if row.schema.is_some() {
670                // Schema path: bloom is identical for every row in this table.
671                // Don't store per-entity — use segment-level bloom instead.
672                return 0;
673            }
674            if let Some(named) = &row.named {
675                let mut bloom = named.keys().fold(0u64, |acc, k| acc | field_name_bloom(k));
676                // Single-source documents no longer materialise promoted
677                // columns, so the body's top-level keys are the only place a
678                // `WHERE`/projection field lives. Fold them into the bloom so
679                // the field-bloom gate doesn't reject a row before the body
680                // read fallback ever runs. Inert for non-document rows (no
681                // binary-container `body` field) — `container_field_names`
682                // self-gates on the RDOC magic.
683                if let Some(Value::Json(bytes)) = named.get("body") {
684                    if let Ok(names) = reddb_types::document_body_codec::field_names(bytes) {
685                        for name in names {
686                            bloom |= field_name_bloom(&name);
687                        }
688                    }
689                }
690                bloom
691            } else {
692                0
693            }
694        }
695        EntityData::Node(node) => node
696            .properties
697            .keys()
698            .fold(0u64, |acc, k| acc | field_name_bloom(k)),
699        EntityData::Edge(edge) => edge
700            .properties
701            .keys()
702            .fold(0u64, |acc, k| acc | field_name_bloom(k)),
703        // Vectors, time-series, queue: no user-named fields worth blooming.
704        _ => 0,
705    }
706}
707
708impl UnifiedEntity {
709    /// Create a new unified entity
710    pub fn new(id: EntityId, kind: EntityKind, data: EntityData) -> Self {
711        let now = current_unix_secs();
712        let field_bloom = compute_entity_field_bloom(&data);
713
714        Self {
715            id,
716            logical_id: None,
717            kind,
718            created_at: now,
719            updated_at: now,
720            data,
721            sequence_id: 0,
722            field_bloom,
723            // Pre-MVCC default: xmin/xmax = 0 means visible to every snapshot.
724            // Transactional writers stamp real snapshot IDs after allocation.
725            xmin: 0,
726            xmax: 0,
727            aux: None,
728        }
729    }
730
731    /// MVCC visibility check (Phase 2.3 PG parity).
732    ///
733    /// Returns `true` when this tuple is visible under the provided
734    /// snapshot xid. Pre-MVCC rows (`xmin == 0`, `xmax == 0`) are visible
735    /// to every snapshot — preserves full compatibility with existing
736    /// data inserted before the MVCC headers existed.
737    ///
738    /// Snapshot isolation rule:
739    ///   - `xmin == 0 || xmin <= snapshot_xid`  (creator committed before snapshot)
740    ///   - `xmax == 0 || xmax > snapshot_xid`   (deleter committed after snapshot)
741    #[inline]
742    pub fn is_visible(&self, snapshot_xid: u64) -> bool {
743        if self.xmin != 0 && self.xmin > snapshot_xid {
744            return false;
745        }
746        if self.xmax != 0 && self.xmax <= snapshot_xid {
747            return false;
748        }
749        true
750    }
751
752    /// Stamp `xmin` (creation transaction ID). Called by the runtime on
753    /// INSERT inside an active transaction.
754    #[inline]
755    pub fn set_xmin(&mut self, xid: u64) {
756        self.xmin = xid;
757    }
758
759    /// Stamp `xmax` (deletion transaction ID). Called by the runtime on
760    /// DELETE/UPDATE inside an active transaction — the tuple survives
761    /// until VACUUM reclaims it.
762    #[inline]
763    pub fn set_xmax(&mut self, xid: u64) {
764        self.xmax = xid;
765    }
766
767    /// Stable user-visible identity. Legacy rows without an explicit
768    /// logical id map to their physical entity id.
769    #[inline]
770    pub fn logical_id(&self) -> EntityId {
771        self.logical_id.unwrap_or(self.id)
772    }
773
774    /// Returns true when the entity carries an explicit logical id on disk.
775    #[inline]
776    pub fn has_explicit_logical_id(&self) -> bool {
777        self.logical_id.is_some()
778    }
779
780    /// Set the stable user-visible identity for this physical version.
781    #[inline]
782    pub fn set_logical_id(&mut self, logical_id: EntityId) {
783        self.logical_id = Some(logical_id);
784    }
785
786    /// Ensure entities written by the current engine carry explicit
787    /// logical identity. Table rows + documents (Phase 1/2) and graph
788    /// nodes/edges (Phase 3) participate in the multi-model MVCC
789    /// versioning rollout and so need a stable logical id for
790    /// version-chain selection. Stamping the logical id is inert for
791    /// non-versioned collections: history only accrues through
792    /// `install_versioned_table_row_update`, which is gated on the
793    /// collection `versioned` flag, so a stamped-but-never-superseded
794    /// entity keeps `logical_id == id` and behaves exactly as before.
795    /// Vectors are intentionally excluded pending their read-path follow
796    /// up (no snapshot-honoring `VECTOR SEARCH`).
797    #[inline]
798    pub fn ensure_table_logical_id(&mut self) {
799        if self.logical_id.is_none()
800            && matches!(
801                self.kind,
802                EntityKind::TableRow { .. } | EntityKind::GraphNode(_) | EntityKind::GraphEdge(_)
803            )
804        {
805            self.logical_id = Some(self.id);
806        }
807    }
808
809    /// Create a table row entity
810    pub fn table_row(
811        id: EntityId,
812        table: impl Into<Arc<str>>,
813        row_id: u64,
814        columns: Vec<Value>,
815    ) -> Self {
816        Self::new(
817            id,
818            EntityKind::TableRow {
819                table: table.into(),
820                row_id,
821            },
822            EntityData::Row(RowData::new(columns)),
823        )
824    }
825
826    /// Create a graph node entity
827    pub fn graph_node(
828        id: EntityId,
829        label: impl Into<String>,
830        node_type: impl Into<String>,
831        properties: HashMap<String, Value>,
832    ) -> Self {
833        Self::new(
834            id,
835            EntityKind::GraphNode(Box::new(GraphNodeKind {
836                label: label.into(),
837                node_type: node_type.into(),
838            })),
839            EntityData::Node(NodeData::with_properties(properties)),
840        )
841    }
842
843    /// Create a graph edge entity
844    pub fn graph_edge(
845        id: EntityId,
846        label: impl Into<String>,
847        from: impl Into<String>,
848        to: impl Into<String>,
849        weight: f32,
850        properties: HashMap<String, Value>,
851    ) -> Self {
852        Self::new(
853            id,
854            EntityKind::GraphEdge(Box::new(GraphEdgeKind {
855                label: label.into(),
856                from_node: from.into(),
857                to_node: to.into(),
858                weight: (weight * 1000.0) as u32,
859            })),
860            EntityData::Edge(EdgeData::with_properties(weight, properties)),
861        )
862    }
863
864    /// Create a vector entity
865    pub fn vector(id: EntityId, collection: impl Into<String>, vector: Vec<f32>) -> Self {
866        Self::new(
867            id,
868            EntityKind::Vector {
869                collection: collection.into(),
870            },
871            EntityData::Vector(VectorData::new(vector)),
872        )
873    }
874
875    /// Add an embedding to this entity
876    pub fn add_embedding(&mut self, slot: EmbeddingSlot) {
877        self.embeddings_mut().push(slot);
878        self.touch();
879    }
880
881    /// Add a cross-reference
882    pub fn add_cross_ref(&mut self, cross_ref: CrossRef) {
883        self.cross_refs_mut().push(cross_ref);
884        self.touch();
885    }
886
887    /// Get embedding by slot name
888    pub fn get_embedding(&self, name: &str) -> Option<&EmbeddingSlot> {
889        self.embeddings().iter().find(|e| e.name == name)
890    }
891
892    /// Update timestamp
893    fn touch(&mut self) {
894        self.updated_at = current_unix_secs();
895    }
896
897    /// Check if entity is stale (not updated in given seconds)
898    pub fn is_stale(&self, max_age_secs: u64) -> bool {
899        let now = current_unix_secs();
900        now.saturating_sub(self.updated_at) > max_age_secs
901    }
902}
903
904/// A cross-reference between entities
905#[derive(Debug, Clone, PartialEq)]
906pub struct CrossRef {
907    /// Source entity ID (the entity that holds this reference)
908    pub source: EntityId,
909    /// Target entity ID
910    pub target: EntityId,
911    /// Target collection name
912    pub target_collection: String,
913    /// Type of reference
914    pub ref_type: RefType,
915    /// Reference weight/strength (0.0-1.0)
916    pub weight: f32,
917    /// When this reference was created
918    pub created_at: u64,
919}
920
921impl CrossRef {
922    /// Create a new cross-reference
923    pub fn new(
924        source: EntityId,
925        target: EntityId,
926        target_collection: impl Into<String>,
927        ref_type: RefType,
928    ) -> Self {
929        Self {
930            source,
931            target,
932            target_collection: target_collection.into(),
933            ref_type,
934            weight: 1.0,
935            created_at: current_unix_secs(),
936        }
937    }
938
939    /// Create with weight
940    pub fn with_weight(
941        source: EntityId,
942        target: EntityId,
943        target_collection: impl Into<String>,
944        ref_type: RefType,
945        weight: f32,
946    ) -> Self {
947        let mut cr = Self::new(source, target, target_collection, ref_type);
948        cr.weight = weight;
949        cr
950    }
951}
952
953/// Types of cross-references between entities
954#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
955pub enum RefType {
956    // Table ↔ Graph
957    RowToNode, // Table row represents a graph node
958    RowToEdge, // Table row represents a graph edge
959    NodeToRow, // Node links back to source row
960
961    // Table ↔ Vector
962    RowToVector, // Table row has embeddings
963    VectorToRow, // Vector search → source row
964
965    // Graph ↔ Vector
966    NodeToVector, // Node has embeddings
967    EdgeToVector, // Edge has embeddings
968    VectorToNode, // Vector search → source node
969
970    // Semantic links (discovered)
971    SimilarTo,   // Discovered by vector similarity
972    RelatedTo,   // Domain-specific relationship
973    DerivesFrom, // Data lineage
974    Mentions,    // Text mentions another entity
975    Contains,    // Structural containment
976    DependsOn,   // Dependency relationship
977}
978
979impl RefType {
980    /// Get the inverse reference type (for bidirectional tracking)
981    pub fn inverse(&self) -> Option<Self> {
982        match self {
983            Self::RowToNode => Some(Self::NodeToRow),
984            Self::NodeToRow => Some(Self::RowToNode),
985            Self::RowToVector => Some(Self::VectorToRow),
986            Self::VectorToRow => Some(Self::RowToVector),
987            Self::NodeToVector => Some(Self::VectorToNode),
988            Self::VectorToNode => Some(Self::NodeToVector),
989            Self::SimilarTo => Some(Self::SimilarTo), // Symmetric
990            Self::RelatedTo => Some(Self::RelatedTo), // Symmetric
991            _ => None,                                // One-directional references
992        }
993    }
994
995    /// Check if this is a symmetric reference type
996    pub fn is_symmetric(&self) -> bool {
997        matches!(self, Self::SimilarTo | Self::RelatedTo)
998    }
999
1000    /// Convert RefType to byte for binary serialization
1001    pub fn to_byte(&self) -> u8 {
1002        match self {
1003            Self::RowToNode => 0,
1004            Self::RowToEdge => 1,
1005            Self::NodeToRow => 2,
1006            Self::RowToVector => 3,
1007            Self::VectorToRow => 4,
1008            Self::NodeToVector => 5,
1009            Self::EdgeToVector => 6,
1010            Self::VectorToNode => 7,
1011            Self::SimilarTo => 8,
1012            Self::RelatedTo => 9,
1013            Self::DerivesFrom => 10,
1014            Self::Mentions => 11,
1015            Self::Contains => 12,
1016            Self::DependsOn => 13,
1017        }
1018    }
1019
1020    /// Create RefType from byte (binary deserialization)
1021    pub fn from_byte(byte: u8) -> Self {
1022        match byte {
1023            0 => Self::RowToNode,
1024            1 => Self::RowToEdge,
1025            2 => Self::NodeToRow,
1026            3 => Self::RowToVector,
1027            4 => Self::VectorToRow,
1028            5 => Self::NodeToVector,
1029            6 => Self::EdgeToVector,
1030            7 => Self::VectorToNode,
1031            8 => Self::SimilarTo,
1032            9 => Self::RelatedTo,
1033            10 => Self::DerivesFrom,
1034            11 => Self::Mentions,
1035            12 => Self::Contains,
1036            13 => Self::DependsOn,
1037            _ => Self::RelatedTo, // Default fallback
1038        }
1039    }
1040}
1041
1042/// Convert Vec<Value> to RowData
1043impl From<Vec<Value>> for RowData {
1044    fn from(columns: Vec<Value>) -> Self {
1045        RowData::new(columns)
1046    }
1047}
1048
1049/// Convert HashMap to NodeData
1050impl From<HashMap<String, Value>> for NodeData {
1051    fn from(properties: HashMap<String, Value>) -> Self {
1052        NodeData::with_properties(properties)
1053    }
1054}
1055
1056/// Convert dense vector to VectorData
1057impl From<Vec<f32>> for VectorData {
1058    fn from(dense: Vec<f32>) -> Self {
1059        VectorData::new(dense)
1060    }
1061}
1062
1063/// Convert tuple (dense, sparse) to VectorData
1064impl From<(Vec<f32>, SparseVector)> for VectorData {
1065    fn from((dense, sparse): (Vec<f32>, SparseVector)) -> Self {
1066        VectorData::with_sparse(dense, sparse)
1067    }
1068}
1069
1070// Helper trait for uniform entity creation
1071impl UnifiedEntity {
1072    /// Create a graph node entity from properties map
1073    pub fn from_properties(
1074        id: EntityId,
1075        label: impl Into<String>,
1076        node_type: impl Into<String>,
1077        properties: impl IntoIterator<Item = (impl Into<String>, Value)>,
1078    ) -> Self {
1079        let props: HashMap<String, Value> =
1080            properties.into_iter().map(|(k, v)| (k.into(), v)).collect();
1081        Self::graph_node(id, label, node_type, props)
1082    }
1083
1084    /// Convert entity to row data if applicable
1085    pub fn into_row(self) -> Option<RowData> {
1086        match self.data {
1087            EntityData::Row(r) => Some(r),
1088            _ => None,
1089        }
1090    }
1091
1092    /// Convert entity to node data if applicable
1093    pub fn into_node(self) -> Option<NodeData> {
1094        match self.data {
1095            EntityData::Node(n) => Some(n),
1096            _ => None,
1097        }
1098    }
1099
1100    /// Convert entity to edge data if applicable
1101    pub fn into_edge(self) -> Option<EdgeData> {
1102        match self.data {
1103            EntityData::Edge(e) => Some(e),
1104            _ => None,
1105        }
1106    }
1107
1108    /// Convert entity to vector data if applicable
1109    pub fn into_vector(self) -> Option<VectorData> {
1110        match self.data {
1111            EntityData::Vector(v) => Some(v),
1112            _ => None,
1113        }
1114    }
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119    use super::*;
1120
1121    #[test]
1122    fn test_entity_creation() {
1123        let id = EntityId::new(1);
1124        let entity = UnifiedEntity::table_row(
1125            id,
1126            "users",
1127            100,
1128            vec![Value::text("alice".to_string()), Value::Integer(25)],
1129        );
1130
1131        assert!(entity.data.is_row());
1132        assert_eq!(entity.kind.storage_type(), "table");
1133        assert_eq!(entity.kind.collection(), "users");
1134    }
1135
1136    #[test]
1137    fn test_cross_refs() {
1138        let id1 = EntityId::new(1);
1139        let id2 = EntityId::new(2);
1140
1141        let cross_ref = CrossRef::new(id1, id2, "nodes", RefType::RowToNode);
1142        assert_eq!(cross_ref.source, id1);
1143        assert_eq!(cross_ref.target, id2);
1144        assert_eq!(cross_ref.ref_type.inverse(), Some(RefType::NodeToRow));
1145    }
1146
1147    #[test]
1148    fn test_sparse_vector() {
1149        let sparse = SparseVector::new(vec![0, 5, 10], vec![1.0, 2.0, 3.0], 100);
1150
1151        assert_eq!(sparse.nnz(), 3);
1152        assert_eq!(sparse.get(5), 2.0);
1153        assert_eq!(sparse.get(3), 0.0);
1154        assert!(sparse.sparsity() > 0.9);
1155    }
1156
1157    #[test]
1158    fn test_embedding_slots() {
1159        let mut entity = UnifiedEntity::table_row(
1160            EntityId::new(1),
1161            "documents",
1162            1,
1163            vec![Value::text("Hello world".to_string())],
1164        );
1165
1166        entity.add_embedding(EmbeddingSlot::new(
1167            "content",
1168            vec![0.1, 0.2, 0.3],
1169            "text-embedding-3-small",
1170        ));
1171
1172        assert_eq!(entity.embeddings().len(), 1);
1173        assert!(entity.get_embedding("content").is_some());
1174        assert!(entity.get_embedding("summary").is_none());
1175    }
1176}