Repository navigation
Expand file tree
/
Copy pathmanifest.rs
More file actions
6121 lines (5515 loc) · 228 KB
/
Copy pathmanifest.rs
File metadata and controls
6121 lines (5515 loc) · 228 KB
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
//! Manifest-based namespace implementation
//!
//! This module provides a namespace implementation that uses a manifest table
//! to track tables and nested namespaces.
use super::manifest_feature_flags::{ensure_readable, ensure_writable};
use arrow::array::builder::{ListBuilder, StringBuilder};
use arrow::array::{Array, ListArray, RecordBatch, RecordBatchIterator, StringArray, UInt64Array};
use arrow::datatypes::{DataType, Field, Schema as ArrowSchema, SchemaRef};
use arrow_ipc::reader::StreamReader;
use async_trait::async_trait;
use bytes::Bytes;
use datafusion_common::DataFusionError;
use datafusion_physical_plan::{
SendableRecordBatchStream,
stream::RecordBatchStreamAdapter as DatafusionRecordBatchStreamAdapter,
};
use futures::{
FutureExt, TryStreamExt,
stream::{self, StreamExt},
};
use lance::dataset::index::LanceIndexStoreExt;
use lance::dataset::transaction::{Operation, Transaction};
use lance::dataset::{
InsertBuilder, ReadParams, WhenMatched, WriteMode, WriteParams, builder::DatasetBuilder,
};
use lance::session::Session;
use lance::{Dataset, dataset::scanner::Scanner};
use lance_core::Error as LanceError;
use lance_core::datatypes::LANCE_UNENFORCED_PRIMARY_KEY_POSITION;
use lance_core::{Error, ROW_ID, Result, box_error};
use lance_index::progress::noop_progress;
use lance_index::registry::IndexPluginRegistry;
use lance_index::scalar::lance_format::LanceIndexStore;
use lance_index::scalar::registry::VALUE_COLUMN_NAME;
use lance_index::scalar::{
BuiltinIndexType, CreatedIndex, ScalarIndexParams, index_files_to_table,
};
use lance_io::object_store::{ObjectStore, ObjectStoreParams};
use lance_io::stream::RecordBatchStream as LanceRecordBatchStream;
use lance_namespace::LanceNamespace;
use lance_namespace::error::NamespaceError;
use lance_namespace::models::{
AlterTableAddColumnsRequest, AlterTableAddColumnsResponse, AlterTableAlterColumnsRequest,
AlterTableAlterColumnsResponse, AlterTableDropColumnsRequest, AlterTableDropColumnsResponse,
CreateNamespaceRequest, CreateNamespaceResponse, CreateTableRequest, CreateTableResponse,
DeclareTableRequest, DeclareTableResponse, DeregisterTableRequest, DeregisterTableResponse,
DescribeNamespaceRequest, DescribeNamespaceResponse, DescribeTableRequest,
DescribeTableResponse, DropNamespaceRequest, DropNamespaceResponse, DropTableRequest,
DropTableResponse, ListNamespacesRequest, ListNamespacesResponse, ListTablesRequest,
ListTablesResponse, NamespaceExistsRequest, RegisterTableRequest, RegisterTableResponse,
TableExistsRequest,
};
use lance_namespace::schema::arrow_schema_to_json;
use lance_table::feature_flags::apply_feature_flags;
use lance_table::format::{Fragment, IndexMetadata, Manifest};
use lance_table::io::commit::{
CommitError, CommitHandler, commit_handler_from_url, write_manifest_file_to_path,
};
use object_store::{Error as ObjectStoreError, path::Path};
use roaring::RoaringBitmap;
use std::io::Cursor;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{
collections::{BTreeMap, HashMap, HashSet},
hash::{DefaultHasher, Hash, Hasher},
ops::{Deref, DerefMut},
sync::{Arc, LazyLock, Mutex as StdMutex, MutexGuard as StdMutexGuard},
};
use tokio::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use uuid::Uuid;
const MANIFEST_TABLE_NAME: &str = "__manifest";
const LANCE_DATA_DIR: &str = "data";
const LANCE_INDICES_DIR: &str = "_indices";
const DELIMITER: &str = "$";
/// Bounded concurrency for per-table `_versions/` probes when filtering declared tables.
/// Higher values reduce latency but increase burst load against the object store.
pub(crate) const DECLARED_FILTER_CONCURRENCY: usize = 16;
// Index names for the __manifest table
/// BTREE index on the object_id column for fast lookups
const OBJECT_ID_INDEX_NAME: &str = "object_id_btree";
/// Bitmap index on the object_type column for filtering by type
const OBJECT_TYPE_INDEX_NAME: &str = "object_type_bitmap";
/// LabelList index on the base_objects column for view dependencies
const BASE_OBJECTS_INDEX_NAME: &str = "base_objects_label_list";
/// Value field of the base_objects index, whose nested `List` type would
/// otherwise allocate an inner field per use.
static BASE_OBJECTS_VALUE_FIELD: LazyLock<Field> = LazyLock::new(|| {
Field::new(
VALUE_COLUMN_NAME,
DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
)
});
// Each retry reloads and rewrites the full manifest. Match the regular Lance
// commit retry budget so multi-process namespace writes can make progress.
const DEFAULT_MANIFEST_REWRITE_COMMIT_RETRIES: u32 = 20;
const MANIFEST_INDEX_BATCH_SIZE: usize = 8192;
/// Object types that can be stored in the manifest
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObjectType {
Namespace,
Table,
}
impl ObjectType {
pub fn as_str(&self) -> &'static str {
match self {
Self::Namespace => "namespace",
Self::Table => "table",
}
}
pub fn parse(s: &str) -> Result<Self> {
match s {
"namespace" => Ok(Self::Namespace),
"table" => Ok(Self::Table),
_ => Err(NamespaceError::Internal {
message: format!("Invalid object type: {}", s),
}
.into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CreateTableMode {
Create,
ExistOk,
Overwrite,
}
impl CreateTableMode {
fn parse(mode: Option<&str>) -> Result<Self> {
match mode {
None => Ok(Self::Create),
Some(mode) if mode.eq_ignore_ascii_case("create") => Ok(Self::Create),
Some(mode)
if mode.eq_ignore_ascii_case("existok")
|| mode.eq_ignore_ascii_case("exist_ok") =>
{
Ok(Self::ExistOk)
}
Some(mode) if mode.eq_ignore_ascii_case("overwrite") => Ok(Self::Overwrite),
Some(mode) => Err(NamespaceError::InvalidInput {
message: format!(
"Unsupported create_table mode '{}'. Supported modes are: 'Create', 'ExistOk', 'Overwrite'",
mode
),
}
.into()),
}
}
fn write_mode(self) -> WriteMode {
match self {
Self::Overwrite => WriteMode::Overwrite,
Self::Create | Self::ExistOk => WriteMode::Create,
}
}
}
/// Information about a table stored in the manifest
#[derive(Debug, Clone)]
pub struct TableInfo {
pub namespace: Vec<String>,
pub name: String,
pub location: String,
pub metadata: Option<HashMap<String, String>>,
}
/// An entry to be inserted into the manifest table.
///
/// This struct makes the meaning of each field explicit, replacing the
/// previous tuple-based API `(String, ObjectType, Option<String>, Option<String>)`.
#[derive(Debug, Clone)]
pub struct ManifestEntry {
/// The unique object identifier (e.g., table name or version object_id)
pub object_id: String,
/// The type of the object (Namespace or Table)
pub object_type: ObjectType,
/// The storage location (e.g., directory name for tables)
pub location: Option<String>,
/// Additional metadata serialized as JSON
pub metadata: Option<String>,
}
struct CopyOnWriteMutation<T> {
result: T,
has_changes: bool,
}
impl<T> CopyOnWriteMutation<T> {
fn updated(result: T) -> Self {
Self {
result,
has_changes: true,
}
}
fn unchanged(result: T) -> Self {
Self {
result,
has_changes: false,
}
}
}
struct ManifestIndexBuildInput {
index_name: &'static str,
column_name: &'static str,
params: ScalarIndexParams,
field: Field,
stream: SendableRecordBatchStream,
}
struct ManifestTrainedIndex {
index_name: &'static str,
column_name: &'static str,
uuid: Uuid,
created_index: CreatedIndex,
}
struct ManifestRowValue {
object_id: String,
object_type: ObjectType,
location: Option<String>,
metadata: Option<String>,
base_objects: Option<Vec<String>>,
}
struct ManifestOutputRow<'a> {
object_id: &'a str,
object_type: ObjectType,
location: Option<&'a str>,
metadata: Option<&'a str>,
base_objects: Option<&'a [String]>,
}
#[derive(Default)]
struct ManifestIndexAccumulator {
object_ids: BTreeMap<Arc<str>, u64>,
object_types: BTreeMap<&'static str, RoaringBitmap>,
base_objects_values: Vec<Option<Vec<String>>>,
base_objects_row_ids: Vec<u64>,
row_count: u64,
}
impl ManifestIndexAccumulator {
fn next_row_id(&self) -> Result<u64> {
if self.row_count >= u64::from(u32::MAX) {
return Err(NamespaceError::Internal {
message: format!(
"Manifest rewrite exceeded maximum single-fragment row count: {}",
self.row_count
),
}
.into());
}
Ok(self.row_count)
}
fn push(&mut self, row: &ManifestOutputRow<'_>) -> Result<u64> {
let row_id = self.next_row_id()?;
if self
.object_ids
.insert(Arc::<str>::from(row.object_id), row_id)
.is_some()
{
return Err(NamespaceError::Internal {
message: format!("Manifest contains duplicate object_id '{}'", row.object_id),
}
.into());
}
self.object_types
.entry(row.object_type.as_str())
.or_default()
.insert(row_id as u32);
self.base_objects_values
.push(row.base_objects.map(|objects| objects.to_vec()));
self.base_objects_row_ids.push(row_id);
self.row_count += 1;
Ok(row_id)
}
}
struct ManifestBatchBuilder {
object_ids: Vec<String>,
object_types: Vec<&'static str>,
locations: Vec<Option<String>>,
metadatas: Vec<Option<String>>,
base_objects: Vec<Option<Vec<String>>>,
}
impl ManifestBatchBuilder {
fn new() -> Self {
Self {
object_ids: Vec::new(),
object_types: Vec::new(),
locations: Vec::new(),
metadatas: Vec::new(),
base_objects: Vec::new(),
}
}
fn is_empty(&self) -> bool {
self.object_ids.is_empty()
}
fn append(
&mut self,
index_data: &mut ManifestIndexAccumulator,
row: ManifestOutputRow<'_>,
) -> Result<()> {
index_data.push(&row)?;
self.object_ids.push(row.object_id.to_string());
self.object_types.push(row.object_type.as_str());
self.locations.push(row.location.map(ToString::to_string));
self.metadatas.push(row.metadata.map(ToString::to_string));
self.base_objects
.push(row.base_objects.map(|objects| objects.to_vec()));
Ok(())
}
fn finish(self) -> Result<RecordBatch> {
let base_objects_array = ManifestNamespace::base_objects_array(&self.base_objects);
RecordBatch::try_new(
ManifestNamespace::manifest_schema(),
vec![
Arc::new(StringArray::from(self.object_ids)),
Arc::new(StringArray::from(self.object_types)),
Arc::new(StringArray::from(self.locations)),
Arc::new(StringArray::from(self.metadatas)),
Arc::new(base_objects_array),
],
)
.map_err(|e| {
lance_core::Error::from(NamespaceError::Internal {
message: format!("Failed to create manifest snapshot batch: {:?}", e),
})
})
}
}
/// How to resolve a storage commit conflict (or an ambiguous commit error that did
/// not land) against the latest catalog state, without re-staging the full rewrite.
enum ConflictResolution<O> {
/// Re-read the latest manifest and re-apply the mutation (upserts, version-range
/// deletes). The staged data/index files are discarded and a new rewrite is attempted.
Retry,
/// Creating these object ids with fail-on-conflict semantics. If any of them now
/// exists in the latest manifest, the create lost the race and must fail with a
/// concurrent-modification error; otherwise retry the rewrite.
FailIfExists(Vec<String>),
/// Deleting `object_id`. If it is already absent from the latest manifest the delete
/// has effectively happened, so return `output` as success; otherwise retry.
SucceedIfAbsent { object_id: String, output: O },
}
trait ManifestStreamMutation: Send {
type Output: Clone + Send + 'static;
fn process_existing_row(
&mut self,
row: ManifestRowValue,
output: &mut ManifestBatchBuilder,
index_data: &mut ManifestIndexAccumulator,
) -> Result<()>;
fn append_rows(
&mut self,
output: &mut ManifestBatchBuilder,
index_data: &mut ManifestIndexAccumulator,
) -> Result<()>;
fn finish(&self) -> CopyOnWriteMutation<Self::Output>;
/// Declares how a storage commit conflict should be resolved against the latest
/// committed catalog state. Defaults to re-reading and re-applying.
fn conflict_resolution(&self) -> ConflictResolution<Self::Output> {
ConflictResolution::Retry
}
}
struct ManifestRewriteShared<M: ManifestStreamMutation> {
mutation: M,
index_data: Option<ManifestIndexAccumulator>,
result: Option<CopyOnWriteMutation<M::Output>>,
error: Option<LanceError>,
}
impl<M: ManifestStreamMutation> ManifestRewriteShared<M> {
fn new(mutation: M) -> Self {
Self {
mutation,
index_data: Some(ManifestIndexAccumulator::default()),
result: None,
error: None,
}
}
}
struct UpsertManifestMutation {
entries: Vec<ManifestEntry>,
base_objects: Vec<Option<Vec<String>>>,
entry_positions: HashMap<String, usize>,
matched: Vec<bool>,
when_matched: WhenMatched,
}
impl UpsertManifestMutation {
fn new(
entries: Vec<ManifestEntry>,
base_objects: Option<Vec<String>>,
when_matched: WhenMatched,
) -> Self {
let entry_positions = entries
.iter()
.enumerate()
.map(|(index, entry)| (entry.object_id.clone(), index))
.collect();
let matched = vec![false; entries.len()];
let mut entry_base_objects = vec![None; entries.len()];
if !entry_base_objects.is_empty() {
entry_base_objects[0] = base_objects;
}
Self {
entries,
base_objects: entry_base_objects,
entry_positions,
matched,
when_matched,
}
}
fn entry_row(&self, index: usize) -> ManifestOutputRow<'_> {
let entry = &self.entries[index];
ManifestOutputRow {
object_id: &entry.object_id,
object_type: entry.object_type,
location: entry.location.as_deref(),
metadata: entry.metadata.as_deref(),
base_objects: self.base_objects[index].as_deref(),
}
}
}
impl ManifestStreamMutation for UpsertManifestMutation {
type Output = ();
fn process_existing_row(
&mut self,
row: ManifestRowValue,
output: &mut ManifestBatchBuilder,
index_data: &mut ManifestIndexAccumulator,
) -> Result<()> {
if let Some(index) = self.entry_positions.get(&row.object_id).copied() {
match self.when_matched {
WhenMatched::Fail => {
return Err(NamespaceError::ConcurrentModification {
message: format!(
"Object '{}' was concurrently created by another operation",
row.object_id
),
}
.into());
}
WhenMatched::UpdateAll => {
self.matched[index] = true;
output.append(index_data, self.entry_row(index))?;
return Ok(());
}
_ => {
return Err(NamespaceError::Internal {
message: format!(
"Unsupported manifest rewrite matched action: {:?}",
self.when_matched
),
}
.into());
}
}
}
output.append(
index_data,
ManifestOutputRow {
object_id: &row.object_id,
object_type: row.object_type,
location: row.location.as_deref(),
metadata: row.metadata.as_deref(),
base_objects: row.base_objects.as_deref(),
},
)
}
fn append_rows(
&mut self,
output: &mut ManifestBatchBuilder,
index_data: &mut ManifestIndexAccumulator,
) -> Result<()> {
for index in 0..self.entries.len() {
if !self.matched[index] {
output.append(index_data, self.entry_row(index))?;
}
}
Ok(())
}
fn finish(&self) -> CopyOnWriteMutation<Self::Output> {
CopyOnWriteMutation::updated(())
}
fn conflict_resolution(&self) -> ConflictResolution<Self::Output> {
match self.when_matched {
// Fail-on-conflict create: a concurrent writer may have created one of these
// ids. Re-applying would still fail, so check directly instead of re-staging.
WhenMatched::Fail => ConflictResolution::FailIfExists(
self.entries.iter().map(|e| e.object_id.clone()).collect(),
),
// Metadata upsert is last-writer-wins: re-read and re-apply.
_ => ConflictResolution::Retry,
}
}
}
struct DeleteObjectMutation {
object_id: String,
deleted: bool,
}
impl ManifestStreamMutation for DeleteObjectMutation {
type Output = ();
fn process_existing_row(
&mut self,
row: ManifestRowValue,
output: &mut ManifestBatchBuilder,
index_data: &mut ManifestIndexAccumulator,
) -> Result<()> {
if row.object_id == self.object_id {
self.deleted = true;
return Ok(());
}
output.append(
index_data,
ManifestOutputRow {
object_id: &row.object_id,
object_type: row.object_type,
location: row.location.as_deref(),
metadata: row.metadata.as_deref(),
base_objects: row.base_objects.as_deref(),
},
)
}
fn append_rows(
&mut self,
_output: &mut ManifestBatchBuilder,
_index_data: &mut ManifestIndexAccumulator,
) -> Result<()> {
Ok(())
}
fn finish(&self) -> CopyOnWriteMutation<Self::Output> {
if self.deleted {
CopyOnWriteMutation::updated(())
} else {
CopyOnWriteMutation::unchanged(())
}
}
fn conflict_resolution(&self) -> ConflictResolution<Self::Output> {
// If a concurrent writer already removed the object, the delete is satisfied.
ConflictResolution::SucceedIfAbsent {
object_id: self.object_id.clone(),
output: (),
}
}
}
/// Information about a namespace stored in the manifest
#[derive(Debug, Clone)]
pub struct NamespaceInfo {
pub namespace: Vec<String>,
pub name: String,
pub metadata: Option<HashMap<String, String>>,
}
/// A wrapper around a Dataset that provides concurrent access.
///
/// This can be cloned cheaply. It supports concurrent reads or exclusive writes.
/// The manifest dataset uses contiguous attached versions and this module never
/// runs old-version cleanup on it, allowing reads to check only the immediate
/// successor manifest before deciding whether a reload is needed.
#[derive(Debug, Clone)]
pub struct DatasetConsistencyWrapper(Arc<RwLock<Dataset>>);
impl DatasetConsistencyWrapper {
/// Create a new wrapper with the given dataset.
pub fn new(dataset: Dataset) -> Self {
debug_assert!(
!dataset
.manifest()
.config
.keys()
.any(|key| key.starts_with("lance.auto_cleanup.")),
"the directory manifest dataset must not enable old-version cleanup"
);
Self(Arc::new(RwLock::new(dataset)))
}
/// Get an immutable reference to the dataset.
/// Always reloads to ensure strong consistency.
pub async fn get(&self) -> Result<DatasetReadGuard<'_>> {
self.reload().await?;
let guard = DatasetReadGuard {
guard: self.0.read().await,
};
// Refuse manifests written with a reader feature flag this build does
// not understand instead of misreading them.
ensure_readable(guard.metadata())?;
Ok(guard)
}
/// Reload the dataset and return a reference.
pub async fn get_refreshed(&self) -> Result<DatasetReadGuard<'_>> {
self.reload().await?;
let guard = DatasetReadGuard {
guard: self.0.read().await,
};
ensure_readable(guard.metadata())?;
Ok(guard)
}
/// Get a mutable reference to the dataset.
/// Always reloads to ensure strong consistency.
pub async fn get_mut(&self) -> Result<DatasetWriteGuard<'_>> {
self.reload().await?;
let guard = DatasetWriteGuard {
guard: self.0.write().await,
};
ensure_readable(guard.metadata())?;
ensure_writable(guard.metadata())?;
Ok(guard)
}
/// Provide a known latest version of the dataset.
///
/// This is usually done after some write operation, which inherently will
/// have the latest version.
pub async fn set_latest(&self, dataset: Dataset) {
let mut write_guard = self.0.write().await;
if dataset.manifest().version > write_guard.manifest().version {
*write_guard = dataset;
}
}
/// Reload the dataset to the latest version.
async fn reload(&self) -> Result<()> {
// First check if we need to reload (with read lock)
let read_guard = self.0.read().await;
let dataset_uri = read_guard.uri().to_string();
let current_version = read_guard.version().version;
log::debug!(
"Reload starting for uri={}, current_version={}",
dataset_uri,
current_version
);
// The directory manifest table uses contiguous attached versions and
// does not run old-version cleanup, so the immediate successor probe is
// enough to detect changes without resolving or loading the latest
// manifest on every namespace read.
let has_successor_version = read_guard.has_successor_version().await.map_err(|e| {
lance_core::Error::from(NamespaceError::Internal {
message: format!("Failed to check dataset staleness: {:?}", e),
})
})?;
log::debug!(
"Reload checked successor_version_exists={} for uri={}, current_version={}",
has_successor_version,
dataset_uri,
current_version
);
drop(read_guard);
// If already up-to-date, return early
if !has_successor_version {
log::debug!("Already up-to-date for uri={}", dataset_uri);
return Ok(());
}
// Need to reload, acquire write lock
let mut write_guard = self.0.write().await;
// Double-check after acquiring write lock (someone else might have reloaded)
let has_successor_version = write_guard.has_successor_version().await.map_err(|e| {
lance_core::Error::from(NamespaceError::Internal {
message: format!("Failed to check dataset staleness: {:?}", e),
})
})?;
if has_successor_version {
write_guard.checkout_latest().await.map_err(|e| {
lance_core::Error::from(NamespaceError::Internal {
message: format!("Failed to checkout latest: {:?}", e),
})
})?;
}
Ok(())
}
}
pub struct DatasetReadGuard<'a> {
guard: RwLockReadGuard<'a, Dataset>,
}
impl Deref for DatasetReadGuard<'_> {
type Target = Dataset;
fn deref(&self) -> &Self::Target {
&self.guard
}
}
pub struct DatasetWriteGuard<'a> {
guard: RwLockWriteGuard<'a, Dataset>,
}
impl Deref for DatasetWriteGuard<'_> {
type Target = Dataset;
fn deref(&self) -> &Self::Target {
&self.guard
}
}
impl DerefMut for DatasetWriteGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.guard
}
}
/// Manifest-based namespace implementation
///
/// Uses a special `__manifest` Lance table to track tables and nested namespaces.
pub struct ManifestNamespace {
root: String,
storage_options: Option<HashMap<String, String>>,
session: Option<Arc<Session>>,
object_store: Arc<ObjectStore>,
base_path: Path,
manifest_dataset: DatasetConsistencyWrapper,
/// Whether directory listing is enabled in dual mode
/// If true, root namespace tables use {table_name}.lance naming
/// If false, they use namespace-prefixed names
dir_listing_enabled: bool,
/// Whether copy-on-write manifest rewrites should build replacement indices.
/// Defaults to true.
inline_optimization_enabled: bool,
/// Number of retries for commit operations on the manifest table.
/// If None, defaults to [`lance_table::io::commit::CommitConfig`] default (20).
commit_retries: Option<u32>,
/// Serialize manifest mutations within a single namespace instance so concurrent
/// create/drop calls do not compete with each other on the same in-memory snapshot.
manifest_mutation_lock: Arc<Mutex<()>>,
}
impl std::fmt::Debug for ManifestNamespace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ManifestNamespace")
.field("root", &self.root)
.field("storage_options", &self.storage_options)
.field("dir_listing_enabled", &self.dir_listing_enabled)
.field(
"inline_optimization_enabled",
&self.inline_optimization_enabled,
)
.finish()
}
}
/// Convert a Lance commit error to an appropriate namespace error.
///
/// Maps lance commit errors to namespace errors:
/// - `CommitConflict`: version collision retries exhausted -> Throttling (safe to retry)
/// - `TooMuchWriteContention`: RetryableCommitConflict (semantic conflict) retries exhausted -> ConcurrentModification
/// - `IncompatibleTransaction`: incompatible concurrent change -> ConcurrentModification
/// - Errors containing "matched/duplicate/already exists": ConcurrentModification (from WhenMatched::Fail)
/// - Other errors: IO error with the operation description
fn convert_lance_commit_error(e: &LanceError, operation: &str, object_id: Option<&str>) -> Error {
match e {
// CommitConflict: version collision retries exhausted -> Throttling (safe to retry)
LanceError::CommitConflict { .. } => NamespaceError::Throttling {
message: format!("Too many concurrent writes, please retry later: {:?}", e),
}
.into(),
// TooMuchWriteContention: RetryableCommitConflict (semantic conflict) retries exhausted -> ConcurrentModification
// IncompatibleTransaction: incompatible concurrent change -> ConcurrentModification
LanceError::TooMuchWriteContention { .. } | LanceError::IncompatibleTransaction { .. } => {
let message = if let Some(id) = object_id {
format!(
"Object '{}' was concurrently modified by another operation: {:?}",
id, e
)
} else {
format!(
"Object was concurrently modified by another operation: {:?}",
e
)
};
NamespaceError::ConcurrentModification { message }.into()
}
// Other errors: check message for semantic conflicts (matched/duplicate from WhenMatched::Fail)
_ => {
let error_msg = e.to_string();
if error_msg.contains("matched")
|| error_msg.contains("duplicate")
|| error_msg.contains("already exists")
{
let message = if let Some(id) = object_id {
format!(
"Object '{}' was concurrently created by another operation: {:?}",
id, e
)
} else {
format!(
"Object was concurrently created by another operation: {:?}",
e
)
};
return NamespaceError::ConcurrentModification { message }.into();
}
lance_core::Error::from(NamespaceError::Internal {
message: format!("{}: {:?}", operation, e),
})
}
}
}
impl ManifestNamespace {
/// Create a new ManifestNamespace from an existing DirectoryNamespace
#[allow(clippy::too_many_arguments)]
pub async fn from_directory(
root: String,
storage_options: Option<HashMap<String, String>>,
session: Option<Arc<Session>>,
object_store: Arc<ObjectStore>,
base_path: Path,
dir_listing_enabled: bool,
inline_optimization_enabled: bool,
commit_retries: Option<u32>,
) -> Result<Self> {
let manifest_dataset =
Self::ensure_manifest_table_up_to_date(&root, &storage_options, session.clone())
.await?;
Ok(Self::new(
root,
storage_options,
session,
object_store,
base_path,
manifest_dataset,
dir_listing_enabled,
inline_optimization_enabled,
commit_retries,
))
}
/// Open an existing manifest dataset without creating or migrating it.
#[allow(clippy::too_many_arguments)]
pub async fn open_from_directory(
root: String,
storage_options: Option<HashMap<String, String>>,
session: Option<Arc<Session>>,
object_store: Arc<ObjectStore>,
base_path: Path,
dir_listing_enabled: bool,
inline_optimization_enabled: bool,
commit_retries: Option<u32>,
) -> Result<Self> {
let manifest_dataset =
Self::open_manifest_table(&root, &storage_options, session.clone()).await?;
Ok(Self::new(
root,
storage_options,
session,
object_store,
base_path,
manifest_dataset,
dir_listing_enabled,
inline_optimization_enabled,
commit_retries,
))
}
#[allow(clippy::too_many_arguments)]
fn new(
root: String,
storage_options: Option<HashMap<String, String>>,
session: Option<Arc<Session>>,
object_store: Arc<ObjectStore>,
base_path: Path,
manifest_dataset: DatasetConsistencyWrapper,
dir_listing_enabled: bool,
inline_optimization_enabled: bool,
commit_retries: Option<u32>,
) -> Self {
Self {
root,
storage_options,
session,
object_store,
base_path,
manifest_dataset,
dir_listing_enabled,
inline_optimization_enabled,
commit_retries,
manifest_mutation_lock: Arc::new(Mutex::new(())),
}
}
/// Build object ID from namespace path and name
pub fn build_object_id(namespace: &[String], name: &str) -> String {
if namespace.is_empty() {
name.to_string()
} else {
let mut id = namespace.join(DELIMITER);
id.push_str(DELIMITER);
id.push_str(name);
id
}
}
/// Parse object ID into namespace path and name
pub fn parse_object_id(object_id: &str) -> (Vec<String>, String) {
let parts: Vec<&str> = object_id.split(DELIMITER).collect();
if parts.len() == 1 {
(Vec::new(), parts[0].to_string())
} else {
let namespace = parts[..parts.len() - 1]
.iter()
.map(|s| s.to_string())
.collect();
let name = parts[parts.len() - 1].to_string();
(namespace, name)
}
}
/// Split an object ID (vec of strings) into namespace and table name
pub fn split_object_id(object_id: &[String]) -> (Vec<String>, String) {
if object_id.len() == 1 {
(vec![], object_id[0].clone())
} else {
(
object_id[..object_id.len() - 1].to_vec(),
object_id[object_id.len() - 1].clone(),
)
}
}
/// Convert an ID (vec of strings) to an object_id string
pub fn str_object_id(object_id: &[String]) -> String {
object_id.join(DELIMITER)
}
fn format_table_id(table_id: &[String]) -> String {
format!("table id '{}'", Self::str_object_id(table_id))
}
/// Generate a new directory name in format: `<hash>_<object_id>`
/// The hash is used to (1) optimize object store throughput,
/// (2) have high enough entropy in a short period of time to prevent issues like
/// failed table creation, delete and create new table of the same name, etc.
/// The object_id is added after the hash to ensure
/// dir name uniqueness and make debugging easier.
pub fn generate_dir_name(object_id: &str) -> String {
// Generate a random number for uniqueness
let random_num: u64 = rand::random();
// Create hash from random number + object_id
let mut hasher = DefaultHasher::new();
random_num.hash(&mut hasher);
object_id.hash(&mut hasher);
let hash = hasher.finish();
// Format as lowercase hex (8 characters - sufficient entropy for uniqueness)
format!("{:08x}_{}", (hash & 0xFFFFFFFF) as u32, object_id)
}