uni-store 1.1.0

Storage layer for Uni graph database - Lance datasets, LSM deltas, and WAL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team

//! Main vertex table for unified vertex storage.
//!
//! This module implements the main `vertices` table as described in STORAGE_DESIGN.md.
//! The main table contains all vertices in the graph with:
//! - `_vid`: Internal vertex ID (primary key)
//! - `_uid`: Content-addressed unique ID (SHA3-256 hash)
//! - `ext_id`: Optional external/user-provided ID (globally unique)
//! - `labels`: List of label names (OpenCypher multi-label)
//! - `props_json`: All properties as JSONB blob
//! - `_deleted`: Soft-delete flag
//! - `_version`: MVCC version
//! - `_created_at`: Creation timestamp
//! - `_updated_at`: Update timestamp

use crate::backend::StorageBackend;
use crate::backend::table_names;
use crate::backend::types::{ScalarIndexType, ScanRequest, WriteMode};
use crate::storage::arrow_convert::build_timestamp_column_from_vid_map;
use anyhow::{Result, anyhow};
use arrow_array::builder::{
    FixedSizeBinaryBuilder, LargeBinaryBuilder, ListBuilder, StringBuilder,
};
use arrow_array::{Array, ArrayRef, BooleanArray, RecordBatch, UInt64Array};
use arrow_schema::{DataType, Field, Schema as ArrowSchema, TimeUnit};
use sha3::{Digest, Sha3_256};
use std::collections::HashMap;
use std::sync::Arc;
use uni_common::Properties;
use uni_common::core::id::{UniId, Vid};

/// Main vertex dataset for the unified `vertices` table.
///
/// This table contains all vertices regardless of label, providing:
/// - Fast ID-based lookups without knowing the label
/// - Global ext_id uniqueness enforcement
/// - Multi-label storage with labels as a list column
#[derive(Debug)]
pub struct MainVertexDataset {
    _base_uri: String,
}

impl MainVertexDataset {
    /// Create a new MainVertexDataset.
    pub fn new(base_uri: &str) -> Self {
        Self {
            _base_uri: base_uri.to_string(),
        }
    }

    /// Get the Arrow schema for the main vertices table.
    pub fn get_arrow_schema() -> Arc<ArrowSchema> {
        Arc::new(ArrowSchema::new(vec![
            Field::new("_vid", DataType::UInt64, false),
            Field::new("_uid", DataType::FixedSizeBinary(32), true),
            Field::new("ext_id", DataType::Utf8, true),
            Field::new(
                "labels",
                DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
                false,
            ),
            Field::new("props_json", DataType::LargeBinary, true),
            Field::new("_deleted", DataType::Boolean, false),
            Field::new("_version", DataType::UInt64, false),
            Field::new(
                "_created_at",
                DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
                true,
            ),
            Field::new(
                "_updated_at",
                DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
                true,
            ),
        ]))
    }

    /// Get the table name for the main vertices table.
    pub fn table_name() -> &'static str {
        table_names::main_vertex_table_name()
    }

    /// Compute the UniId (content-addressed hash) for a vertex.
    fn compute_vertex_uid(labels: &[String], ext_id: Option<&str>, props: &Properties) -> UniId {
        let mut hasher = Sha3_256::new();

        // Hash labels (sorted for consistency)
        let mut sorted_labels = labels.to_vec();
        sorted_labels.sort();
        for label in &sorted_labels {
            hasher.update(label.as_bytes());
            hasher.update(b"\0");
        }

        // Hash ext_id if present
        if let Some(ext_id) = ext_id {
            hasher.update(b"ext_id:");
            hasher.update(ext_id.as_bytes());
            hasher.update(b"\0");
        }

        // Hash properties (sorted by key for deterministic hashing)
        let mut sorted_keys: Vec<_> = props.keys().collect();
        sorted_keys.sort();
        for key in sorted_keys {
            if key == "ext_id" {
                continue; // Already handled above
            }
            if let Some(val) = props.get(key) {
                hasher.update(key.as_bytes());
                hasher.update(b":");
                hasher.update(val.to_string().as_bytes());
                hasher.update(b"\0");
            }
        }

        let result = hasher.finalize();
        UniId::from_bytes(result.into())
    }

    /// Build a record batch for the main vertices table.
    ///
    /// # Arguments
    /// * `vertices` - List of (vid, labels, properties, deleted, version) tuples
    /// * `created_at` - Optional map of Vid -> nanoseconds since epoch
    /// * `updated_at` - Optional map of Vid -> nanoseconds since epoch
    pub fn build_record_batch(
        vertices: &[(Vid, Vec<String>, Properties, bool, u64)],
        created_at: Option<&HashMap<Vid, i64>>,
        updated_at: Option<&HashMap<Vid, i64>>,
    ) -> Result<RecordBatch> {
        let arrow_schema = Self::get_arrow_schema();
        let mut columns: Vec<ArrayRef> = Vec::with_capacity(arrow_schema.fields().len());

        // _vid column
        let vids: Vec<u64> = vertices.iter().map(|(v, _, _, _, _)| v.as_u64()).collect();
        columns.push(Arc::new(UInt64Array::from(vids)));

        // _uid column
        let mut uid_builder = FixedSizeBinaryBuilder::new(32);
        for (_, labels, props, _, _) in vertices.iter() {
            let ext_id = props.get("ext_id").and_then(|v| v.as_str());
            let uid = Self::compute_vertex_uid(labels, ext_id, props);
            uid_builder.append_value(uid.as_bytes())?;
        }
        columns.push(Arc::new(uid_builder.finish()));

        // ext_id column
        let mut ext_id_builder = StringBuilder::new();
        for (_, _, props, _, _) in vertices.iter() {
            if let Some(ext_id_val) = props.get("ext_id").and_then(|v| v.as_str()) {
                ext_id_builder.append_value(ext_id_val);
            } else {
                ext_id_builder.append_null();
            }
        }
        columns.push(Arc::new(ext_id_builder.finish()));

        // labels column (List<String>)
        let mut labels_builder = ListBuilder::new(StringBuilder::new());
        for (_, labels, _, _, _) in vertices.iter() {
            let values_builder = labels_builder.values();
            for label in labels {
                values_builder.append_value(label);
            }
            labels_builder.append(true);
        }
        columns.push(Arc::new(labels_builder.finish()));

        // props_json column (JSONB binary encoding)
        let mut props_json_builder = LargeBinaryBuilder::new();
        for (_, _, props, _, _) in vertices.iter() {
            let jsonb_bytes = {
                let json_val = serde_json::to_value(props).unwrap_or(serde_json::json!({}));
                let uni_val: uni_common::Value = json_val.into();
                uni_common::cypher_value_codec::encode(&uni_val)
            };
            props_json_builder.append_value(&jsonb_bytes);
        }
        columns.push(Arc::new(props_json_builder.finish()));

        // _deleted column
        let deleted: Vec<bool> = vertices.iter().map(|(_, _, _, d, _)| *d).collect();
        columns.push(Arc::new(BooleanArray::from(deleted)));

        // _version column
        let versions: Vec<u64> = vertices.iter().map(|(_, _, _, _, v)| *v).collect();
        columns.push(Arc::new(UInt64Array::from(versions)));

        // _created_at and _updated_at columns using shared builder
        let vids = vertices.iter().map(|(v, _, _, _, _)| *v);
        columns.push(build_timestamp_column_from_vid_map(
            vids.clone(),
            created_at,
        ));
        columns.push(build_timestamp_column_from_vid_map(vids, updated_at));

        RecordBatch::try_new(arrow_schema, columns).map_err(|e| anyhow!(e))
    }

    /// Write a batch to the main vertices table.
    ///
    /// Creates the table if it doesn't exist, otherwise appends to it.
    pub async fn write_batch(backend: &dyn StorageBackend, batch: RecordBatch) -> Result<()> {
        let table_name = table_names::main_vertex_table_name();

        if backend.table_exists(table_name).await? {
            backend
                .write(table_name, vec![batch], WriteMode::Append)
                .await
        } else {
            backend.create_table(table_name, vec![batch]).await
        }
    }

    /// Ensure default indexes exist on the main vertices table.
    pub async fn ensure_default_indexes(backend: &dyn StorageBackend) -> Result<()> {
        let table_name = table_names::main_vertex_table_name();

        // BTree indexes for primary key and lookup columns
        let _ = backend
            .create_scalar_index(table_name, "_vid", ScalarIndexType::BTree)
            .await;
        let _ = backend
            .create_scalar_index(table_name, "ext_id", ScalarIndexType::BTree)
            .await;
        let _ = backend
            .create_scalar_index(table_name, "_uid", ScalarIndexType::BTree)
            .await;

        // LabelList index for array_contains() queries on labels
        let _ = backend
            .create_scalar_index(table_name, "labels", ScalarIndexType::LabelList)
            .await;

        Ok(())
    }

    /// Query the main vertices table for a vertex by ext_id.
    ///
    /// Returns the Vid if found, None otherwise.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    ///   Pass `None` for writer uniqueness checks (global visibility).
    ///   Pass `Some(hwm)` for query-time snapshot isolation.
    pub async fn find_by_ext_id(
        backend: &dyn StorageBackend,
        ext_id: &str,
        version: Option<u64>,
    ) -> Result<Option<Vid>> {
        let table_name = table_names::main_vertex_table_name();

        if !backend.table_exists(table_name).await? {
            return Ok(None);
        }

        let mut filter = format!(
            "ext_id = '{}' AND _deleted = false",
            ext_id.replace('\'', "''")
        );
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["_vid".to_string()]),
            )
            .await?;

        for batch in results {
            if batch.num_rows() > 0
                && let Some(vid_col) = batch.column_by_name("_vid")
                && let Some(vid_arr) = vid_col.as_any().downcast_ref::<UInt64Array>()
            {
                return Ok(Some(Vid::from(vid_arr.value(0))));
            }
        }

        Ok(None)
    }

    /// Check if an ext_id already exists in the main vertices table.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    pub async fn ext_id_exists(
        backend: &dyn StorageBackend,
        ext_id: &str,
        version: Option<u64>,
    ) -> Result<bool> {
        Ok(Self::find_by_ext_id(backend, ext_id, version)
            .await?
            .is_some())
    }

    /// Find labels for a vertex by VID in the main vertices table.
    ///
    /// Returns the list of labels if found, None otherwise.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    pub async fn find_labels_by_vid(
        backend: &dyn StorageBackend,
        vid: Vid,
        version: Option<u64>,
    ) -> Result<Option<Vec<String>>> {
        let table_name = table_names::main_vertex_table_name();

        if !backend.table_exists(table_name).await? {
            return Ok(None);
        }

        let mut filter = format!("_vid = {} AND _deleted = false", vid.as_u64());
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["labels".to_string()]),
            )
            .await?;

        for batch in results {
            if batch.num_rows() > 0
                && let Some(labels_col) = batch.column_by_name("labels")
                && let Some(list_arr) = labels_col.as_any().downcast_ref::<arrow_array::ListArray>()
            {
                // Labels is a List<Utf8> column
                let values = list_arr.value(0);
                if let Some(str_arr) = values.as_any().downcast_ref::<arrow_array::StringArray>() {
                    let labels: Vec<String> = (0..str_arr.len())
                        .filter_map(|i| {
                            if str_arr.is_null(i) {
                                None
                            } else {
                                Some(str_arr.value(i).to_string())
                            }
                        })
                        .collect();
                    return Ok(Some(labels));
                }
            }
        }

        Ok(None)
    }

    /// Find all non-deleted VIDs in the main vertices table.
    ///
    /// Returns all VIDs where `_deleted = false`.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    ///
    /// # Errors
    ///
    /// Returns an error if the table query fails.
    pub async fn find_all_vids(
        backend: &dyn StorageBackend,
        version: Option<u64>,
    ) -> Result<Vec<Vid>> {
        let table_name = table_names::main_vertex_table_name();

        if !backend.table_exists(table_name).await? {
            return Ok(Vec::new());
        }

        let mut filter = "_deleted = false".to_string();
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["_vid".to_string()]),
            )
            .await?;

        let mut vids = Vec::new();
        for batch in results {
            if let Some(vid_col) = batch.column_by_name("_vid")
                && let Some(vid_arr) = vid_col.as_any().downcast_ref::<UInt64Array>()
            {
                for i in 0..vid_arr.len() {
                    if !vid_arr.is_null(i) {
                        vids.push(Vid::new(vid_arr.value(i)));
                    }
                }
            }
        }

        Ok(vids)
    }

    /// Find VIDs by label name in the main vertices table.
    ///
    /// Searches for vertices where the labels array contains the given label
    /// and `_deleted = false`.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    ///
    /// # Errors
    ///
    /// Returns an error if the table query fails.
    pub async fn find_vids_by_label_name(
        backend: &dyn StorageBackend,
        label: &str,
        version: Option<u64>,
    ) -> Result<Vec<Vid>> {
        let table_name = table_names::main_vertex_table_name();

        if !backend.table_exists(table_name).await? {
            return Ok(Vec::new());
        }

        // Use SQL array_contains to filter by label
        let mut filter = format!("_deleted = false AND array_contains(labels, '{}')", label);
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["_vid".to_string()]),
            )
            .await?;

        let mut vids = Vec::new();
        for batch in results {
            if let Some(vid_col) = batch.column_by_name("_vid")
                && let Some(vid_arr) = vid_col.as_any().downcast_ref::<UInt64Array>()
            {
                for i in 0..vid_arr.len() {
                    if !vid_arr.is_null(i) {
                        vids.push(Vid::new(vid_arr.value(i)));
                    }
                }
            }
        }

        Ok(vids)
    }

    /// Find VIDs by multiple label names (intersection semantics).
    ///
    /// Returns vertices that have ALL the specified labels.
    /// Uses `array_contains(labels, 'A') AND array_contains(labels, 'B')` filtering.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    pub async fn find_vids_by_labels(
        backend: &dyn StorageBackend,
        labels: &[&str],
        version: Option<u64>,
    ) -> Result<Vec<Vid>> {
        let table_name = table_names::main_vertex_table_name();

        if labels.is_empty() || !backend.table_exists(table_name).await? {
            return Ok(Vec::new());
        }

        // Build AND conditions for each label
        let label_conditions: Vec<String> = labels
            .iter()
            .map(|label| {
                let escaped = label.replace('\'', "''");
                format!("array_contains(labels, '{}')", escaped)
            })
            .collect();

        let mut filter = format!("_deleted = false AND {}", label_conditions.join(" AND "));
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["_vid".to_string()]),
            )
            .await?;

        let mut vids = Vec::new();
        for batch in results {
            if let Some(vid_col) = batch.column_by_name("_vid")
                && let Some(vid_arr) = vid_col.as_any().downcast_ref::<UInt64Array>()
            {
                for i in 0..vid_arr.len() {
                    if !vid_arr.is_null(i) {
                        vids.push(Vid::new(vid_arr.value(i)));
                    }
                }
            }
        }

        Ok(vids)
    }

    /// Batch-fetch properties for multiple VIDs from the main vertices table.
    ///
    /// Returns a HashMap mapping VIDs to their parsed properties.
    /// Non-deleted vertices are returned with properties from props_json.
    /// This is used for schemaless vertex scans via DataFusion.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    ///
    /// # Errors
    ///
    /// Returns an error if the table query fails or JSON parsing fails.
    pub async fn find_batch_props_by_vids(
        backend: &dyn StorageBackend,
        vids: &[Vid],
        version: Option<u64>,
    ) -> Result<HashMap<Vid, Properties>> {
        let table_name = table_names::main_vertex_table_name();

        if vids.is_empty() || !backend.table_exists(table_name).await? {
            return Ok(HashMap::new());
        }

        // Build IN clause for VIDs
        let vid_list: Vec<String> = vids.iter().map(|v| v.as_u64().to_string()).collect();
        let mut filter = format!("_vid IN ({}) AND _deleted = false", vid_list.join(", "));
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["_vid".to_string(), "props_json".to_string()]),
            )
            .await?;

        let mut props_map = HashMap::new();

        for batch in results {
            let vid_col = batch.column_by_name("_vid");
            let props_col = batch.column_by_name("props_json");

            if let (Some(vid_arr), Some(props_arr)) = (
                vid_col.and_then(|c| c.as_any().downcast_ref::<UInt64Array>()),
                props_col.and_then(|c| c.as_any().downcast_ref::<arrow_array::LargeBinaryArray>()),
            ) {
                for i in 0..batch.num_rows() {
                    if vid_arr.is_null(i) {
                        continue;
                    }
                    let vid = Vid::new(vid_arr.value(i));

                    let props: Properties = if props_arr.is_null(i) || props_arr.value(i).is_empty()
                    {
                        Properties::new()
                    } else {
                        let bytes = props_arr.value(i);
                        let uni_val = uni_common::cypher_value_codec::decode(bytes)
                            .map_err(|e| anyhow!("Failed to decode CypherValue: {}", e))?;
                        let json_val: serde_json::Value = uni_val.into();
                        serde_json::from_value(json_val)
                            .map_err(|e| anyhow!("Failed to parse props_json: {}", e))?
                    };

                    props_map.insert(vid, props);
                }
            }
        }

        Ok(props_map)
    }

    /// Find properties for a vertex by VID in the main vertices table.
    ///
    /// Returns the props_json parsed into a Properties HashMap if found.
    /// This is used as a fallback for unknown/schemaless labels.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    ///
    /// # Errors
    ///
    /// Returns an error if the table query fails or JSON parsing fails.
    pub async fn find_props_by_vid(
        backend: &dyn StorageBackend,
        vid: Vid,
        version: Option<u64>,
    ) -> Result<Option<Properties>> {
        let table_name = table_names::main_vertex_table_name();

        if !backend.table_exists(table_name).await? {
            return Ok(None);
        }

        let mut filter = format!("_vid = {} AND _deleted = false", vid.as_u64());
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["props_json".to_string(), "_version".to_string()]),
            )
            .await?;

        // Find the row with highest version (latest)
        let mut best_props: Option<Properties> = None;
        let mut best_version: u64 = 0;

        for batch in results {
            let props_col = batch.column_by_name("props_json");
            let version_col = batch.column_by_name("_version");

            if let (Some(props_arr), Some(ver_arr)) = (
                props_col.and_then(|c| c.as_any().downcast_ref::<arrow_array::LargeBinaryArray>()),
                version_col.and_then(|c| c.as_any().downcast_ref::<UInt64Array>()),
            ) {
                for i in 0..batch.num_rows() {
                    let version = if ver_arr.is_null(i) {
                        0
                    } else {
                        ver_arr.value(i)
                    };

                    if version >= best_version {
                        best_version = version;
                        if props_arr.is_null(i) || props_arr.value(i).is_empty() {
                            best_props = Some(Properties::new());
                        } else {
                            let bytes = props_arr.value(i);
                            let uni_val = uni_common::cypher_value_codec::decode(bytes)
                                .map_err(|e| anyhow!("Failed to decode CypherValue: {}", e))?;
                            let json_val: serde_json::Value = uni_val.into();
                            let parsed: Properties = serde_json::from_value(json_val)
                                .map_err(|e| anyhow!("Failed to parse props_json: {}", e))?;
                            best_props = Some(parsed);
                        }
                    }
                }
            }
        }

        Ok(best_props)
    }

    /// Batch-fetch labels for multiple VIDs from the main vertices table.
    ///
    /// # Arguments
    /// * `version` - Optional version high water mark for snapshot isolation.
    pub async fn find_batch_labels_by_vids(
        backend: &dyn StorageBackend,
        vids: &[Vid],
        version: Option<u64>,
    ) -> Result<HashMap<Vid, Vec<String>>> {
        let table_name = table_names::main_vertex_table_name();

        if vids.is_empty() || !backend.table_exists(table_name).await? {
            return Ok(HashMap::new());
        }

        // Build IN clause for VIDs
        let vid_list: Vec<String> = vids.iter().map(|v| v.as_u64().to_string()).collect();
        let mut filter = format!("_vid IN ({}) AND _deleted = false", vid_list.join(", "));
        if let Some(hwm) = version {
            filter.push_str(&format!(" AND _version <= {}", hwm));
        }

        let results = backend
            .scan(
                ScanRequest::all(table_name)
                    .with_filter(filter)
                    .with_columns(vec!["_vid".to_string(), "labels".to_string()]),
            )
            .await?;

        let mut label_map = HashMap::new();

        for batch in results {
            let vid_col = batch.column_by_name("_vid");
            let labels_col = batch.column_by_name("labels");

            if let (Some(vid_arr), Some(labels_arr)) = (
                vid_col.and_then(|c| c.as_any().downcast_ref::<UInt64Array>()),
                labels_col.and_then(|c| c.as_any().downcast_ref::<arrow_array::ListArray>()),
            ) {
                for i in 0..batch.num_rows() {
                    if vid_arr.is_null(i) {
                        continue;
                    }
                    let vid = Vid::new(vid_arr.value(i));

                    let values = labels_arr.value(i);
                    if let Some(str_arr) =
                        values.as_any().downcast_ref::<arrow_array::StringArray>()
                    {
                        let labels: Vec<String> = (0..str_arr.len())
                            .filter_map(|j| {
                                if str_arr.is_null(j) {
                                    None
                                } else {
                                    Some(str_arr.value(j).to_string())
                                }
                            })
                            .collect();
                        label_map.insert(vid, labels);
                    }
                }
            }
        }

        Ok(label_map)
    }
}

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

    #[test]
    fn test_main_vertex_schema() {
        let schema = MainVertexDataset::get_arrow_schema();
        assert_eq!(schema.fields().len(), 9);
        assert!(schema.field_with_name("_vid").is_ok());
        assert!(schema.field_with_name("_uid").is_ok());
        assert!(schema.field_with_name("ext_id").is_ok());
        assert!(schema.field_with_name("labels").is_ok());
        assert!(schema.field_with_name("props_json").is_ok());
        assert!(schema.field_with_name("_deleted").is_ok());
        assert!(schema.field_with_name("_version").is_ok());
        assert!(schema.field_with_name("_created_at").is_ok());
        assert!(schema.field_with_name("_updated_at").is_ok());
    }

    #[test]
    fn test_build_record_batch() {
        use uni_common::Value;
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("Alice".to_string()));
        props.insert("ext_id".to_string(), Value::String("user_001".to_string()));

        let vertices = vec![(Vid::new(1), vec!["Person".to_string()], props, false, 1u64)];

        let batch = MainVertexDataset::build_record_batch(&vertices, None, None).unwrap();
        assert_eq!(batch.num_rows(), 1);
        assert_eq!(batch.num_columns(), 9);

        // Check ext_id was extracted
        let ext_id_col = batch.column_by_name("ext_id").unwrap();
        let ext_id_arr = ext_id_col.as_any().downcast_ref::<StringArray>().unwrap();
        assert_eq!(ext_id_arr.value(0), "user_001");
    }

    #[test]
    fn test_compute_vertex_uid_deterministic() {
        use uni_common::Value;
        let labels = vec!["Person".to_string()];
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("Alice".to_string()));

        let uid1 = MainVertexDataset::compute_vertex_uid(&labels, None, &props);
        let uid2 = MainVertexDataset::compute_vertex_uid(&labels, None, &props);
        assert_eq!(uid1, uid2, "Same inputs should produce same UID");
    }

    #[test]
    fn test_compute_vertex_uid_label_order_independence() {
        use uni_common::Value;
        let mut props = HashMap::new();
        props.insert("name".to_string(), Value::String("Alice".to_string()));

        let labels_ab = vec!["Admin".to_string(), "Person".to_string()];
        let labels_ba = vec!["Person".to_string(), "Admin".to_string()];

        let uid1 = MainVertexDataset::compute_vertex_uid(&labels_ab, None, &props);
        let uid2 = MainVertexDataset::compute_vertex_uid(&labels_ba, None, &props);
        assert_eq!(uid1, uid2, "Label order should not affect UID");
    }

    #[test]
    fn test_compute_vertex_uid_different_props_different_uid() {
        use uni_common::Value;
        let labels = vec!["Person".to_string()];

        let mut props1 = HashMap::new();
        props1.insert("name".to_string(), Value::String("Alice".to_string()));

        let mut props2 = HashMap::new();
        props2.insert("name".to_string(), Value::String("Bob".to_string()));

        let uid1 = MainVertexDataset::compute_vertex_uid(&labels, None, &props1);
        let uid2 = MainVertexDataset::compute_vertex_uid(&labels, None, &props2);
        assert_ne!(
            uid1, uid2,
            "Different properties should produce different UIDs"
        );
    }
}