Skip to main content

uni_store/runtime/
l0.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2024-2026 Dragonscale Team
3
4use crate::runtime::wal::{Mutation, WriteAheadLog};
5use anyhow::Result;
6use std::collections::{HashMap, HashSet};
7use std::sync::Arc;
8use std::time::{SystemTime, UNIX_EPOCH};
9use tracing::{instrument, trace};
10use uni_common::core::id::{Eid, Vid};
11use uni_common::graph::simple_graph::{Direction, SimpleGraph};
12use uni_common::{Properties, Value};
13use uni_crdt::Crdt;
14
15/// Items a read-write transaction observed during execution, used for SSI
16/// read-write antidependency detection at commit.
17///
18/// Shared (via `Arc<Mutex<_>>`) between the read path — which records reads
19/// through the transaction's `QueryContext` — and the commit path, which checks
20/// it against concurrently-committed write-sets. Item-level granularity;
21/// phantoms are out of scope (handled by the `FOR UPDATE` escape hatch).
22#[derive(Debug, Default)]
23pub struct OccReadSet {
24    /// Vertices the transaction read.
25    pub vertices: HashSet<Vid>,
26    /// Edges the transaction read.
27    pub edges: HashSet<Eid>,
28}
29
30impl OccReadSet {
31    /// `true` when nothing has been read yet. Used to decide whether a `FOR
32    /// UPDATE` acquisition may safely re-pin a still-fresh transaction.
33    pub fn is_empty(&self) -> bool {
34        self.vertices.is_empty() && self.edges.is_empty()
35    }
36}
37
38/// Returns the current timestamp in nanoseconds since Unix epoch.
39fn now_nanos() -> i64 {
40    SystemTime::now()
41        .duration_since(UNIX_EPOCH)
42        .map(|d| d.as_nanos() as i64)
43        .unwrap_or(0)
44}
45
46/// Returns the [`Crdt`] a property value encodes, or `None` if it is not one.
47///
48/// `Crdt` is `#[serde(tag = "t", content = "d")]`, so it deserializes only from a
49/// JSON object, and only `Value::Map(_)` produces one — gating on `Map` avoids
50/// allocating a JSON tree for large non-map values (e.g. embedding columns).
51///
52/// This is the single source of truth for "is this value CRDT-mergeable": both
53/// the commit-time merge ([`L0Buffer::merge_crdt_properties`]) and the OCC
54/// write-set carve-out ([`crate::runtime::occ::WriteSet::from_l0`]) consult it,
55/// so the carve-out can never exclude an item the merge would actually overwrite
56/// (which would silently lose an update).
57pub(crate) fn try_as_crdt(v: &Value) -> Option<Crdt> {
58    if !matches!(v, Value::Map(_)) {
59        return None;
60    }
61    serde_json::from_value::<Crdt>(v.clone().into()).ok()
62}
63
64/// Serialize a constraint key for O(1) uniqueness checks.
65/// Format: label + separator + sorted (prop_name, value) pairs.
66pub fn serialize_constraint_key(label: &str, key_values: &[(String, Value)]) -> Vec<u8> {
67    let mut buf = label.as_bytes().to_vec();
68    buf.push(0); // separator
69    let mut sorted = key_values.to_vec();
70    sorted.sort_by(|a, b| a.0.cmp(&b.0));
71    for (k, v) in &sorted {
72        buf.extend(k.as_bytes());
73        buf.push(0);
74        // Use serde_json serialization for deterministic value encoding
75        buf.extend(serde_json::to_vec(v).unwrap_or_default());
76        buf.push(0);
77    }
78    buf
79}
80
81/// Per-type mutation counters accumulated by the L0 buffer.
82///
83/// Used to provide detailed mutation statistics (e.g., `nodes_created`,
84/// `relationships_deleted`) on `ExecuteResult`. Callers snapshot before/after
85/// execution and call [`diff()`](MutationStats::diff) to get the delta.
86#[derive(Debug, Clone, Default)]
87pub struct MutationStats {
88    pub nodes_created: usize,
89    pub nodes_deleted: usize,
90    pub relationships_created: usize,
91    pub relationships_deleted: usize,
92    pub properties_set: usize,
93    pub properties_removed: usize,
94    pub labels_added: usize,
95    pub labels_removed: usize,
96}
97
98impl MutationStats {
99    /// Compute the field-wise difference `self - before`.
100    pub fn diff(&self, before: &Self) -> Self {
101        Self {
102            nodes_created: self.nodes_created.saturating_sub(before.nodes_created),
103            nodes_deleted: self.nodes_deleted.saturating_sub(before.nodes_deleted),
104            relationships_created: self
105                .relationships_created
106                .saturating_sub(before.relationships_created),
107            relationships_deleted: self
108                .relationships_deleted
109                .saturating_sub(before.relationships_deleted),
110            properties_set: self.properties_set.saturating_sub(before.properties_set),
111            properties_removed: self
112                .properties_removed
113                .saturating_sub(before.properties_removed),
114            labels_added: self.labels_added.saturating_sub(before.labels_added),
115            labels_removed: self.labels_removed.saturating_sub(before.labels_removed),
116        }
117    }
118}
119
120#[derive(Clone, Debug)]
121pub struct TombstoneEntry {
122    pub eid: Eid,
123    pub src_vid: Vid,
124    pub dst_vid: Vid,
125    pub edge_type: u32,
126}
127
128pub struct L0Buffer {
129    /// Graph topology using simple adjacency lists
130    pub graph: SimpleGraph,
131    /// Soft-deleted edges (tombstones for LSM-style merging)
132    pub tombstones: HashMap<Eid, TombstoneEntry>,
133    /// Soft-deleted vertices
134    pub vertex_tombstones: HashSet<Vid>,
135    /// Edge version tracking for MVCC
136    pub edge_versions: HashMap<Eid, u64>,
137    /// Vertex version tracking for MVCC
138    pub vertex_versions: HashMap<Vid, u64>,
139    /// Edge properties (stored separately from topology)
140    pub edge_properties: HashMap<Eid, Properties>,
141    /// Vertex properties (stored separately from topology)
142    pub vertex_properties: HashMap<Vid, Properties>,
143    /// Edge endpoint lookup: eid -> (src, dst, type)
144    pub edge_endpoints: HashMap<Eid, (Vid, Vid, u32)>,
145    /// Vertex labels (VID -> list of label names)
146    /// New in storage design: vertices can have multiple labels
147    pub vertex_labels: HashMap<Vid, Vec<String>>,
148    /// Reverse index: label name → set of VIDs with that label. Maintained
149    /// alongside `vertex_labels` for O(1) label-based vertex lookups.
150    pub label_to_vids: HashMap<String, HashSet<Vid>>,
151    /// Vids whose FULL label set was explicitly replaced by a label mutation
152    /// (`SET n:Label` / `REMOVE n:Label`) in this buffer, via
153    /// [`L0Buffer::set_vertex_labels`]. Distinguishes a deliberate label
154    /// replacement from the empty `vertex_labels` entry a property-only write
155    /// incidentally creates (`entry().or_default()`), so `merge` knows to REPLACE
156    /// (not append) these vids' labels and `WriteSet::from_l0` knows they are
157    /// conflictable writes. A transaction-buffer concept; empty on main L0.
158    pub vertex_label_overwrites: HashSet<Vid>,
159    /// Edge types (EID -> type name)
160    pub edge_types: HashMap<Eid, String>,
161    /// Current version counter
162    pub current_version: u64,
163    /// Mutation count for flush decisions
164    pub mutation_count: usize,
165    /// Per-type mutation counters for detailed statistics.
166    pub mutation_stats: MutationStats,
167    /// Write-ahead log for durability
168    pub wal: Option<Arc<WriteAheadLog>>,
169    /// WAL LSN at the time this L0 was rotated for flush.
170    /// Used to ensure WAL truncation doesn't remove entries needed by pending flushes.
171    pub wal_lsn_at_flush: u64,
172    /// WAL LSN at the time this L0 became active (the previous rotation point).
173    ///
174    /// Everything at or below this LSN is durable in L1 before this buffer's own
175    /// data begins; while the buffer is pending flush its committed WAL entries
176    /// live strictly ABOVE it. It is therefore the floor below which WAL
177    /// truncation and a published `wal_high_water_mark` may safely advance —
178    /// using `wal_lsn_at_flush` (the high watermark) there would discard a
179    /// pending buffer's own not-yet-flushed entries (lost-commit on a graceful
180    /// close after a failed flush).
181    pub wal_lsn_at_start: u64,
182    /// Vertex creation timestamps (nanoseconds since epoch)
183    pub vertex_created_at: HashMap<Vid, i64>,
184    /// Vertex update timestamps (nanoseconds since epoch)
185    pub vertex_updated_at: HashMap<Vid, i64>,
186    /// Edge creation timestamps (nanoseconds since epoch)
187    pub edge_created_at: HashMap<Eid, i64>,
188    /// Edge update timestamps (nanoseconds since epoch)
189    pub edge_updated_at: HashMap<Eid, i64>,
190    /// Estimated size in bytes for memory limit enforcement.
191    /// Incremented O(1) on each mutation to avoid O(V+E) size_bytes() calls.
192    pub estimated_size: usize,
193    /// Per-constraint index for O(1) unique key checks.
194    /// Key: constraint composite key (label + sorted property values serialized).
195    /// Value: Vid that owns this key.
196    pub constraint_index: HashMap<Vec<u8>, Vid>,
197    /// Implicit MERGE-key guard for phantom-free `MERGE` *without* a declared
198    /// `UNIQUE` constraint. Same key format as `constraint_index` (built by
199    /// [`serialize_constraint_key`]), but populated only by a `MERGE` that
200    /// *creates* a node, and re-probed at commit only against other concurrent
201    /// `MERGE`-creates — so two concurrent `MERGE`s of the same key converge to
202    /// one node (the loser aborts retriably) instead of silently duplicating,
203    /// while a plain `CREATE` of the same properties is unaffected (it never
204    /// registers a key). Tombstoned with the owning vid; transient (not rebuilt
205    /// on recovery).
206    pub merge_guard_index: HashMap<Vec<u8>, Vid>,
207    /// Per-edge-constraint index for O(1) unique edge-key checks. Mirrors
208    /// [`constraint_index`](Self::constraint_index) but keyed to a live edge's
209    /// `Eid` (built by [`serialize_constraint_key`] with the edge-type name as the
210    /// discriminator). Populated by the edge-insert path for declared edge-type
211    /// `Unique`/`NodeKey` constraints, tombstoned in `apply_edge_deletion`, and
212    /// rebuilt from live edge properties on recovery.
213    pub edge_constraint_index: HashMap<Vec<u8>, Eid>,
214    /// Reverse index `ext_id` → owning vid for O(1) global ext_id uniqueness
215    /// checks (`Writer::check_extid_globally_unique` previously scanned every
216    /// `vertex_properties` map per insert — O(n²) ingest). Maintained by the
217    /// vertex insert impls (synced to the post-CRDT-merge value) and by
218    /// `apply_vertex_deletion`, so merge and WAL replay keep it consistent
219    /// for free.
220    pub extid_index: HashMap<String, Vid>,
221    /// Per-VID set of property keys that should land via Lance MergeInsert
222    /// (partial-column update) at flush time. Populated by
223    /// `insert_vertex_partial`; cleared by full-row inserts and deletes.
224    /// A VID present here at flush time is emitted to the partial batch;
225    /// absent VIDs flush via the existing full-row Append.
226    pub vertex_partial_keys: HashMap<Vid, HashSet<String>>,
227    /// Edge analog of `vertex_partial_keys` (Round 12 §A). Populated by
228    /// `insert_edge_partial_full`; cleared by full-row inserts and edge
229    /// deletes. Per-edge-type delta-table flush honors these by emitting
230    /// a `MergeInsertBuilder` source with only the touched schema
231    /// columns plus `eid`, `op`, `_version`, `_updated_at`, and
232    /// `overflow_json` (when an overflow prop was touched).
233    pub edge_partial_keys: HashMap<Eid, HashSet<String>>,
234    /// Phase B (UniConfig::defer_embeddings): VIDs whose auto-embedding
235    /// was skipped at insert time and is owed at flush. Value = primary
236    /// label name (the rest of the embedding config is looked up from the
237    /// schema at flush time). Drained by `flush_stream_l1` before column
238    /// extraction; entries are removed when the embedding lands in the
239    /// vertex's L0 property map.
240    pub pending_embeddings: HashMap<Vid, String>,
241    /// Optimistic-concurrency read sequence (SSI). Stamped on a transaction's
242    /// private L0 at creation with the Writer's commit-sequence at that moment,
243    /// and consulted at commit to detect intervening conflicting commits. `0`
244    /// for the main L0 and when SSI is disabled.
245    pub occ_read_seq: u64,
246    /// Optimistic-concurrency read-set (SSI). `Some` on a read-write
247    /// transaction's private L0 when SSI tracking is active; the read path
248    /// records observed ids here and commit checks them for antidependencies.
249    /// `None` for the main L0 and read-only / SSI-disabled paths.
250    pub occ_read_set: Option<Arc<parking_lot::Mutex<OccReadSet>>>,
251    /// Optional plugin registry for registry-dispatched CRDT merges at
252    /// commit-time property merge (`merge_crdt_properties`).
253    ///
254    /// Behavior-preserving when absent: falls back to native
255    /// [`uni_crdt::Crdt::try_merge`] bit-for-bit when no provider is
256    /// registered. Stamped onto every live buffer by the owning `L0Manager`.
257    /// Not part of buffer identity — cloned buffers (forked ASSUME/ABDUCE L0s)
258    /// inherit it, but it is never serialized or flushed.
259    pub plugin_registry: Option<Arc<uni_plugin::PluginRegistry>>,
260}
261
262impl std::fmt::Debug for L0Buffer {
263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264        f.debug_struct("L0Buffer")
265            .field("vertex_count", &self.graph.vertex_count())
266            .field("edge_count", &self.graph.edge_count())
267            .field("tombstones", &self.tombstones.len())
268            .field("vertex_tombstones", &self.vertex_tombstones.len())
269            .field("current_version", &self.current_version)
270            .field("mutation_count", &self.mutation_count)
271            .finish()
272    }
273}
274
275impl Clone for L0Buffer {
276    /// Clone the L0 buffer for fork/restore (ASSUME/ABDUCE).
277    ///
278    /// The cloned buffer does NOT share the WAL reference — forked L0s are
279    /// ephemeral and should not write to the WAL.
280    fn clone(&self) -> Self {
281        Self {
282            graph: self.graph.clone(),
283            tombstones: self.tombstones.clone(),
284            vertex_tombstones: self.vertex_tombstones.clone(),
285            edge_versions: self.edge_versions.clone(),
286            vertex_versions: self.vertex_versions.clone(),
287            edge_properties: self.edge_properties.clone(),
288            vertex_properties: self.vertex_properties.clone(),
289            edge_endpoints: self.edge_endpoints.clone(),
290            vertex_labels: self.vertex_labels.clone(),
291            label_to_vids: self.label_to_vids.clone(),
292            vertex_label_overwrites: self.vertex_label_overwrites.clone(),
293            edge_types: self.edge_types.clone(),
294            current_version: self.current_version,
295            mutation_count: self.mutation_count,
296            mutation_stats: self.mutation_stats.clone(),
297            wal: None, // Forked L0s don't share the WAL
298            wal_lsn_at_flush: self.wal_lsn_at_flush,
299            wal_lsn_at_start: self.wal_lsn_at_start,
300            vertex_created_at: self.vertex_created_at.clone(),
301            vertex_updated_at: self.vertex_updated_at.clone(),
302            edge_created_at: self.edge_created_at.clone(),
303            edge_updated_at: self.edge_updated_at.clone(),
304            estimated_size: self.estimated_size,
305            constraint_index: self.constraint_index.clone(),
306            edge_constraint_index: self.edge_constraint_index.clone(),
307            merge_guard_index: self.merge_guard_index.clone(),
308            extid_index: self.extid_index.clone(),
309            vertex_partial_keys: self.vertex_partial_keys.clone(),
310            edge_partial_keys: self.edge_partial_keys.clone(),
311            pending_embeddings: self.pending_embeddings.clone(),
312            occ_read_seq: self.occ_read_seq,
313            // Forked L0s (ASSUME/ABDUCE) do not participate in OCC tracking.
314            occ_read_set: None,
315            // Inherit the registry so forked buffers merge custom CRDTs the
316            // same way the parent does.
317            plugin_registry: self.plugin_registry.clone(),
318        }
319    }
320}
321
322impl L0Buffer {
323    /// Append labels to a vec, skipping duplicates.
324    fn append_unique_labels(existing: &mut Vec<String>, labels: &[String]) {
325        for label in labels {
326            if !existing.contains(label) {
327                existing.push(label.clone());
328            }
329        }
330    }
331
332    /// Add a VID to the reverse label index for each of the given labels.
333    fn index_labels_for_vid(&mut self, vid: Vid, labels: &[String]) {
334        for label in labels {
335            self.label_to_vids
336                .entry(label.clone())
337                .or_default()
338                .insert(vid);
339        }
340    }
341
342    /// Read a vertex's current string `ext_id` from a property map.
343    fn extid_of(props: &Properties) -> Option<String> {
344        props
345            .get("ext_id")
346            .and_then(|v| v.as_str())
347            .map(str::to_owned)
348    }
349
350    /// Sync `extid_index` for `vid` around a property write.
351    ///
352    /// `old` / `new` are the vertex's ext_id before / after the CRDT merge —
353    /// the index always reflects the post-merge value, matching what the old
354    /// full scan in `Writer::check_extid_globally_unique` observed. Only
355    /// called when the incoming properties contain an `ext_id` key (the merge
356    /// cannot change the value otherwise).
357    fn sync_extid_index(&mut self, vid: Vid, old: Option<String>, new: Option<String>) {
358        if old == new {
359            return;
360        }
361        if let Some(old) = old
362            && self.extid_index.get(&old) == Some(&vid)
363        {
364            self.extid_index.remove(&old);
365        }
366        if let Some(new) = new {
367            self.extid_index.insert(new, vid);
368        }
369    }
370
371    /// Remove a VID from all label entries in the reverse index.
372    fn remove_vid_from_label_index(&mut self, vid: Vid) {
373        if let Some(labels) = self.vertex_labels.get(&vid) {
374            for label in labels {
375                if let Some(set) = self.label_to_vids.get_mut(label) {
376                    set.remove(&vid);
377                }
378            }
379        }
380    }
381
382    /// Replaces a vertex's FULL label set — the semantics of `SET n:Label` /
383    /// `REMOVE n:Label`, which resolve the new complete set before writing.
384    ///
385    /// Unlike [`add_vertex_labels`](Self::add_vertex_labels) (append), this clears
386    /// the vid's existing labels from the reverse index, sets the new set, and
387    /// re-indexes — so a removal actually removes. It marks the vid in
388    /// `vertex_label_overwrites` so `merge` REPLACES (not appends) these labels at
389    /// commit and `WriteSet::from_l0` treats the change as a conflictable write.
390    /// Increments `mutation_count` (a label change is a real mutation; its sibling
391    /// `remove_vertex_label` already does so).
392    pub fn set_vertex_labels(&mut self, vid: Vid, labels: &[String]) {
393        self.remove_vid_from_label_index(vid);
394        self.vertex_labels.insert(vid, labels.to_vec());
395        self.index_labels_for_vid(vid, labels);
396        self.vertex_label_overwrites.insert(vid);
397        self.current_version += 1;
398        self.mutation_count += 1;
399    }
400
401    /// Merge CRDT properties into an existing property map.
402    /// Attempts CRDT merge if both values are valid CRDTs, falls back to overwrite.
403    ///
404    /// When the entry is empty (new vertex insert), skips the expensive JSON
405    /// round-trip and directly assigns the properties.
406    ///
407    /// Logs a warning when a CRDT value is overwritten by a non-CRDT scalar
408    /// (limitation R1).
409    fn merge_crdt_properties(
410        entry: &mut Properties,
411        properties: Properties,
412        registry: Option<&Arc<uni_plugin::PluginRegistry>>,
413    ) {
414        // Fast path: new vertex with no existing properties — skip JSON round-trip
415        if entry.is_empty() {
416            *entry = properties;
417            return;
418        }
419
420        for (k, v) in properties {
421            // `try_as_crdt` performs the Map-gated CRDT probe (see its docs for the
422            // wide-row perf rationale). Sharing it with `WriteSet::from_l0` keeps the
423            // OCC carve-out consistent with this merge-versus-overwrite decision.
424            if let Some(mut new_crdt) = try_as_crdt(&v)
425                && let Some(existing_v) = entry.get(&k)
426                && let Ok(existing_crdt) = serde_json::from_value::<Crdt>(existing_v.clone().into())
427            {
428                // Use a fallible merge to avoid panic on type mismatch.
429                // Operand order: self=new (new_crdt), other=existing
430                // (existing_crdt) — existing-into-new. Preserve — a custom
431                // provider's merge may be non-commutative.
432                let merged = match registry {
433                    Some(reg) => new_crdt.merge_via_registry(&existing_crdt, reg).is_ok(),
434                    None => new_crdt.try_merge(&existing_crdt).is_ok(),
435                };
436                if merged && let Ok(merged_json) = serde_json::to_value(new_crdt) {
437                    entry.insert(k, uni_common::Value::from(merged_json));
438                    continue;
439                }
440                // CRDT variant mismatch (or a failed re-serialize): fall through to
441                // a last-writer-wins overwrite, discarding the existing CRDT's
442                // merged state. The OCC commit-time carve-out check
443                // (`occ::crdt_carveout_overwrite`) aborts a *concurrent* writer
444                // before reaching here, and write-time schema enforcement rejects a
445                // wrong declared variant; this warns on any residual (e.g. a
446                // single-writer variant change) so the discarded state is visible.
447                tracing::warn!(
448                    property = %k,
449                    existing_variant = existing_crdt.type_name(),
450                    "overwriting CRDT property with a different CRDT variant \
451                     (last-writer-wins); merged CRDT state is discarded"
452                );
453            } else if try_as_crdt(&v).is_none()
454                && entry.get(&k).is_some_and(|e| try_as_crdt(e).is_some())
455            {
456                // R1: an existing CRDT value is overwritten by a non-CRDT scalar
457                // (last-writer-wins), silently discarding the CRDT's merged state
458                // — a property written as BOTH a CRDT and last-writer-wins. The OCC
459                // write-set carve-out lets CRDT-only writers commit without
460                // conflicting, so a concurrent LWW write on the same property
461                // cannot be flagged as a conflict; surface it here instead.
462                tracing::warn!(
463                    property = %k,
464                    "overwriting CRDT property with non-CRDT value (last-writer-wins); \
465                     merged CRDT state is discarded"
466                );
467            }
468            // Fallback: Overwrite (last-writer-wins).
469            entry.insert(k, v);
470        }
471    }
472
473    /// Helper function to estimate property map size in bytes.
474    fn estimate_properties_size(props: &Properties) -> usize {
475        props.keys().map(|k| k.len() + 32).sum()
476    }
477
478    /// Returns an estimate of the buffer size in bytes.
479    /// Includes all fields for accurate memory accounting.
480    pub fn size_bytes(&self) -> usize {
481        let mut total = 0;
482
483        // Topology
484        total += self.graph.vertex_count() * 8;
485        total += self.graph.edge_count() * 24;
486
487        // Properties (rough estimate: key string + 32 bytes for value)
488        for props in self.vertex_properties.values() {
489            total += Self::estimate_properties_size(props);
490        }
491        for props in self.edge_properties.values() {
492            total += Self::estimate_properties_size(props);
493        }
494
495        // Metadata
496        total += self.tombstones.len() * 64;
497        total += self.vertex_tombstones.len() * 8;
498        total += self.edge_versions.len() * 16;
499        total += self.vertex_versions.len() * 16;
500        total += self.edge_endpoints.len() * 28; // (Vid, Vid, u32) = 8+8+4 + overhead
501
502        // Vertex labels
503        for labels in self.vertex_labels.values() {
504            total += labels.iter().map(|l| l.len() + 24).sum::<usize>();
505        }
506
507        // Reverse label index (label_to_vids)
508        for (label, vids) in &self.label_to_vids {
509            total += label.len() + 24 + vids.len() * 8 + 48; // string + HashSet overhead
510        }
511
512        // Edge types
513        for type_name in self.edge_types.values() {
514            total += type_name.len() + 24;
515        }
516
517        // Timestamps (4 maps, each entry is 16 bytes: 8-byte key + 8-byte i64 value)
518        total += self.vertex_created_at.len() * 16;
519        total += self.vertex_updated_at.len() * 16;
520        total += self.edge_created_at.len() * 16;
521        total += self.edge_updated_at.len() * 16;
522
523        total
524    }
525
526    pub fn new(start_version: u64, wal: Option<Arc<WriteAheadLog>>) -> Self {
527        Self {
528            graph: SimpleGraph::new(),
529            tombstones: HashMap::new(),
530            vertex_tombstones: HashSet::new(),
531            edge_versions: HashMap::new(),
532            vertex_versions: HashMap::new(),
533            edge_properties: HashMap::new(),
534            vertex_properties: HashMap::new(),
535            edge_endpoints: HashMap::new(),
536            vertex_labels: HashMap::new(),
537            label_to_vids: HashMap::new(),
538            vertex_label_overwrites: HashSet::new(),
539            edge_types: HashMap::new(),
540            current_version: start_version,
541            mutation_count: 0,
542            mutation_stats: MutationStats::default(),
543            wal,
544            wal_lsn_at_flush: 0,
545            wal_lsn_at_start: 0,
546            vertex_created_at: HashMap::new(),
547            vertex_updated_at: HashMap::new(),
548            edge_created_at: HashMap::new(),
549            edge_updated_at: HashMap::new(),
550            estimated_size: 0,
551            constraint_index: HashMap::new(),
552            edge_constraint_index: HashMap::new(),
553            merge_guard_index: HashMap::new(),
554            extid_index: HashMap::new(),
555            vertex_partial_keys: HashMap::new(),
556            edge_partial_keys: HashMap::new(),
557            pending_embeddings: HashMap::new(),
558            occ_read_seq: 0,
559            occ_read_set: None,
560            plugin_registry: None,
561        }
562    }
563
564    /// Install the plugin registry used for registry-dispatched CRDT merges.
565    ///
566    /// Stamped by the owning `L0Manager` onto every buffer it mints so the
567    /// commit-time merge (`merge_crdt_properties`) can route custom
568    /// CRDT kinds through a registered provider. Absent registry preserves
569    /// native [`uni_crdt::Crdt::try_merge`] behavior.
570    pub fn set_plugin_registry(&mut self, registry: Arc<uni_plugin::PluginRegistry>) {
571        self.plugin_registry = Some(registry);
572    }
573
574    pub fn insert_vertex(&mut self, vid: Vid, properties: Properties) {
575        self.insert_vertex_with_labels(vid, properties, &[]);
576    }
577
578    /// Insert a vertex with associated labels.
579    pub fn insert_vertex_with_labels(
580        &mut self,
581        vid: Vid,
582        properties: Properties,
583        labels: &[String],
584    ) {
585        self.insert_vertex_with_labels_impl(vid, properties, labels, false);
586    }
587
588    /// Core vertex insertion. When `skip_wal` is true, skips WAL append
589    /// (used during merge where the caller already wrote to WAL).
590    fn insert_vertex_with_labels_impl(
591        &mut self,
592        vid: Vid,
593        properties: Properties,
594        labels: &[String],
595        skip_wal: bool,
596    ) {
597        self.current_version += 1;
598        let version = self.current_version;
599        let now = now_nanos();
600
601        if !skip_wal && let Some(wal) = &self.wal {
602            let _ = wal.append(Mutation::InsertVertex {
603                vid,
604                properties: properties.clone(),
605                labels: labels.to_vec(),
606            });
607        }
608
609        // Full-row insert supersedes any pending partial-update state for
610        // this VID.
611        self.vertex_partial_keys.remove(&vid);
612
613        self.apply_vertex_write(vid, properties, labels, version, now);
614        self.mutation_stats.nodes_created += 1;
615    }
616
617    /// Insert a vertex's FULL property row, tagging `touched_keys` so the
618    /// flush emits exactly those columns via Lance `MergeInsertBuilder`
619    /// instead of a full-row Append.
620    ///
621    /// `props` MUST be the fully-merged property map (storage union
622    /// in-flight L0 union the new touched values, per
623    /// `PropertyManager::get_all_vertex_props_with_ctx`). The caller is
624    /// responsible for the union; L0 here just stores it so scans see
625    /// the complete row without per-key reconciliation.
626    ///
627    /// `touched_keys` lists the property keys this SET statement
628    /// actually assigned — the union of those across all coalesced
629    /// SetItems on this VID. Lance MergeInsert sends a source batch
630    /// with `_vid`, `_deleted`, `_version`, `_updated_at`, and those
631    /// touched columns; non-touched columns retain their pre-merge
632    /// values on the Lance side, skipping the wide-row write.
633    ///
634    /// A subsequent full-row `insert_vertex_with_labels` or
635    /// `delete_vertex` on the same VID clears the partial-keys entry
636    /// so partial state never outlives a stronger write.
637    pub fn insert_vertex_partial_full(
638        &mut self,
639        vid: Vid,
640        props: Properties,
641        touched_keys: HashSet<String>,
642        labels: &[String],
643    ) {
644        // Stage the full row through the existing partial-impl (same
645        // CRDT merge / version bump / timestamps), preserving the
646        // partial-keys entry so we can extend it below.
647        self.insert_vertex_with_labels_partial_impl(vid, props, labels, false);
648        self.vertex_partial_keys
649            .entry(vid)
650            .or_default()
651            .extend(touched_keys);
652    }
653
654    /// Legacy partial-only variant used by some uni-store paths. Kept
655    /// for source-compatibility but new uni-query callers should use
656    /// `insert_vertex_partial_full` to preserve scan-side L0 visibility.
657    pub fn insert_vertex_partial(&mut self, vid: Vid, touched: Properties, labels: &[String]) {
658        // Record dirty keys BEFORE the full-row impl runs (which would
659        // clear them). The keys come from the touched set; the values
660        // are merged into L0 by the shared CRDT path below.
661        let touched_keys: Vec<String> = touched.keys().cloned().collect();
662
663        // If the VID already has a full-row pending insert (e.g., CREATE
664        // earlier in the same tx), we must NOT downgrade it to partial.
665        // Detected by: VID is in vertex_properties WITH a version stamp
666        // AND not currently in vertex_partial_keys → it was written as
667        // a full row recently. The conservative rule: only enable the
668        // partial path when there's no full-row pending insert. We
669        // approximate "no full-row pending" by checking that the VID's
670        // current entry in vertex_partial_keys is non-empty OR the VID
671        // is not in vertex_properties (fresh row, but caller asked
672        // partial — let it through and the post-flush union covers it).
673        let already_full = self.vertex_properties.contains_key(&vid)
674            && !self.vertex_partial_keys.contains_key(&vid);
675
676        // Stage the CRDT merge through the existing path. We bypass the
677        // full-row `insert_vertex_with_labels_impl` clearing of
678        // partial_keys by inlining the work, then restoring/extending
679        // the partial-key set.
680        self.insert_vertex_with_labels_partial_impl(vid, touched, labels, false);
681
682        if !already_full {
683            self.vertex_partial_keys
684                .entry(vid)
685                .or_default()
686                .extend(touched_keys);
687        }
688    }
689
690    /// Core partial-insert: same as `insert_vertex_with_labels_impl` but
691    /// preserves any existing `vertex_partial_keys[vid]` entry so the
692    /// caller can extend it after the merge.
693    fn insert_vertex_with_labels_partial_impl(
694        &mut self,
695        vid: Vid,
696        properties: Properties,
697        labels: &[String],
698        skip_wal: bool,
699    ) {
700        self.current_version += 1;
701        let version = self.current_version;
702        let now = now_nanos();
703
704        if !skip_wal && let Some(wal) = &self.wal {
705            // WAL records the partial as a full-row InsertVertex; on replay
706            // the full-row path runs (which clears partial_keys). This is
707            // semantically correct — L0 in memory always holds the union of
708            // partial deltas via merge_crdt_properties; recovery doesn't
709            // need to preserve partial-vs-full distinction.
710            let _ = wal.append(Mutation::InsertVertex {
711                vid,
712                properties: properties.clone(),
713                labels: labels.to_vec(),
714            });
715        }
716
717        // NOTE: deliberately DOES NOT remove from vertex_partial_keys.
718        // The caller (`insert_vertex_partial`) extends that set after.
719        // Partial writes also don't bump `nodes_created` — they update
720        // existing nodes; `properties_set` is the correct counter.
721        self.apply_vertex_write(vid, properties, labels, version, now);
722    }
723
724    /// Shared body of the full-row and partial vertex-write paths: clear the
725    /// tombstone, CRDT-merge the properties (keeping the `ext_id` index in
726    /// sync), stamp version/timestamps, append the labels, and update the
727    /// mutation counters and size estimate.
728    ///
729    /// Reads nothing from `vertex_partial_keys`, so the two callers are free
730    /// to clear or preserve that entry around this call.
731    fn apply_vertex_write(
732        &mut self,
733        vid: Vid,
734        properties: Properties,
735        labels: &[String],
736        version: u64,
737        now: i64,
738    ) {
739        self.vertex_tombstones.remove(&vid);
740
741        // Size/count computed up front so `properties` can be moved into the
742        // CRDT merge below instead of deep-cloned.
743        let props_size = Self::estimate_properties_size(&properties);
744        let props_count = properties.len();
745        let tracks_extid = properties.contains_key("ext_id");
746
747        let entry = self.vertex_properties.entry(vid).or_default();
748        let old_extid = if tracks_extid {
749            Self::extid_of(entry)
750        } else {
751            None
752        };
753        Self::merge_crdt_properties(entry, properties, self.plugin_registry.as_ref());
754        if tracks_extid {
755            let new_extid =
756                Self::extid_of(self.vertex_properties.get(&vid).expect("just inserted"));
757            self.sync_extid_index(vid, old_extid, new_extid);
758        }
759        self.vertex_versions.insert(vid, version);
760
761        // Set timestamps - created_at only set if this is a new vertex
762        self.vertex_created_at.entry(vid).or_insert(now);
763        self.vertex_updated_at.insert(vid, now);
764
765        // Track labels — always create an entry so unlabeled vertices are
766        // distinguishable from "not in L0" when queried via get_vertex_labels.
767        let labels_size: usize = labels.iter().map(|l| l.len() + 24).sum();
768        let existing = self.vertex_labels.entry(vid).or_default();
769        Self::append_unique_labels(existing, labels);
770        self.index_labels_for_vid(vid, labels);
771
772        self.graph.add_vertex(vid);
773        self.mutation_count += 1;
774        self.mutation_stats.properties_set += props_count;
775        self.mutation_stats.labels_added += labels.len();
776
777        self.estimated_size += 8 + props_size + 16 + labels_size + 32;
778    }
779
780    /// Add labels to an existing vertex.
781    pub fn add_vertex_labels(&mut self, vid: Vid, labels: &[String]) {
782        let existing = self.vertex_labels.entry(vid).or_default();
783        Self::append_unique_labels(existing, labels);
784        self.index_labels_for_vid(vid, labels);
785    }
786
787    /// Remove a label from an existing vertex.
788    /// Returns true if the label was found and removed, false otherwise.
789    pub fn remove_vertex_label(&mut self, vid: Vid, label: &str) -> bool {
790        if let Some(labels) = self.vertex_labels.get_mut(&vid)
791            && let Some(pos) = labels.iter().position(|l| l == label)
792        {
793            labels.remove(pos);
794            if let Some(set) = self.label_to_vids.get_mut(label) {
795                set.remove(&vid);
796            }
797            self.current_version += 1;
798            self.mutation_count += 1;
799            self.mutation_stats.labels_removed += 1;
800            // Note: WAL logging for label mutations not yet implemented
801            // Currently consistent with add_vertex_labels behavior
802            return true;
803        }
804        false
805    }
806
807    /// Set the type for an edge.
808    pub fn set_edge_type(&mut self, eid: Eid, edge_type: String) {
809        self.edge_types.insert(eid, edge_type);
810    }
811
812    pub fn delete_vertex(&mut self, vid: Vid) -> Result<()> {
813        self.delete_vertex_impl(vid, false)
814    }
815
816    /// Core vertex deletion. When `skip_wal` is true, skips WAL append
817    /// (used during merge where the caller already wrote to WAL).
818    fn delete_vertex_impl(&mut self, vid: Vid, skip_wal: bool) -> Result<()> {
819        self.current_version += 1;
820
821        if !skip_wal && let Some(wal) = &mut self.wal {
822            let labels = self.vertex_labels.get(&vid).cloned().unwrap_or_default();
823            wal.append(Mutation::DeleteVertex { vid, labels })?;
824        }
825
826        self.apply_vertex_deletion(vid);
827        Ok(())
828    }
829
830    /// Cascade-delete a vertex: tombstone all connected edges and remove the vertex.
831    ///
832    /// Shared between `delete_vertex` (live mutations) and `replay_mutations` (WAL recovery).
833    fn apply_vertex_deletion(&mut self, vid: Vid) {
834        let version = self.current_version;
835
836        // Collect edges to delete using O(degree) neighbors() instead of O(E) scan
837        let mut edges_to_remove = HashSet::new();
838
839        // Collect outgoing edges
840        for entry in self.graph.neighbors(vid, Direction::Outgoing) {
841            edges_to_remove.insert(entry.eid);
842        }
843
844        // Collect incoming edges
845        for entry in self.graph.neighbors(vid, Direction::Incoming) {
846            edges_to_remove.insert(entry.eid); // HashSet handles self-loop deduplication
847        }
848
849        let cascaded_edges_count = edges_to_remove.len();
850
851        // Tombstone and remove all collected edges
852        for eid in edges_to_remove {
853            // Retrieve edge endpoints from the map to create tombstone
854            if let Some((src, dst, etype)) = self.edge_endpoints.get(&eid) {
855                self.tombstones.insert(
856                    eid,
857                    TombstoneEntry {
858                        eid,
859                        src_vid: *src,
860                        dst_vid: *dst,
861                        edge_type: *etype,
862                    },
863                );
864                self.edge_versions.insert(eid, version);
865                self.edge_endpoints.remove(&eid);
866                self.edge_properties.remove(&eid);
867                self.graph.remove_edge(eid);
868                self.mutation_count += 1;
869                self.mutation_stats.relationships_deleted += 1;
870            }
871        }
872
873        self.remove_vid_from_label_index(vid);
874        self.vertex_tombstones.insert(vid);
875        // Drop the vid's ext_id index entry (O(1) via its current property
876        // value, read before the property map entry is removed below).
877        if let Some(props) = self.vertex_properties.get(&vid)
878            && let Some(ext) = Self::extid_of(props)
879            && self.extid_index.get(&ext) == Some(&vid)
880        {
881            self.extid_index.remove(&ext);
882        }
883        self.vertex_properties.remove(&vid);
884        // Deletion supersedes any pending partial-update state.
885        self.vertex_partial_keys.remove(&vid);
886        self.vertex_versions.insert(vid, version);
887        self.graph.remove_vertex(vid);
888        self.mutation_count += 1;
889        self.mutation_stats.nodes_deleted += 1;
890
891        // Remove constraint index entries for this vertex
892        self.constraint_index.retain(|_, v| *v != vid);
893        // Same for the implicit MERGE guard, so a later re-MERGE of a deleted
894        // node's key does not false-conflict with the stale entry.
895        self.merge_guard_index.retain(|_, v| *v != vid);
896
897        // 64 bytes per edge tombstone + 8 for vertex tombstone
898        self.estimated_size += cascaded_edges_count * 72 + 8;
899    }
900
901    pub fn insert_edge(
902        &mut self,
903        src_vid: Vid,
904        dst_vid: Vid,
905        edge_type: u32,
906        eid: Eid,
907        properties: Properties,
908        edge_type_name: Option<String>,
909    ) -> Result<()> {
910        self.insert_edge_impl(
911            src_vid,
912            dst_vid,
913            edge_type,
914            eid,
915            properties,
916            edge_type_name,
917            false,
918        )
919    }
920
921    /// Core edge insertion. When `skip_wal` is true, skips WAL append
922    /// (used during merge where the caller already wrote to WAL).
923    #[allow(clippy::too_many_arguments)]
924    fn insert_edge_impl(
925        &mut self,
926        src_vid: Vid,
927        dst_vid: Vid,
928        edge_type: u32,
929        eid: Eid,
930        properties: Properties,
931        edge_type_name: Option<String>,
932        skip_wal: bool,
933    ) -> Result<()> {
934        self.current_version += 1;
935        let now = now_nanos();
936
937        if !skip_wal && let Some(wal) = &mut self.wal {
938            wal.append(Mutation::InsertEdge {
939                src_vid,
940                dst_vid,
941                edge_type,
942                eid,
943                version: self.current_version,
944                properties: properties.clone(),
945                edge_type_name: edge_type_name.clone(),
946            })?;
947        }
948
949        self.apply_edge_insertion(src_vid, dst_vid, edge_type, eid, properties)?;
950
951        // Store edge type name in metadata if provided
952        let type_name_size = if let Some(ref name) = edge_type_name {
953            let size = name.len() + 24;
954            self.edge_types.insert(eid, name.clone());
955            size
956        } else {
957            0
958        };
959
960        // Set timestamps - created_at only set if this is a new edge
961        self.edge_created_at.entry(eid).or_insert(now);
962        self.edge_updated_at.insert(eid, now);
963
964        // A full-row insert supersedes any pending partial-update state
965        // for this EID (Round 12 §A).
966        self.edge_partial_keys.remove(&eid);
967
968        self.estimated_size += type_name_size;
969
970        Ok(())
971    }
972
973    /// Insert an edge's FULL property row plus a touched-keys hint so the
974    /// flush emits only those schema columns via Lance `MergeInsert` on
975    /// the per-edge-type delta tables. Edge analog of
976    /// `insert_vertex_partial_full` (Round 12 §A).
977    #[allow(clippy::too_many_arguments)]
978    pub fn insert_edge_partial_full(
979        &mut self,
980        src_vid: Vid,
981        dst_vid: Vid,
982        edge_type: u32,
983        eid: Eid,
984        properties: Properties,
985        edge_type_name: Option<String>,
986        touched_keys: HashSet<String>,
987    ) -> Result<()> {
988        self.current_version += 1;
989        let now = now_nanos();
990
991        if let Some(wal) = &mut self.wal {
992            wal.append(Mutation::InsertEdge {
993                src_vid,
994                dst_vid,
995                edge_type,
996                eid,
997                version: self.current_version,
998                properties: properties.clone(),
999                edge_type_name: edge_type_name.clone(),
1000            })?;
1001        }
1002
1003        self.apply_edge_insertion(src_vid, dst_vid, edge_type, eid, properties)?;
1004
1005        // `apply_edge_insertion` cleared the partial-keys entry as a
1006        // safety measure (full-row insert supersedes partial). Re-insert
1007        // with the touched-keys hint so the flush emits a partial source.
1008        self.edge_partial_keys
1009            .entry(eid)
1010            .or_default()
1011            .extend(touched_keys);
1012
1013        let type_name_size = if let Some(ref name) = edge_type_name {
1014            let size = name.len() + 24;
1015            self.edge_types.insert(eid, name.clone());
1016            size
1017        } else {
1018            0
1019        };
1020
1021        self.edge_created_at.entry(eid).or_insert(now);
1022        self.edge_updated_at.insert(eid, now);
1023
1024        self.estimated_size += type_name_size;
1025
1026        Ok(())
1027    }
1028
1029    /// Core edge insertion logic: add vertices, add edge, merge properties, update metadata.
1030    ///
1031    /// Shared between `insert_edge` (live mutations) and `replay_mutations` (WAL recovery).
1032    ///
1033    /// # Errors
1034    ///
1035    /// Returns error if either endpoint vertex has been deleted (exists in vertex_tombstones).
1036    /// This prevents "ghost vertex" resurrection via edge insertion. See issue #77.
1037    fn apply_edge_insertion(
1038        &mut self,
1039        src_vid: Vid,
1040        dst_vid: Vid,
1041        edge_type: u32,
1042        eid: Eid,
1043        properties: Properties,
1044    ) -> Result<()> {
1045        let version = self.current_version;
1046
1047        // Check if either endpoint has been deleted. Inserting an edge to a deleted
1048        // vertex would resurrect it as a "ghost vertex" with no properties. See issue #77.
1049        if self.vertex_tombstones.contains(&src_vid) {
1050            anyhow::bail!(
1051                "Cannot insert edge: source vertex {} has been deleted (issue #77)",
1052                src_vid
1053            );
1054        }
1055        if self.vertex_tombstones.contains(&dst_vid) {
1056            anyhow::bail!(
1057                "Cannot insert edge: destination vertex {} has been deleted (issue #77)",
1058                dst_vid
1059            );
1060        }
1061
1062        // Add vertices to graph topology if they don't exist.
1063        // IMPORTANT: Only add to graph structure, do NOT call insert_vertex.
1064        // insert_vertex creates a new version with empty properties, which would
1065        // cause MVCC to pick the empty version as "latest", losing original properties.
1066        if !self.graph.contains_vertex(src_vid) {
1067            self.graph.add_vertex(src_vid);
1068        }
1069        if !self.graph.contains_vertex(dst_vid) {
1070            self.graph.add_vertex(dst_vid);
1071        }
1072
1073        self.graph.add_edge(src_vid, dst_vid, eid, edge_type);
1074
1075        // Store metadata with CRDT merge logic
1076        let props_size = Self::estimate_properties_size(&properties);
1077        let props_count = properties.len();
1078        if !properties.is_empty() {
1079            let entry = self.edge_properties.entry(eid).or_default();
1080            Self::merge_crdt_properties(entry, properties, self.plugin_registry.as_ref());
1081        }
1082
1083        self.edge_versions.insert(eid, version);
1084        self.edge_endpoints
1085            .insert(eid, (src_vid, dst_vid, edge_type));
1086        self.tombstones.remove(&eid);
1087        self.mutation_count += 1;
1088        self.mutation_stats.relationships_created += 1;
1089        self.mutation_stats.properties_set += props_count;
1090
1091        // 24 edge + props + 16 version + 28 endpoints + 32 timestamps
1092        self.estimated_size += 24 + props_size + 16 + 28 + 32;
1093
1094        Ok(())
1095    }
1096
1097    pub fn delete_edge(
1098        &mut self,
1099        eid: Eid,
1100        src_vid: Vid,
1101        dst_vid: Vid,
1102        edge_type: u32,
1103    ) -> Result<()> {
1104        self.delete_edge_impl(eid, src_vid, dst_vid, edge_type, false)
1105    }
1106
1107    /// Core edge deletion. When `skip_wal` is true, skips WAL append
1108    /// (used during merge where the caller already wrote to WAL).
1109    fn delete_edge_impl(
1110        &mut self,
1111        eid: Eid,
1112        src_vid: Vid,
1113        dst_vid: Vid,
1114        edge_type: u32,
1115        skip_wal: bool,
1116    ) -> Result<()> {
1117        self.current_version += 1;
1118        let now = now_nanos();
1119
1120        if !skip_wal && let Some(wal) = &mut self.wal {
1121            wal.append(Mutation::DeleteEdge {
1122                eid,
1123                src_vid,
1124                dst_vid,
1125                edge_type,
1126                version: self.current_version,
1127            })?;
1128        }
1129
1130        self.apply_edge_deletion(eid, src_vid, dst_vid, edge_type);
1131
1132        // Update timestamp - deletion is an update
1133        self.edge_updated_at.insert(eid, now);
1134
1135        Ok(())
1136    }
1137
1138    /// Core edge deletion logic: tombstone the edge, update version, remove from graph.
1139    ///
1140    /// Shared between `delete_edge` (live mutations) and `replay_mutations` (WAL recovery).
1141    fn apply_edge_deletion(&mut self, eid: Eid, src_vid: Vid, dst_vid: Vid, edge_type: u32) {
1142        let version = self.current_version;
1143
1144        self.tombstones.insert(
1145            eid,
1146            TombstoneEntry {
1147                eid,
1148                src_vid,
1149                dst_vid,
1150                edge_type,
1151            },
1152        );
1153        self.edge_versions.insert(eid, version);
1154        // Deletion supersedes any pending partial-update state for this
1155        // EID (Round 12 §A).
1156        self.edge_partial_keys.remove(&eid);
1157        // Drop any unique-constraint keys this edge owned so a later edge may
1158        // reuse the value (mirrors `apply_vertex_deletion`).
1159        self.edge_constraint_index.retain(|_, e| *e != eid);
1160        self.graph.remove_edge(eid);
1161        self.mutation_count += 1;
1162        self.mutation_stats.relationships_deleted += 1;
1163
1164        // 64 bytes tombstone + 16 bytes version
1165        self.estimated_size += 80;
1166    }
1167
1168    /// Returns neighbors in the specified direction.
1169    /// O(degree) complexity - iterates only edges connected to the vertex.
1170    pub fn get_neighbors(
1171        &self,
1172        vid: Vid,
1173        edge_type: u32,
1174        direction: Direction,
1175    ) -> Vec<(Vid, Eid, u64)> {
1176        let edges = self.graph.neighbors(vid, direction);
1177
1178        edges
1179            .iter()
1180            .filter(|e| e.edge_type == edge_type && !self.is_tombstoned(e.eid))
1181            .map(|e| {
1182                let neighbor = match direction {
1183                    Direction::Outgoing => e.dst_vid,
1184                    Direction::Incoming => e.src_vid,
1185                };
1186                let version = self.edge_versions.get(&e.eid).copied().unwrap_or(0);
1187                (neighbor, e.eid, version)
1188            })
1189            .collect()
1190    }
1191
1192    pub fn is_tombstoned(&self, eid: Eid) -> bool {
1193        self.tombstones.contains_key(&eid)
1194    }
1195
1196    /// Returns all VIDs in vertex_labels that match the given label name.
1197    /// O(1) lookup via the reverse label index.
1198    pub fn vids_for_label(&self, label_name: &str) -> Vec<Vid> {
1199        self.label_to_vids
1200            .get(label_name)
1201            .map(|set| set.iter().copied().collect())
1202            .unwrap_or_default()
1203    }
1204
1205    /// Returns all vertex VIDs in the L0 buffer.
1206    ///
1207    /// Used for schemaless scanning (MATCH (n) without label).
1208    pub fn all_vertex_vids(&self) -> Vec<Vid> {
1209        self.vertex_properties.keys().copied().collect()
1210    }
1211
1212    /// Returns all VIDs in vertex_labels that match any of the given label names.
1213    /// Uses the reverse label index — O(sum of matching set sizes).
1214    pub fn vids_for_labels(&self, label_names: &[&str]) -> Vec<Vid> {
1215        let mut result = HashSet::new();
1216        for label_name in label_names {
1217            if let Some(set) = self.label_to_vids.get(*label_name) {
1218                result.extend(set.iter().copied());
1219            }
1220        }
1221        result.into_iter().collect()
1222    }
1223
1224    /// Returns all VIDs that have ALL specified labels.
1225    /// Uses the reverse label index — intersects the per-label sets.
1226    pub fn vids_with_all_labels(&self, label_names: &[&str]) -> Vec<Vid> {
1227        if label_names.is_empty() {
1228            return Vec::new();
1229        }
1230        // Collect the per-label sets; if any label is missing from the index,
1231        // the intersection is empty.
1232        let sets: Vec<&HashSet<Vid>> = match label_names
1233            .iter()
1234            .map(|ln| self.label_to_vids.get(*ln))
1235            .collect::<Option<Vec<_>>>()
1236        {
1237            Some(s) => s,
1238            None => return Vec::new(),
1239        };
1240        // Start from the smallest set for efficiency.
1241        let smallest = sets.iter().min_by_key(|s| s.len()).unwrap();
1242        smallest
1243            .iter()
1244            .copied()
1245            .filter(|vid| sets.iter().all(|s| s.contains(vid)))
1246            .collect()
1247    }
1248
1249    /// Gets the labels for a VID.
1250    pub fn get_vertex_labels(&self, vid: Vid) -> Option<&[String]> {
1251        self.vertex_labels.get(&vid).map(|v| v.as_slice())
1252    }
1253
1254    /// Gets the edge type for an EID.
1255    pub fn get_edge_type(&self, eid: Eid) -> Option<&str> {
1256        self.edge_types.get(&eid).map(|s| s.as_str())
1257    }
1258
1259    /// Returns all EIDs in edge_types that match the given type name.
1260    /// Used for L0 overlay during schemaless edge scanning.
1261    pub fn eids_for_type(&self, type_name: &str) -> Vec<Eid> {
1262        self.edge_types
1263            .iter()
1264            .filter(|(eid, etype)| *etype == type_name && !self.tombstones.contains_key(eid))
1265            .map(|(eid, _)| *eid)
1266            .collect()
1267    }
1268
1269    /// Returns all edge EIDs in the L0 buffer (non-tombstoned).
1270    ///
1271    /// Used for schemaless scanning (`MATCH ()-[r]->()`) without type.
1272    pub fn all_edge_eids(&self) -> Vec<Eid> {
1273        self.edge_endpoints
1274            .keys()
1275            .filter(|eid| !self.tombstones.contains_key(eid))
1276            .copied()
1277            .collect()
1278    }
1279
1280    /// Returns edge endpoint data (src_vid, dst_vid) for an EID.
1281    pub fn get_edge_endpoints(&self, eid: Eid) -> Option<(Vid, Vid)> {
1282        self.edge_endpoints
1283            .get(&eid)
1284            .map(|(src, dst, _)| (*src, *dst))
1285    }
1286
1287    /// Returns full edge endpoint data (src_vid, dst_vid, edge_type_id) for an EID.
1288    pub fn get_edge_endpoint_full(&self, eid: Eid) -> Option<(Vid, Vid, u32)> {
1289        self.edge_endpoints.get(&eid).copied()
1290    }
1291
1292    /// Insert a constraint key into the index for O(1) duplicate detection.
1293    pub fn insert_constraint_key(&mut self, key: Vec<u8>, vid: Vid) {
1294        self.constraint_index.insert(key, vid);
1295    }
1296
1297    /// Check if a constraint key exists in the index, excluding a specific VID.
1298    /// Returns true if the key exists and is owned by a different vertex.
1299    pub fn has_constraint_key(&self, key: &[u8], exclude_vid: Vid) -> bool {
1300        self.constraint_index
1301            .get(key)
1302            .is_some_and(|&v| v != exclude_vid)
1303    }
1304
1305    /// Insert an edge unique-constraint key into the index (edge analogue of
1306    /// [`insert_constraint_key`](Self::insert_constraint_key)).
1307    pub fn insert_edge_constraint_key(&mut self, key: Vec<u8>, eid: Eid) {
1308        self.edge_constraint_index.insert(key, eid);
1309    }
1310
1311    /// Check if an edge unique-constraint key exists, owned by an edge other than
1312    /// `exclude_eid`. Edge analogue of
1313    /// [`has_constraint_key`](Self::has_constraint_key).
1314    pub fn has_edge_constraint_key(&self, key: &[u8], exclude_eid: Eid) -> bool {
1315        self.edge_constraint_index
1316            .get(key)
1317            .is_some_and(|&e| e != exclude_eid)
1318    }
1319
1320    /// Register a MERGE-create's key into the implicit phantom guard.
1321    pub fn insert_merge_guard_key(&mut self, key: Vec<u8>, vid: Vid) {
1322        self.merge_guard_index.insert(key, vid);
1323    }
1324
1325    /// Check if a MERGE-guard key exists, owned by a different vertex than
1326    /// `exclude_vid` — i.e. a concurrent MERGE already created this key.
1327    pub fn has_merge_guard_key(&self, key: &[u8], exclude_vid: Vid) -> bool {
1328        self.merge_guard_index
1329            .get(key)
1330            .is_some_and(|&v| v != exclude_vid)
1331    }
1332
1333    #[instrument(skip(self, other), level = "trace")]
1334    /// Validate that merging `other` into `self` will not bail on a tombstoned
1335    /// edge endpoint (issue #77), **without mutating** either buffer.
1336    ///
1337    /// Mirrors the endpoint-liveness guard in `apply_edge_insertion`
1338    /// against the tombstone state [`Self::merge`] produces: `other`'s vertex
1339    /// deletions are applied and its vertex inserts clear their own tombstone,
1340    /// so an inserted edge bails iff an endpoint is tombstoned in `self` or
1341    /// `other` and is not (re-)inserted by `other`.
1342    ///
1343    /// Run this under `flush_lock` *before* the durable WAL flush so an
1344    /// offending commit is rejected up front. After the flush the transaction
1345    /// is durable, and a `merge` bail would leave a ghost/partial commit whose
1346    /// WAL replay re-bails — rendering the database unopenable.
1347    ///
1348    /// # Errors
1349    ///
1350    /// Returns an error naming the offending edge and endpoint when the merge
1351    /// would bail.
1352    pub fn validate_merge_edge_endpoints(&self, other: &L0Buffer) -> Result<()> {
1353        // An endpoint is effectively deleted after the merge's vertex phase if
1354        // it is tombstoned in either buffer and `other` does not re-insert it
1355        // (an insert clears the tombstone).
1356        let is_deleted = |vid: &Vid| {
1357            (self.vertex_tombstones.contains(vid) || other.vertex_tombstones.contains(vid))
1358                && !other.vertex_properties.contains_key(vid)
1359        };
1360        for (eid, (src_vid, dst_vid, _etype)) in &other.edge_endpoints {
1361            if other.tombstones.contains_key(eid) {
1362                continue; // a deletion, not an insertion — never resurrects a vertex
1363            }
1364            if is_deleted(src_vid) {
1365                anyhow::bail!(
1366                    "Cannot insert edge {}: source vertex {} has been deleted (issue #77)",
1367                    eid,
1368                    src_vid
1369                );
1370            }
1371            if is_deleted(dst_vid) {
1372                anyhow::bail!(
1373                    "Cannot insert edge {}: destination vertex {} has been deleted (issue #77)",
1374                    eid,
1375                    dst_vid
1376                );
1377            }
1378        }
1379        Ok(())
1380    }
1381
1382    pub fn merge(&mut self, other: &L0Buffer) -> Result<()> {
1383        // Validate-then-apply: reject a merge that would bail on a tombstoned
1384        // edge endpoint before mutating anything, so a failed merge can never
1385        // leave a partially-applied (non-atomic) commit.
1386        self.validate_merge_edge_endpoints(other)?;
1387        self.merge_validated(
1388            other,
1389            other.vertex_properties.clone(),
1390            other.edge_properties.clone(),
1391        )
1392    }
1393
1394    /// Commit-path variant of [`merge`](Self::merge) that consumes `other`'s
1395    /// vertex/edge property maps instead of deep-cloning every row.
1396    ///
1397    /// Everything else in `other` (endpoints, tombstones, versions, labels)
1398    /// is left intact — `commit_transaction_l0` still reads those after the
1399    /// merge. The caller must not rely on `other.vertex_properties` /
1400    /// `other.edge_properties` afterwards, which is safe on the commit path
1401    /// because committing consumes the transaction.
1402    pub fn merge_take(&mut self, other: &mut L0Buffer) -> Result<()> {
1403        // Validate BEFORE draining: the endpoint check consults
1404        // `other.vertex_properties` (the "re-inserted by other" exemption).
1405        self.validate_merge_edge_endpoints(other)?;
1406        let vertex_props = std::mem::take(&mut other.vertex_properties);
1407        let edge_props = std::mem::take(&mut other.edge_properties);
1408        self.merge_validated(other, vertex_props, edge_props)
1409    }
1410
1411    /// Shared merge body. `vertex_props` / `edge_props` are `other`'s property
1412    /// maps, passed by value so rows move instead of clone; the caller has
1413    /// already run `validate_merge_edge_endpoints`.
1414    fn merge_validated(
1415        &mut self,
1416        other: &L0Buffer,
1417        vertex_props: HashMap<Vid, Properties>,
1418        mut edge_props: HashMap<Eid, Properties>,
1419    ) -> Result<()> {
1420        trace!(
1421            other_mutation_count = other.mutation_count,
1422            "Merging L0 buffer"
1423        );
1424        // skip_wal=true throughout: the caller (commit_transaction_l0) already
1425        // wrote every one of these mutations to WAL before invoking merge —
1426        // re-appending here would double the WAL volume per commit.
1427        // Merge Vertices
1428        for &vid in &other.vertex_tombstones {
1429            self.delete_vertex_impl(vid, true)?;
1430        }
1431
1432        for (vid, props) in vertex_props {
1433            let labels = other.vertex_labels.get(&vid).cloned().unwrap_or_default();
1434            self.insert_vertex_with_labels_impl(vid, props, &labels, true);
1435        }
1436
1437        // Merge vertex labels that might not have properties
1438        for (vid, labels) in &other.vertex_labels {
1439            if !self.vertex_labels.contains_key(vid) {
1440                self.vertex_labels.insert(*vid, labels.clone());
1441                for label in labels {
1442                    self.label_to_vids
1443                        .entry(label.clone())
1444                        .or_default()
1445                        .insert(*vid);
1446                }
1447            }
1448        }
1449
1450        // Label-overwrite pass: a `SET n:Label` / `REMOVE n:Label` resolved the
1451        // FULL new label set into `other.vertex_labels[vid]` and flagged the vid.
1452        // REPLACE (not append) so removals actually remove and an existing
1453        // vertex's label change lands — overriding any append from the property
1454        // loop above. Skip vids deleted in the same commit. (The append loops
1455        // stay correct for property-path label unions, which are NOT flagged.)
1456        for vid in &other.vertex_label_overwrites {
1457            if other.vertex_tombstones.contains(vid) {
1458                continue;
1459            }
1460            let labels = other.vertex_labels.get(vid).cloned().unwrap_or_default();
1461            self.remove_vid_from_label_index(*vid);
1462            self.vertex_labels.insert(*vid, labels.clone());
1463            self.index_labels_for_vid(*vid, &labels);
1464            // Carry the overwrite flag into the persistent (main) buffer so a
1465            // pure relabel of a prior-window vid — which is absent from
1466            // `vertex_properties` — is still re-derived at flush (M8). The
1467            // flag is cleared when this buffer is rotated out by the flush.
1468            self.vertex_label_overwrites.insert(*vid);
1469        }
1470
1471        // Merge Edges - insert all edges from edge_endpoints, using empty props if none exist
1472        for (eid, (src, dst, etype)) in &other.edge_endpoints {
1473            if other.tombstones.contains_key(eid) {
1474                self.delete_edge_impl(*eid, *src, *dst, *etype, true)?;
1475            } else {
1476                let props = edge_props.remove(eid).unwrap_or_default();
1477                let etype_name = other.edge_types.get(eid).cloned();
1478                self.insert_edge_impl(*src, *dst, *etype, *eid, props, etype_name, true)?;
1479            }
1480        }
1481
1482        // Merge tombstones for edges that only exist in the target buffer (self),
1483        // not in the source buffer's edge_endpoints.  Without this, transaction
1484        // DELETEs of pre-existing edges are silently lost on commit.
1485        for (eid, tombstone) in &other.tombstones {
1486            if !other.edge_endpoints.contains_key(eid) {
1487                self.delete_edge_impl(
1488                    *eid,
1489                    tombstone.src_vid,
1490                    tombstone.dst_vid,
1491                    tombstone.edge_type,
1492                    true,
1493                )?;
1494            }
1495        }
1496
1497        // Edge types are now merged inside insert_edge, so no separate loop needed
1498
1499        // Merge timestamps - preserve semantics of or_insert (keep oldest created_at)
1500        // and insert (use latest updated_at)
1501        for (vid, ts) in &other.vertex_created_at {
1502            self.vertex_created_at.entry(*vid).or_insert(*ts); // keep oldest
1503        }
1504        for (vid, ts) in &other.vertex_updated_at {
1505            self.vertex_updated_at.insert(*vid, *ts); // use latest (tx wins)
1506        }
1507
1508        for (eid, ts) in &other.edge_created_at {
1509            self.edge_created_at.entry(*eid).or_insert(*ts); // keep oldest
1510        }
1511        for (eid, ts) in &other.edge_updated_at {
1512            self.edge_updated_at.insert(*eid, *ts); // use latest (tx wins)
1513        }
1514
1515        // Conservatively add other's estimated size (may overcount due to
1516        // deduplication, but that's safe for a memory limit).
1517        self.estimated_size += other.estimated_size;
1518
1519        // Merge constraint index
1520        for (key, vid) in &other.constraint_index {
1521            self.constraint_index.insert(key.clone(), *vid);
1522        }
1523
1524        // Merge the implicit MERGE-key guard so a committed MERGE-create is
1525        // visible to a concurrent transaction's commit-time re-probe.
1526        for (key, vid) in &other.merge_guard_index {
1527            self.merge_guard_index.insert(key.clone(), *vid);
1528        }
1529
1530        // Merge the edge unique-constraint index (parallel to `constraint_index`).
1531        for (key, eid) in &other.edge_constraint_index {
1532            self.edge_constraint_index.insert(key.clone(), *eid);
1533        }
1534
1535        // Carry deferred-embedding markers from the tx L0 into the main L0 so the
1536        // flush-time `drain_pending_embeddings` sees them (the marked vids' properties were
1537        // just merged above). Without this, `defer_embeddings` auto-embed silently no-ops for
1538        // any transactional write — a pre-existing gap that also affects single-vector
1539        // deferral, surfaced while wiring multi-vector auto-embed (issue #104).
1540        for (vid, label) in &other.pending_embeddings {
1541            self.pending_embeddings.insert(*vid, label.clone());
1542        }
1543
1544        Ok(())
1545    }
1546
1547    /// Replay mutations from WAL without re-logging them.
1548    /// Used during startup recovery to restore L0 state from persisted WAL.
1549    /// Uses CRDT merge semantics to ensure recovered state matches pre-crash state.
1550    #[instrument(skip(self, mutations), level = "debug")]
1551    pub fn replay_mutations(&mut self, mutations: Vec<Mutation>) -> Result<()> {
1552        trace!(count = mutations.len(), "Replaying mutations");
1553        for mutation in mutations {
1554            match mutation {
1555                Mutation::InsertVertex {
1556                    vid,
1557                    properties,
1558                    labels,
1559                } => {
1560                    // Apply without WAL logging, with CRDT merge semantics
1561                    self.current_version += 1;
1562                    let version = self.current_version;
1563
1564                    self.vertex_tombstones.remove(&vid);
1565                    let tracks_extid = properties.contains_key("ext_id");
1566                    let entry = self.vertex_properties.entry(vid).or_default();
1567                    let old_extid = if tracks_extid {
1568                        Self::extid_of(entry)
1569                    } else {
1570                        None
1571                    };
1572                    Self::merge_crdt_properties(entry, properties, self.plugin_registry.as_ref());
1573                    if tracks_extid {
1574                        let new_extid = Self::extid_of(
1575                            self.vertex_properties.get(&vid).expect("just inserted"),
1576                        );
1577                        self.sync_extid_index(vid, old_extid, new_extid);
1578                    }
1579                    self.vertex_versions.insert(vid, version);
1580                    self.graph.add_vertex(vid);
1581                    self.mutation_count += 1;
1582
1583                    // Restore vertex labels from WAL
1584                    let existing = self.vertex_labels.entry(vid).or_default();
1585                    Self::append_unique_labels(existing, &labels);
1586                    for label in &labels {
1587                        self.label_to_vids
1588                            .entry(label.clone())
1589                            .or_default()
1590                            .insert(vid);
1591                    }
1592                }
1593                Mutation::DeleteVertex { vid, labels } => {
1594                    self.current_version += 1;
1595                    // Restore labels BEFORE apply_vertex_deletion
1596                    if !labels.is_empty() {
1597                        let existing = self.vertex_labels.entry(vid).or_default();
1598                        Self::append_unique_labels(existing, &labels);
1599                        for label in &labels {
1600                            self.label_to_vids
1601                                .entry(label.clone())
1602                                .or_default()
1603                                .insert(vid);
1604                        }
1605                    }
1606                    self.apply_vertex_deletion(vid);
1607                }
1608                Mutation::SetVertexLabels { vid, labels } => {
1609                    // REPLACE the vid's full label set (a label-only mutation
1610                    // resolved the complete set). Replace, not append, so a
1611                    // replayed removal removes; clears the old reverse-index
1612                    // entries first.
1613                    self.current_version += 1;
1614                    self.remove_vid_from_label_index(vid);
1615                    self.vertex_labels.insert(vid, labels.clone());
1616                    self.index_labels_for_vid(vid, &labels);
1617                    // Mark this vid as a label overwrite, exactly like the live
1618                    // `set_vertex_labels` path. Without this marker the M8
1619                    // flush/merge overwrite pass skips the vid (a label-only
1620                    // mutation leaves no `vertex_properties` entry), so a
1621                    // WAL-durable SET/REMOVE label on a prior-window vertex
1622                    // would be silently lost at the first post-recovery flush.
1623                    self.vertex_label_overwrites.insert(vid);
1624                    self.mutation_count += 1;
1625                }
1626                Mutation::InsertEdge {
1627                    src_vid,
1628                    dst_vid,
1629                    edge_type,
1630                    eid,
1631                    version: _,
1632                    properties,
1633                    edge_type_name,
1634                } => {
1635                    self.current_version += 1;
1636                    // Skip-and-warn on the issue-#77 endpoint bail: a pre-fix
1637                    // durable WAL may hold a ghost edge whose endpoint was
1638                    // tombstoned. Recovery must still open the database rather
1639                    // than abort, so drop the offending edge and continue.
1640                    match self.apply_edge_insertion(src_vid, dst_vid, edge_type, eid, properties) {
1641                        Ok(()) => {
1642                            // Restore edge type name metadata if present
1643                            if let Some(name) = edge_type_name {
1644                                self.edge_types.insert(eid, name);
1645                            }
1646                        }
1647                        Err(e) => {
1648                            tracing::warn!(
1649                                ?eid,
1650                                ?src_vid,
1651                                ?dst_vid,
1652                                error = %e,
1653                                "WAL replay: skipping edge insertion to a deleted endpoint (issue #77)"
1654                            );
1655                        }
1656                    }
1657                }
1658                Mutation::DeleteEdge {
1659                    eid,
1660                    src_vid,
1661                    dst_vid,
1662                    edge_type,
1663                    version: _,
1664                } => {
1665                    self.current_version += 1;
1666                    self.apply_edge_deletion(eid, src_vid, dst_vid, edge_type);
1667                }
1668            }
1669        }
1670        Ok(())
1671    }
1672}
1673
1674#[cfg(test)]
1675mod tests {
1676    use super::*;
1677
1678    #[test]
1679    fn test_l0_buffer_ops() -> Result<()> {
1680        let mut l0 = L0Buffer::new(0, None);
1681        let vid_a = Vid::new(1);
1682        let vid_b = Vid::new(2);
1683        let eid_ab = Eid::new(101);
1684
1685        l0.insert_edge(vid_a, vid_b, 1, eid_ab, HashMap::new(), None)?;
1686
1687        let neighbors = l0.get_neighbors(vid_a, 1, Direction::Outgoing);
1688        assert_eq!(neighbors.len(), 1);
1689        assert_eq!(neighbors[0].0, vid_b);
1690        assert_eq!(neighbors[0].1, eid_ab);
1691
1692        l0.delete_edge(eid_ab, vid_a, vid_b, 1)?;
1693        assert!(l0.is_tombstoned(eid_ab));
1694
1695        // Verify neighbors are empty after deletion
1696        let neighbors_after = l0.get_neighbors(vid_a, 1, Direction::Outgoing);
1697        assert_eq!(neighbors_after.len(), 0);
1698
1699        Ok(())
1700    }
1701
1702    /// Regression for review #5: merging an edge whose endpoint is tombstoned
1703    /// in the target buffer must be rejected up front (`validate_merge_edge_endpoints`)
1704    /// and `merge` must be atomic — never partially applied. Before the fix this
1705    /// bailed only *inside* `merge`, after the durable WAL flush, leaving a ghost
1706    /// commit that made the database unopenable on replay.
1707    #[test]
1708    fn validate_merge_rejects_edge_to_tombstoned_endpoint() {
1709        let mut main = L0Buffer::new(0, None);
1710        let vid_a = Vid::new(1);
1711        let vid_b = Vid::new(2);
1712        main.insert_vertex(vid_a, HashMap::new());
1713        main.insert_vertex(vid_b, HashMap::new());
1714        main.delete_vertex(vid_b).unwrap(); // B is now tombstoned in main
1715
1716        // A transaction that inserts an edge A -> B (B tombstoned in main).
1717        let mut tx = L0Buffer::new(0, None);
1718        let eid = Eid::new(101);
1719        tx.insert_edge(vid_a, vid_b, 1, eid, HashMap::new(), None)
1720            .unwrap();
1721
1722        assert!(
1723            main.validate_merge_edge_endpoints(&tx).is_err(),
1724            "edge to a tombstoned endpoint must be rejected before merge"
1725        );
1726        // merge validates first, so it errors and leaves main untouched (atomic).
1727        assert!(
1728            main.merge(&tx).is_err(),
1729            "merge must reject, not bail mid-apply"
1730        );
1731        assert!(
1732            !main.edge_endpoints.contains_key(&eid),
1733            "a rejected merge must not have partially applied the edge"
1734        );
1735    }
1736
1737    /// When the transaction re-inserts the endpoint vertex, the edge is valid
1738    /// (the insert clears the tombstone) and the merge succeeds.
1739    #[test]
1740    fn validate_merge_allows_edge_when_endpoint_reinserted() {
1741        let mut main = L0Buffer::new(0, None);
1742        let vid_a = Vid::new(1);
1743        let vid_b = Vid::new(2);
1744        main.insert_vertex(vid_a, HashMap::new());
1745        main.insert_vertex(vid_b, HashMap::new());
1746        main.delete_vertex(vid_b).unwrap();
1747
1748        let mut tx = L0Buffer::new(0, None);
1749        tx.insert_vertex(vid_b, HashMap::new()); // re-insert B
1750        let eid = Eid::new(101);
1751        tx.insert_edge(vid_a, vid_b, 1, eid, HashMap::new(), None)
1752            .unwrap();
1753
1754        assert!(main.validate_merge_edge_endpoints(&tx).is_ok());
1755        assert!(main.merge(&tx).is_ok());
1756        assert!(main.edge_endpoints.contains_key(&eid));
1757    }
1758
1759    /// Edges between live endpoints merge as before — no false positives.
1760    #[test]
1761    fn validate_merge_allows_edge_to_live_endpoints() {
1762        let mut main = L0Buffer::new(0, None);
1763        let vid_a = Vid::new(1);
1764        let vid_b = Vid::new(2);
1765        main.insert_vertex(vid_a, HashMap::new());
1766        main.insert_vertex(vid_b, HashMap::new());
1767
1768        let mut tx = L0Buffer::new(0, None);
1769        let eid = Eid::new(101);
1770        tx.insert_edge(vid_a, vid_b, 1, eid, HashMap::new(), None)
1771            .unwrap();
1772
1773        assert!(main.validate_merge_edge_endpoints(&tx).is_ok());
1774        assert!(main.merge(&tx).is_ok());
1775        assert!(main.edge_endpoints.contains_key(&eid));
1776    }
1777
1778    #[test]
1779    fn test_l0_buffer_multiple_edges() -> Result<()> {
1780        let mut l0 = L0Buffer::new(0, None);
1781        let vid_a = Vid::new(1);
1782        let vid_b = Vid::new(2);
1783        let vid_c = Vid::new(3);
1784        let eid_ab = Eid::new(101);
1785        let eid_ac = Eid::new(102);
1786
1787        l0.insert_edge(vid_a, vid_b, 1, eid_ab, HashMap::new(), None)?;
1788        l0.insert_edge(vid_a, vid_c, 1, eid_ac, HashMap::new(), None)?;
1789
1790        let neighbors = l0.get_neighbors(vid_a, 1, Direction::Outgoing);
1791        assert_eq!(neighbors.len(), 2);
1792
1793        // Delete one edge
1794        l0.delete_edge(eid_ab, vid_a, vid_b, 1)?;
1795
1796        // Should still have one neighbor
1797        let neighbors_after = l0.get_neighbors(vid_a, 1, Direction::Outgoing);
1798        assert_eq!(neighbors_after.len(), 1);
1799        assert_eq!(neighbors_after[0].0, vid_c);
1800
1801        Ok(())
1802    }
1803
1804    #[test]
1805    fn test_l0_buffer_edge_type_filter() -> Result<()> {
1806        let mut l0 = L0Buffer::new(0, None);
1807        let vid_a = Vid::new(1);
1808        let vid_b = Vid::new(2);
1809        let vid_c = Vid::new(3);
1810        let eid_ab = Eid::new(101);
1811        let eid_ac = Eid::new(201); // Different edge type
1812
1813        l0.insert_edge(vid_a, vid_b, 1, eid_ab, HashMap::new(), None)?;
1814        l0.insert_edge(vid_a, vid_c, 2, eid_ac, HashMap::new(), None)?;
1815
1816        // Filter by edge type 1
1817        let type1_neighbors = l0.get_neighbors(vid_a, 1, Direction::Outgoing);
1818        assert_eq!(type1_neighbors.len(), 1);
1819        assert_eq!(type1_neighbors[0].0, vid_b);
1820
1821        // Filter by edge type 2
1822        let type2_neighbors = l0.get_neighbors(vid_a, 2, Direction::Outgoing);
1823        assert_eq!(type2_neighbors.len(), 1);
1824        assert_eq!(type2_neighbors[0].0, vid_c);
1825
1826        Ok(())
1827    }
1828
1829    #[test]
1830    fn test_l0_buffer_incoming_edges() -> Result<()> {
1831        let mut l0 = L0Buffer::new(0, None);
1832        let vid_a = Vid::new(1);
1833        let vid_b = Vid::new(2);
1834        let vid_c = Vid::new(3);
1835        let eid_ab = Eid::new(101);
1836        let eid_cb = Eid::new(102);
1837
1838        // a -> b and c -> b
1839        l0.insert_edge(vid_a, vid_b, 1, eid_ab, HashMap::new(), None)?;
1840        l0.insert_edge(vid_c, vid_b, 1, eid_cb, HashMap::new(), None)?;
1841
1842        // Check incoming edges to b
1843        let incoming = l0.get_neighbors(vid_b, 1, Direction::Incoming);
1844        assert_eq!(incoming.len(), 2);
1845
1846        Ok(())
1847    }
1848
1849    /// Regression test: merge should preserve edges without properties
1850    #[test]
1851    fn test_merge_empty_props_edge() -> Result<()> {
1852        let mut main_l0 = L0Buffer::new(0, None);
1853        let mut tx_l0 = L0Buffer::new(0, None);
1854
1855        let vid_a = Vid::new(1);
1856        let vid_b = Vid::new(2);
1857        let eid_ab = Eid::new(101);
1858
1859        // Insert edge with empty properties in transaction L0
1860        tx_l0.insert_edge(vid_a, vid_b, 1, eid_ab, HashMap::new(), None)?;
1861
1862        // Verify edge exists in tx_l0
1863        assert!(tx_l0.edge_endpoints.contains_key(&eid_ab));
1864        assert!(!tx_l0.edge_properties.contains_key(&eid_ab)); // No properties entry
1865
1866        // Merge into main L0
1867        main_l0.merge(&tx_l0)?;
1868
1869        // Edge should exist in main L0 after merge
1870        assert!(main_l0.edge_endpoints.contains_key(&eid_ab));
1871        let neighbors = main_l0.get_neighbors(vid_a, 1, Direction::Outgoing);
1872        assert_eq!(neighbors.len(), 1);
1873        assert_eq!(neighbors[0].0, vid_b);
1874
1875        Ok(())
1876    }
1877
1878    /// Regression test: WAL replay should use CRDT merge semantics
1879    #[test]
1880    fn test_replay_crdt_merge() -> Result<()> {
1881        use crate::runtime::wal::Mutation;
1882        use serde_json::json;
1883        use uni_common::Value;
1884
1885        let mut l0 = L0Buffer::new(0, None);
1886        let vid = Vid::new(1);
1887
1888        // Create GCounter CRDT values using correct serde format:
1889        // {"t": "gc", "d": {"counts": {...}}}
1890        let counter1: Value = json!({
1891            "t": "gc",
1892            "d": {"counts": {"node1": 5}}
1893        })
1894        .into();
1895        let counter2: Value = json!({
1896            "t": "gc",
1897            "d": {"counts": {"node2": 3}}
1898        })
1899        .into();
1900
1901        // First mutation: insert vertex with counter1
1902        let mut props1 = HashMap::new();
1903        props1.insert("counter".to_string(), counter1.clone());
1904        l0.replay_mutations(vec![Mutation::InsertVertex {
1905            vid,
1906            properties: props1,
1907            labels: vec![],
1908        }])?;
1909
1910        // Second mutation: insert same vertex with counter2 (should merge)
1911        let mut props2 = HashMap::new();
1912        props2.insert("counter".to_string(), counter2.clone());
1913        l0.replay_mutations(vec![Mutation::InsertVertex {
1914            vid,
1915            properties: props2,
1916            labels: vec![],
1917        }])?;
1918
1919        // Verify CRDT was merged (both node1 and node2 counts present)
1920        let stored_props = l0.vertex_properties.get(&vid).unwrap();
1921        let stored_counter = stored_props.get("counter").unwrap();
1922
1923        // Convert back to serde_json::Value for nested access
1924        let stored_json: serde_json::Value = stored_counter.clone().into();
1925        // The merged counter should have both node1: 5 and node2: 3
1926        let data = stored_json.get("d").unwrap();
1927        let counts = data.get("counts").unwrap();
1928        assert_eq!(counts.get("node1"), Some(&json!(5)));
1929        assert_eq!(counts.get("node2"), Some(&json!(3)));
1930
1931        Ok(())
1932    }
1933
1934    #[test]
1935    fn test_merge_preserves_vertex_timestamps() -> Result<()> {
1936        let mut l0_main = L0Buffer::new(0, None);
1937        let mut l0_tx = L0Buffer::new(0, None);
1938        let vid = Vid::new(1);
1939
1940        // Main buffer: insert vertex with timestamp T1
1941        let ts_main_created = 1000;
1942        let ts_main_updated = 1100;
1943        l0_main.insert_vertex(vid, HashMap::new());
1944        l0_main.vertex_created_at.insert(vid, ts_main_created);
1945        l0_main.vertex_updated_at.insert(vid, ts_main_updated);
1946
1947        // Transaction buffer: update same vertex with timestamp T2 (later)
1948        let ts_tx_created = 2000; // should be ignored (main has older created_at)
1949        let ts_tx_updated = 2100; // should win (tx has newer updated_at)
1950        l0_tx.insert_vertex(vid, HashMap::new());
1951        l0_tx.vertex_created_at.insert(vid, ts_tx_created);
1952        l0_tx.vertex_updated_at.insert(vid, ts_tx_updated);
1953
1954        // Merge transaction into main
1955        l0_main.merge(&l0_tx)?;
1956
1957        // Verify created_at is oldest (from main)
1958        assert_eq!(
1959            *l0_main.vertex_created_at.get(&vid).unwrap(),
1960            ts_main_created,
1961            "created_at should preserve oldest timestamp"
1962        );
1963
1964        // Verify updated_at is latest (from tx)
1965        assert_eq!(
1966            *l0_main.vertex_updated_at.get(&vid).unwrap(),
1967            ts_tx_updated,
1968            "updated_at should use latest timestamp"
1969        );
1970
1971        Ok(())
1972    }
1973
1974    #[test]
1975    fn test_merge_preserves_edge_timestamps() -> Result<()> {
1976        let mut l0_main = L0Buffer::new(0, None);
1977        let mut l0_tx = L0Buffer::new(0, None);
1978        let vid_a = Vid::new(1);
1979        let vid_b = Vid::new(2);
1980        let eid = Eid::new(100);
1981
1982        // Main buffer: insert edge with timestamp T1
1983        let ts_main_created = 1000;
1984        let ts_main_updated = 1100;
1985        l0_main.insert_edge(vid_a, vid_b, 1, eid, HashMap::new(), None)?;
1986        l0_main.edge_created_at.insert(eid, ts_main_created);
1987        l0_main.edge_updated_at.insert(eid, ts_main_updated);
1988
1989        // Transaction buffer: update same edge with timestamp T2 (later)
1990        let ts_tx_created = 2000; // should be ignored
1991        let ts_tx_updated = 2100; // should win
1992        l0_tx.insert_edge(vid_a, vid_b, 1, eid, HashMap::new(), None)?;
1993        l0_tx.edge_created_at.insert(eid, ts_tx_created);
1994        l0_tx.edge_updated_at.insert(eid, ts_tx_updated);
1995
1996        // Merge transaction into main
1997        l0_main.merge(&l0_tx)?;
1998
1999        // Verify created_at is oldest (from main)
2000        assert_eq!(
2001            *l0_main.edge_created_at.get(&eid).unwrap(),
2002            ts_main_created,
2003            "edge created_at should preserve oldest timestamp"
2004        );
2005
2006        // Verify updated_at is latest (from tx)
2007        assert_eq!(
2008            *l0_main.edge_updated_at.get(&eid).unwrap(),
2009            ts_tx_updated,
2010            "edge updated_at should use latest timestamp"
2011        );
2012
2013        Ok(())
2014    }
2015
2016    #[test]
2017    fn test_merge_created_at_not_overwritten_for_existing_vertex() -> Result<()> {
2018        use uni_common::Value;
2019
2020        let mut l0_main = L0Buffer::new(0, None);
2021        let mut l0_tx = L0Buffer::new(0, None);
2022        let vid = Vid::new(1);
2023
2024        // Main buffer: vertex created at T1
2025        let ts_original = 1000;
2026        l0_main.insert_vertex(vid, HashMap::new());
2027        l0_main.vertex_created_at.insert(vid, ts_original);
2028        l0_main.vertex_updated_at.insert(vid, ts_original);
2029
2030        // Transaction buffer: update vertex (created_at would be T2 if set)
2031        let ts_tx = 2000;
2032        let mut props = HashMap::new();
2033        props.insert("updated".to_string(), Value::String("yes".to_string()));
2034        l0_tx.insert_vertex(vid, props);
2035        l0_tx.vertex_created_at.insert(vid, ts_tx);
2036        l0_tx.vertex_updated_at.insert(vid, ts_tx);
2037
2038        // Merge transaction into main
2039        l0_main.merge(&l0_tx)?;
2040
2041        // Verify created_at was NOT overwritten (still T1, not T2)
2042        assert_eq!(
2043            *l0_main.vertex_created_at.get(&vid).unwrap(),
2044            ts_original,
2045            "created_at must not be overwritten for existing vertex"
2046        );
2047
2048        // Verify updated_at WAS updated (now T2)
2049        assert_eq!(
2050            *l0_main.vertex_updated_at.get(&vid).unwrap(),
2051            ts_tx,
2052            "updated_at should reflect transaction timestamp"
2053        );
2054
2055        // Verify properties were merged
2056        assert!(
2057            l0_main
2058                .vertex_properties
2059                .get(&vid)
2060                .unwrap()
2061                .contains_key("updated")
2062        );
2063
2064        Ok(())
2065    }
2066
2067    /// Test for Issue #23: Vertex labels preserved through replay_mutations
2068    #[test]
2069    fn test_replay_mutations_preserves_vertex_labels() -> Result<()> {
2070        use crate::runtime::wal::Mutation;
2071
2072        let mut l0 = L0Buffer::new(0, None);
2073        let vid = Vid::new(42);
2074
2075        // Create InsertVertex mutation with labels
2076        let mutations = vec![Mutation::InsertVertex {
2077            vid,
2078            properties: {
2079                let mut props = HashMap::new();
2080                props.insert(
2081                    "name".to_string(),
2082                    uni_common::Value::String("Alice".to_string()),
2083                );
2084                props
2085            },
2086            labels: vec!["Person".to_string(), "User".to_string()],
2087        }];
2088
2089        // Replay mutations
2090        l0.replay_mutations(mutations)?;
2091
2092        // Verify vertex exists in L0
2093        assert!(l0.vertex_properties.contains_key(&vid));
2094
2095        // Verify labels are preserved
2096        let labels = l0.get_vertex_labels(vid).expect("Labels should exist");
2097        assert_eq!(labels.len(), 2);
2098        assert!(labels.contains(&"Person".to_string()));
2099        assert!(labels.contains(&"User".to_string()));
2100
2101        // Verify vertex is findable by label
2102        let person_vids = l0.vids_for_label("Person");
2103        assert_eq!(person_vids.len(), 1);
2104        assert_eq!(person_vids[0], vid);
2105
2106        let user_vids = l0.vids_for_label("User");
2107        assert_eq!(user_vids.len(), 1);
2108        assert_eq!(user_vids[0], vid);
2109
2110        Ok(())
2111    }
2112
2113    /// Test for Issue #23: DeleteVertex labels preserved for tombstone flushing
2114    #[test]
2115    fn test_replay_mutations_preserves_delete_vertex_labels() -> Result<()> {
2116        use crate::runtime::wal::Mutation;
2117
2118        let mut l0 = L0Buffer::new(0, None);
2119        let vid = Vid::new(99);
2120
2121        // First insert vertex with labels
2122        l0.insert_vertex_with_labels(
2123            vid,
2124            HashMap::new(),
2125            &["Person".to_string(), "Admin".to_string()],
2126        );
2127
2128        // Verify vertex and labels exist
2129        assert!(l0.vertex_properties.contains_key(&vid));
2130        let labels = l0.get_vertex_labels(vid).expect("Labels should exist");
2131        assert_eq!(labels.len(), 2);
2132
2133        // Create DeleteVertex mutation with labels
2134        let mutations = vec![Mutation::DeleteVertex {
2135            vid,
2136            labels: vec!["Person".to_string(), "Admin".to_string()],
2137        }];
2138
2139        // Replay deletion
2140        l0.replay_mutations(mutations)?;
2141
2142        // Verify vertex is tombstoned
2143        assert!(l0.vertex_tombstones.contains(&vid));
2144
2145        // Verify labels are preserved in L0 (needed for Issue #76 tombstone flushing)
2146        // The labels should still be accessible for the flush logic to know which tables to update
2147        let labels = l0.get_vertex_labels(vid);
2148        assert!(
2149            labels.is_some(),
2150            "Labels should be preserved even after deletion for tombstone flushing"
2151        );
2152
2153        Ok(())
2154    }
2155
2156    /// Test for Issue #28: Edge type name preserved through replay_mutations
2157    #[test]
2158    fn test_replay_mutations_preserves_edge_type_name() -> Result<()> {
2159        use crate::runtime::wal::Mutation;
2160
2161        let mut l0 = L0Buffer::new(0, None);
2162        let src = Vid::new(1);
2163        let dst = Vid::new(2);
2164        let eid = Eid::new(500);
2165        let edge_type = 100;
2166
2167        // Create InsertEdge mutation with edge_type_name
2168        let mutations = vec![Mutation::InsertEdge {
2169            src_vid: src,
2170            dst_vid: dst,
2171            edge_type,
2172            eid,
2173            version: 1,
2174            properties: {
2175                let mut props = HashMap::new();
2176                props.insert("since".to_string(), uni_common::Value::Int(2020));
2177                props
2178            },
2179            edge_type_name: Some("KNOWS".to_string()),
2180        }];
2181
2182        // Replay mutations
2183        l0.replay_mutations(mutations)?;
2184
2185        // Verify edge exists in L0
2186        assert!(l0.edge_endpoints.contains_key(&eid));
2187
2188        // Verify edge type name is preserved
2189        let type_name = l0.get_edge_type(eid).expect("Edge type name should exist");
2190        assert_eq!(type_name, "KNOWS");
2191
2192        // Verify edge is findable by type name
2193        let knows_eids = l0.eids_for_type("KNOWS");
2194        assert_eq!(knows_eids.len(), 1);
2195        assert_eq!(knows_eids[0], eid);
2196
2197        Ok(())
2198    }
2199
2200    /// Test for Issue #28: Edge type mapping survives multiple replay cycles
2201    #[test]
2202    fn test_edge_type_mapping_survives_multiple_replays() -> Result<()> {
2203        use crate::runtime::wal::Mutation;
2204
2205        let mut l0 = L0Buffer::new(0, None);
2206
2207        // Replay multiple edge insertions with different types
2208        let mutations = vec![
2209            Mutation::InsertEdge {
2210                src_vid: Vid::new(1),
2211                dst_vid: Vid::new(2),
2212                edge_type: 100,
2213                eid: Eid::new(1000),
2214                version: 1,
2215                properties: HashMap::new(),
2216                edge_type_name: Some("KNOWS".to_string()),
2217            },
2218            Mutation::InsertEdge {
2219                src_vid: Vid::new(2),
2220                dst_vid: Vid::new(3),
2221                edge_type: 101,
2222                eid: Eid::new(1001),
2223                version: 2,
2224                properties: HashMap::new(),
2225                edge_type_name: Some("LIKES".to_string()),
2226            },
2227            Mutation::InsertEdge {
2228                src_vid: Vid::new(3),
2229                dst_vid: Vid::new(1),
2230                edge_type: 100,
2231                eid: Eid::new(1002),
2232                version: 3,
2233                properties: HashMap::new(),
2234                edge_type_name: Some("KNOWS".to_string()),
2235            },
2236        ];
2237
2238        l0.replay_mutations(mutations)?;
2239
2240        // Verify all edge type mappings are preserved
2241        assert_eq!(l0.get_edge_type(Eid::new(1000)), Some("KNOWS"));
2242        assert_eq!(l0.get_edge_type(Eid::new(1001)), Some("LIKES"));
2243        assert_eq!(l0.get_edge_type(Eid::new(1002)), Some("KNOWS"));
2244
2245        // Verify edges can be queried by type
2246        let knows_edges = l0.eids_for_type("KNOWS");
2247        assert_eq!(knows_edges.len(), 2);
2248        assert!(knows_edges.contains(&Eid::new(1000)));
2249        assert!(knows_edges.contains(&Eid::new(1002)));
2250
2251        let likes_edges = l0.eids_for_type("LIKES");
2252        assert_eq!(likes_edges.len(), 1);
2253        assert_eq!(likes_edges[0], Eid::new(1001));
2254
2255        Ok(())
2256    }
2257
2258    /// Test for Issue #23 + #28: Combined vertex labels and edge types in replay
2259    #[test]
2260    fn test_replay_mutations_combined_labels_and_edge_types() -> Result<()> {
2261        use crate::runtime::wal::Mutation;
2262
2263        let mut l0 = L0Buffer::new(0, None);
2264        let alice = Vid::new(1);
2265        let bob = Vid::new(2);
2266        let eid = Eid::new(100);
2267
2268        // Simulate crash recovery scenario: replay full transaction log
2269        let mutations = vec![
2270            // Insert Alice with Person label
2271            Mutation::InsertVertex {
2272                vid: alice,
2273                properties: {
2274                    let mut props = HashMap::new();
2275                    props.insert(
2276                        "name".to_string(),
2277                        uni_common::Value::String("Alice".to_string()),
2278                    );
2279                    props
2280                },
2281                labels: vec!["Person".to_string()],
2282            },
2283            // Insert Bob with Person label
2284            Mutation::InsertVertex {
2285                vid: bob,
2286                properties: {
2287                    let mut props = HashMap::new();
2288                    props.insert(
2289                        "name".to_string(),
2290                        uni_common::Value::String("Bob".to_string()),
2291                    );
2292                    props
2293                },
2294                labels: vec!["Person".to_string()],
2295            },
2296            // Create KNOWS edge between them
2297            Mutation::InsertEdge {
2298                src_vid: alice,
2299                dst_vid: bob,
2300                edge_type: 1,
2301                eid,
2302                version: 3,
2303                properties: HashMap::new(),
2304                edge_type_name: Some("KNOWS".to_string()),
2305            },
2306        ];
2307
2308        // Replay all mutations
2309        l0.replay_mutations(mutations)?;
2310
2311        // Verify vertex labels preserved
2312        assert_eq!(l0.get_vertex_labels(alice).unwrap().len(), 1);
2313        assert_eq!(l0.get_vertex_labels(bob).unwrap().len(), 1);
2314        assert_eq!(l0.vids_for_label("Person").len(), 2);
2315
2316        // Verify edge type name preserved
2317        assert_eq!(l0.get_edge_type(eid).unwrap(), "KNOWS");
2318        assert_eq!(l0.eids_for_type("KNOWS").len(), 1);
2319
2320        // Verify graph structure
2321        let alice_neighbors = l0.get_neighbors(alice, 1, Direction::Outgoing);
2322        assert_eq!(alice_neighbors.len(), 1);
2323        assert_eq!(alice_neighbors[0].0, bob);
2324
2325        Ok(())
2326    }
2327
2328    /// Test for Issue #23: Empty labels should deserialize correctly (backward compat)
2329    #[test]
2330    fn test_replay_mutations_backward_compat_empty_labels() -> Result<()> {
2331        use crate::runtime::wal::Mutation;
2332
2333        let mut l0 = L0Buffer::new(0, None);
2334        let vid = Vid::new(1);
2335
2336        // Simulate old WAL format: InsertVertex with empty labels
2337        // (This tests #[serde(default)] behavior)
2338        let mutations = vec![Mutation::InsertVertex {
2339            vid,
2340            properties: HashMap::new(),
2341            labels: vec![], // Empty labels (old format compatibility)
2342        }];
2343
2344        l0.replay_mutations(mutations)?;
2345
2346        // Vertex should exist
2347        assert!(l0.vertex_properties.contains_key(&vid));
2348
2349        // Labels should be empty but entry should exist in vertex_labels
2350        let labels = l0.get_vertex_labels(vid);
2351        assert!(labels.is_some(), "Labels entry should exist even if empty");
2352        assert_eq!(labels.unwrap().len(), 0);
2353
2354        Ok(())
2355    }
2356
2357    #[test]
2358    fn test_now_nanos_returns_nanosecond_range() {
2359        // Test that now_nanos() returns a value in nanosecond range
2360        // As of 2025, Unix timestamp in nanoseconds should be > 1.7e18
2361        // (2025-01-01 is approximately 1,735,689,600 seconds = 1.735e18 nanoseconds)
2362        let now = now_nanos();
2363
2364        // Verify it's in nanosecond range (not microseconds which would be 1000x smaller)
2365        assert!(
2366            now > 1_700_000_000_000_000_000,
2367            "now_nanos() returned {}, expected > 1.7e18 for nanoseconds",
2368            now
2369        );
2370
2371        // Sanity check: should also be less than year 2100 in nanoseconds (4.1e18)
2372        assert!(
2373            now < 4_100_000_000_000_000_000,
2374            "now_nanos() returned {}, expected < 4.1e18",
2375            now
2376        );
2377    }
2378}