lancedb 0.27.2

LanceDB: A serverless, low-latency vector database for AI applications
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors

//! DataFusion ExecutionPlan for inserting data into LanceDB tables.

use std::any::Any;
use std::sync::{Arc, LazyLock, Mutex};

use arrow_array::{RecordBatch, UInt64Array};
use arrow_schema::{DataType, Field, Schema as ArrowSchema, SchemaRef};
use datafusion_common::{DataFusionError, Result as DataFusionResult};
use datafusion_execution::{SendableRecordBatchStream, TaskContext};
use datafusion_physical_expr::{EquivalenceProperties, Partitioning};
use datafusion_physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion_physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use datafusion_physical_plan::{
    DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
};
use futures::TryStreamExt;
use lance::Dataset;
use lance::dataset::transaction::{Operation, Transaction};
use lance::dataset::{CommitBuilder, InsertBuilder, WriteParams};
use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter;
use lance_table::format::Fragment;

use crate::table::dataset::DatasetConsistencyWrapper;

pub(crate) static COUNT_SCHEMA: LazyLock<SchemaRef> = LazyLock::new(|| {
    Arc::new(ArrowSchema::new(vec![Field::new(
        "count",
        DataType::UInt64,
        false,
    )]))
});

fn operation_fragments(operation: &Operation) -> &[Fragment] {
    match operation {
        Operation::Append { fragments } => fragments,
        Operation::Overwrite { fragments, .. } => fragments,
        _ => &[],
    }
}

fn count_rows_from_operation(operation: &Operation) -> u64 {
    operation_fragments(operation)
        .iter()
        .map(|f| f.num_rows().unwrap_or(0) as u64)
        .sum()
}

fn operation_fragments_mut(operation: &mut Operation) -> &mut Vec<Fragment> {
    match operation {
        Operation::Append { fragments } => fragments,
        Operation::Overwrite { fragments, .. } => fragments,
        _ => panic!("Unsupported operation type for getting mutable fragments"),
    }
}

fn merge_transactions(mut transactions: Vec<Transaction>) -> Option<Transaction> {
    let mut first = transactions.pop()?;

    for txn in transactions {
        let first_fragments = operation_fragments_mut(&mut first.operation);
        let txn_fragments = operation_fragments(&txn.operation);
        first_fragments.extend_from_slice(txn_fragments);
    }

    Some(first)
}

/// ExecutionPlan for inserting data into a native LanceDB table.
///
/// This plan executes inserts by:
/// 1. Each partition writes data independently using InsertBuilder::execute_uncommitted_stream
/// 2. The last partition to complete commits all transactions atomically
/// 3. Returns the count of inserted rows per partition
#[derive(Debug)]
pub struct InsertExec {
    ds_wrapper: DatasetConsistencyWrapper,
    dataset: Arc<Dataset>,
    input: Arc<dyn ExecutionPlan>,
    write_params: WriteParams,
    properties: PlanProperties,
    partial_transactions: Arc<Mutex<Vec<Transaction>>>,
    metrics: ExecutionPlanMetricsSet,
}

impl InsertExec {
    pub fn new(
        ds_wrapper: DatasetConsistencyWrapper,
        dataset: Arc<Dataset>,
        input: Arc<dyn ExecutionPlan>,
        write_params: WriteParams,
    ) -> Self {
        let schema = COUNT_SCHEMA.clone();
        let num_partitions = input.output_partitioning().partition_count();
        let properties = PlanProperties::new(
            EquivalenceProperties::new(schema),
            Partitioning::UnknownPartitioning(num_partitions),
            EmissionType::Final,
            Boundedness::Bounded,
        );

        Self {
            ds_wrapper,
            dataset,
            input,
            write_params,
            properties,
            partial_transactions: Arc::new(Mutex::new(Vec::with_capacity(num_partitions))),
            metrics: ExecutionPlanMetricsSet::new(),
        }
    }
}

impl DisplayAs for InsertExec {
    fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match t {
            DisplayFormatType::Default | DisplayFormatType::Verbose => {
                write!(f, "InsertExec: mode={:?}", self.write_params.mode)
            }
            DisplayFormatType::TreeRender => {
                write!(f, "InsertExec")
            }
        }
    }
}

impl ExecutionPlan for InsertExec {
    fn name(&self) -> &str {
        Self::static_name()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn properties(&self) -> &PlanProperties {
        &self.properties
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.input]
    }

    fn maintains_input_order(&self) -> Vec<bool> {
        vec![false]
    }

    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
        vec![false]
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
        if children.len() != 1 {
            return Err(DataFusionError::Internal(
                "InsertExec requires exactly one child".to_string(),
            ));
        }
        Ok(Arc::new(Self::new(
            self.ds_wrapper.clone(),
            self.dataset.clone(),
            children[0].clone(),
            self.write_params.clone(),
        )))
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> DataFusionResult<SendableRecordBatchStream> {
        let input_stream = self.input.execute(partition, context)?;
        let dataset = self.dataset.clone();
        let write_params = self.write_params.clone();
        let partial_transactions = self.partial_transactions.clone();
        let total_partitions = self.input.output_partitioning().partition_count();
        let ds_wrapper = self.ds_wrapper.clone();

        let output_bytes = MetricBuilder::new(&self.metrics).output_bytes(partition);
        let input_schema = input_stream.schema();
        let input_stream: SendableRecordBatchStream =
            Box::pin(InstrumentedRecordBatchStreamAdapter::new(
                input_schema,
                input_stream.map_ok(move |batch| {
                    output_bytes.add(batch.get_array_memory_size());
                    batch
                }),
                partition,
                &self.metrics,
            ));

        let stream = futures::stream::once(async move {
            let transaction = InsertBuilder::new(dataset.clone())
                .with_params(&write_params)
                .execute_uncommitted_stream(input_stream)
                .await?;

            let num_rows = count_rows_from_operation(&transaction.operation);

            let to_commit = {
                // Don't hold the lock over an await point.
                let mut txns = partial_transactions
                    .lock()
                    .unwrap_or_else(|e| e.into_inner());
                txns.push(transaction);
                if txns.len() == total_partitions {
                    Some(std::mem::take(&mut *txns))
                } else {
                    None
                }
            };

            if let Some(transactions) = to_commit
                && let Some(merged_txn) = merge_transactions(transactions)
            {
                let new_dataset = CommitBuilder::new(dataset.clone())
                    .execute(merged_txn)
                    .await?;
                ds_wrapper.update(new_dataset);
            }

            Ok(RecordBatch::try_new(
                COUNT_SCHEMA.clone(),
                vec![Arc::new(UInt64Array::from(vec![num_rows]))],
            )?)
        });

        Ok(Box::pin(RecordBatchStreamAdapter::new(
            COUNT_SCHEMA.clone(),
            stream,
        )))
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner())
    }
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;
    use arrow_array::{RecordBatchIterator, record_batch};
    use datafusion::prelude::SessionContext;
    use datafusion_catalog::MemTable;
    use tempfile::tempdir;

    use crate::connect;

    #[tokio::test]
    async fn test_insert_via_sql() {
        let tmp_dir = tempdir().unwrap();
        let uri = tmp_dir.path().to_str().unwrap();

        let db = connect(uri).execute().await.unwrap();

        // Create initial table
        let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap();
        let table = db
            .create_table("test_insert", batch)
            .execute()
            .await
            .unwrap();

        // Verify initial count
        assert_eq!(table.count_rows(None).await.unwrap(), 3);

        let ctx = SessionContext::new();
        let provider =
            crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone())
                .await
                .unwrap();
        ctx.register_table("test_insert", Arc::new(provider))
            .unwrap();

        ctx.sql("INSERT INTO test_insert VALUES (4), (5), (6)")
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();

        // Verify final count
        table.checkout_latest().await.unwrap();
        assert_eq!(table.count_rows(None).await.unwrap(), 6);
    }

    #[tokio::test]
    async fn test_insert_overwrite_via_sql() {
        let tmp_dir = tempdir().unwrap();
        let uri = tmp_dir.path().to_str().unwrap();

        let db = connect(uri).execute().await.unwrap();

        // Create initial table with 3 rows
        let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap();
        let table = db
            .create_table("test_overwrite", batch)
            .execute()
            .await
            .unwrap();

        assert_eq!(table.count_rows(None).await.unwrap(), 3);

        let ctx = SessionContext::new();
        let provider =
            crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone())
                .await
                .unwrap();
        ctx.register_table("test_overwrite", Arc::new(provider))
            .unwrap();

        ctx.sql("INSERT OVERWRITE INTO test_overwrite VALUES (10), (20)")
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();

        // Verify: should have 2 rows (overwritten, not appended)
        table.checkout_latest().await.unwrap();
        assert_eq!(table.count_rows(None).await.unwrap(), 2);
    }

    #[tokio::test]
    async fn test_insert_empty_batch() {
        let tmp_dir = tempdir().unwrap();
        let uri = tmp_dir.path().to_str().unwrap();

        let db = connect(uri).execute().await.unwrap();

        // Create initial table
        let batch = record_batch!(("id", Int32, [1, 2, 3])).unwrap();
        let table = db
            .create_table("test_empty", batch)
            .execute()
            .await
            .unwrap();

        assert_eq!(table.count_rows(None).await.unwrap(), 3);

        let ctx = SessionContext::new();
        let provider =
            crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone())
                .await
                .unwrap();
        ctx.register_table("test_empty", Arc::new(provider))
            .unwrap();

        let source_schema = Arc::new(ArrowSchema::new(vec![Field::new(
            "id",
            DataType::Int32,
            false,
        )]));
        // Empty batches
        let source_reader: Box<dyn arrow_array::RecordBatchReader + Send> =
            Box::new(RecordBatchIterator::new(
                std::iter::empty::<Result<RecordBatch, arrow_schema::ArrowError>>(),
                source_schema,
            ));
        let source_table = db
            .create_table("empty_source", source_reader)
            .execute()
            .await
            .unwrap();
        let source_provider =
            crate::table::datafusion::BaseTableAdapter::try_new(source_table.base_table().clone())
                .await
                .unwrap();
        ctx.register_table("empty_source", Arc::new(source_provider))
            .unwrap();

        // Execute INSERT with empty source
        ctx.sql("INSERT INTO test_empty SELECT * FROM empty_source")
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();

        // Verify: should still have 3 rows (nothing inserted)
        table.checkout_latest().await.unwrap();
        assert_eq!(table.count_rows(None).await.unwrap(), 3);
    }

    #[tokio::test]
    async fn test_insert_multiple_batches() {
        let tmp_dir = tempdir().unwrap();
        let uri = tmp_dir.path().to_str().unwrap();

        let db = connect(uri).execute().await.unwrap();

        // Create initial table
        let batch = record_batch!(("id", Int32, [1])).unwrap();
        let schema = batch.schema();
        let table = db
            .create_table("test_multi_batch", batch)
            .execute()
            .await
            .unwrap();

        let ctx = SessionContext::new();
        let provider =
            crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone())
                .await
                .unwrap();
        ctx.register_table("test_multi_batch", Arc::new(provider))
            .unwrap();

        // Memtable with multiple batches and multiple partitions
        let source_table = MemTable::try_new(
            schema.clone(),
            vec![
                // Partition 0
                vec![
                    record_batch!(("id", Int32, [2, 3])).unwrap(),
                    record_batch!(("id", Int32, [4, 5])).unwrap(),
                ],
                // Partition 1
                vec![record_batch!(("id", Int32, [6, 7, 8])).unwrap()],
            ],
        )
        .unwrap();
        ctx.register_table("multi_batch_source", Arc::new(source_table))
            .unwrap();

        ctx.sql("INSERT INTO test_multi_batch SELECT * FROM multi_batch_source")
            .await
            .unwrap()
            .collect()
            .await
            .unwrap();

        // Verify: should have 1 + 2 + 2 + 3 = 8 rows
        table.checkout_latest().await.unwrap();
        assert_eq!(table.count_rows(None).await.unwrap(), 8);
    }
}