indexlake-datafusion 0.6.0

IndexLake datafusion integration
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
use std::collections::HashMap;
use std::sync::Arc;

use arrow::datatypes::SchemaRef;
use datafusion_common::DataFusionError;
use datafusion_execution::TaskContext;
use datafusion_expr::dml::InsertOp;
use datafusion_physical_plan::ExecutionPlan;
use datafusion_proto::logical_plan::DefaultLogicalExtensionCodec;
use datafusion_proto::logical_plan::from_proto::parse_exprs;
use datafusion_proto::logical_plan::to_proto::serialize_exprs;
use datafusion_proto::physical_plan::PhysicalExtensionCodec;
use datafusion_proto::physical_plan::PhysicalProtoConverterExtension;
use datafusion_proto::protobuf::Schema as ProtoSchema;
use indexlake::catalog::{DataFileRecord, RowValidity};
use indexlake::storage::DataFileFormat;
use indexlake::table::TableUpdate;
use prost::Message;
use uuid::Uuid;

use crate::index_lake_physical_plan_node::IndexLakePhysicalPlanType;
use crate::{
    DataFile, ExprColumnAssignment, IndexLakeDeleteExec, IndexLakeDeleteExecNode,
    IndexLakeExprNode, IndexLakeInsertExec, IndexLakeInsertExecNode, IndexLakePhysicalPlanNode,
    IndexLakeScanExec, IndexLakeScanExecNode, IndexLakeSearchExec, IndexLakeSearchExecNode,
    IndexLakeUpdateExec, IndexLakeUpdateExecNode, LazyTable, TableScanPartition,
    TableScanPartitionAuto, TableScanPartitionProvided, table_scan_partition,
};

#[derive(Debug)]
pub struct IndexLakePhysicalCodec {
    client: Arc<indexlake::Client>,
}

impl IndexLakePhysicalCodec {
    pub fn new(client: Arc<indexlake::Client>) -> Self {
        Self { client }
    }
}

impl PhysicalExtensionCodec for IndexLakePhysicalCodec {
    fn try_decode(
        &self,
        buf: &[u8],
        inputs: &[Arc<dyn ExecutionPlan>],
        ctx: &TaskContext,
        _proto_converter: &dyn PhysicalProtoConverterExtension,
    ) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> {
        let indexlake_node = IndexLakePhysicalPlanNode::decode(buf).map_err(|e| {
            DataFusionError::Internal(format!(
                "Failed to decode indexlake physical plan node: {e:?}"
            ))
        })?;
        let indexlake_plan = indexlake_node.index_lake_physical_plan_type.ok_or_else(|| {
            DataFusionError::Internal(
                "Failed to decode indexlake physical plan node due to physical plan type is none".to_string()
            )
        })?;

        match indexlake_plan {
            IndexLakePhysicalPlanType::Scan(node) => {
                let schema = parse_schema(node.schema)?;

                let projection = parse_projection(node.projection.as_ref());
                let filters = parse_exprs(&node.filters, ctx, &DefaultLogicalExtensionCodec {})?;

                let lazy_table =
                    LazyTable::new(self.client.clone(), node.namespace_name, node.table_name);

                let scan_partitions = parse_scan_partitions(&node.partitions)?;
                let partition_row_counts = node
                    .partition_row_counts
                    .iter()
                    .map(|value| *value as usize)
                    .collect::<Vec<_>>();
                let partition_row_counts = Arc::new(partition_row_counts);

                Ok(Arc::new(IndexLakeScanExec::try_new(
                    lazy_table,
                    schema,
                    scan_partitions,
                    partition_row_counts,
                    projection,
                    filters,
                    node.batch_size as usize,
                    node.limit.map(|l| l as usize),
                )?))
            }
            IndexLakePhysicalPlanType::Insert(node) => {
                if inputs.len() != 1 {
                    return Err(DataFusionError::Internal(format!(
                        "IndexLakeInsertExec requires exactly one input, got {}",
                        inputs.len()
                    )));
                }
                let input = inputs[0].clone();

                let insert_op = parse_insert_op(node.insert_op)?;

                let lazy_table =
                    LazyTable::new(self.client.clone(), node.namespace_name, node.table_name);

                Ok(Arc::new(IndexLakeInsertExec::try_new(
                    lazy_table,
                    input,
                    insert_op,
                    node.bypass_insert_threshold as usize,
                )?))
            }
            IndexLakePhysicalPlanType::Search(node) => {
                let schema = parse_schema(node.schema)?;
                let projection = parse_projection(node.projection.as_ref());
                let lazy_table =
                    LazyTable::new(self.client.clone(), node.namespace_name, node.table_name);

                let codec = self
                    .client
                    .index_kinds
                    .get(&node.index_kind)
                    .and_then(|kind| kind.search_query_codec())
                    .ok_or_else(|| {
                        DataFusionError::Internal(format!(
                            "Search query codec not found for index kind: {}",
                            node.index_kind
                        ))
                    })?;
                let query = codec.decode(&node.query_data).map_err(|e| {
                    DataFusionError::Internal(format!("Failed to decode search query: {e}"))
                })?;

                Ok(Arc::new(IndexLakeSearchExec::try_new(
                    lazy_table,
                    schema,
                    query,
                    node.dynamic_fields.clone(),
                    projection,
                    node.limit.map(|l| l as usize),
                )?))
            }
            IndexLakePhysicalPlanType::Update(node) => {
                let condition: indexlake::expr::Expr =
                    deserialize_il_expr(node.condition.as_ref().ok_or_else(|| {
                        DataFusionError::Internal("Missing condition in update node".to_string())
                    })?)?;

                let mut set_map = HashMap::new();
                for assignment in &node.assignments {
                    let value: indexlake::expr::Expr =
                        deserialize_il_expr(assignment.value.as_ref().ok_or_else(|| {
                            DataFusionError::Internal(
                                "Missing value in update assignment".to_string(),
                            )
                        })?)?;
                    set_map.insert(assignment.column.clone(), value);
                }

                let lazy_table =
                    LazyTable::new(self.client.clone(), node.namespace_name, node.table_name);

                let update = TableUpdate { set_map, condition };
                Ok(Arc::new(IndexLakeUpdateExec::try_new(lazy_table, update)?))
            }
            IndexLakePhysicalPlanType::Delete(node) => {
                let condition: indexlake::expr::Expr =
                    deserialize_il_expr(node.condition.as_ref().ok_or_else(|| {
                        DataFusionError::Internal("Missing condition in delete node".to_string())
                    })?)?;

                let lazy_table =
                    LazyTable::new(self.client.clone(), node.namespace_name, node.table_name);

                Ok(Arc::new(IndexLakeDeleteExec::try_new(
                    lazy_table, condition,
                )?))
            }
        }
    }

    fn try_encode(
        &self,
        node: Arc<dyn ExecutionPlan>,
        buf: &mut Vec<u8>,
        _proto_converter: &dyn PhysicalProtoConverterExtension,
    ) -> Result<(), DataFusionError> {
        if let Some(exec) = node.downcast_ref::<IndexLakeScanExec>() {
            let projection = serialize_projection(exec.projection.as_ref());

            let filters = serialize_exprs(&exec.filters, &DefaultLogicalExtensionCodec {})?;

            let schema = serialize_schema(&exec.output_schema)?;

            let partitions = serialize_scan_partitions(exec.scan_partitions());
            let partition_row_counts = exec
                .partition_row_counts()
                .iter()
                .map(|value| *value as u64)
                .collect();

            let proto = IndexLakePhysicalPlanNode {
                index_lake_physical_plan_type: Some(IndexLakePhysicalPlanType::Scan(
                    IndexLakeScanExecNode {
                        namespace_name: exec.lazy_table.namespace_name.clone(),
                        table_name: exec.lazy_table.table_name.clone(),
                        partition_count: exec.partition_count as u32,
                        partitions,
                        projection,
                        filters,
                        batch_size: exec.batch_size as u32,
                        limit: exec.limit.map(|l| l as u32),
                        schema: Some(schema),
                        partition_row_counts,
                    },
                )),
            };

            proto.encode(buf).map_err(|e| {
                DataFusionError::Internal(format!(
                    "Failed to encode indexlake scan execution plan: {e:?}"
                ))
            })?;

            Ok(())
        } else if let Some(exec) = node.downcast_ref::<IndexLakeInsertExec>() {
            let insert_op = serialize_insert_op(exec.insert_op);

            let proto = IndexLakePhysicalPlanNode {
                index_lake_physical_plan_type: Some(IndexLakePhysicalPlanType::Insert(
                    IndexLakeInsertExecNode {
                        namespace_name: exec.lazy_table.namespace_name.clone(),
                        table_name: exec.lazy_table.table_name.clone(),
                        insert_op,
                        bypass_insert_threshold: exec.bypass_insert_threshold as u32,
                    },
                )),
            };

            proto.encode(buf).map_err(|e| {
                DataFusionError::Internal(format!(
                    "Failed to encode indexlake insert execution plan: {e:?}"
                ))
            })?;

            Ok(())
        } else if let Some(exec) = node.downcast_ref::<IndexLakeSearchExec>() {
            let schema = serialize_schema(&exec.output_schema)?;
            let projection = serialize_projection(exec.projection.as_ref());

            let proto = IndexLakePhysicalPlanNode {
                index_lake_physical_plan_type: Some(IndexLakePhysicalPlanType::Search(
                    IndexLakeSearchExecNode {
                        namespace_name: exec.lazy_table.namespace_name.clone(),
                        table_name: exec.lazy_table.table_name.clone(),
                        index_kind: exec.query.index_kind().to_string(),
                        limit: exec.limit.map(|l| l as u32),
                        dynamic_fields: exec.dynamic_fields.clone(),
                        projection,
                        schema: Some(schema),
                        query_data: {
                            let kind = self
                                .client
                                .index_kinds
                                .get(exec.query.index_kind())
                                .ok_or_else(|| {
                                    DataFusionError::Internal(format!(
                                        "Index kind '{}' not found",
                                        exec.query.index_kind()
                                    ))
                                })?;
                            let codec = kind.search_query_codec().ok_or_else(|| {
                                DataFusionError::Internal(format!(
                                    "Search query codec not found for index kind: {}",
                                    exec.query.index_kind()
                                ))
                            })?;
                            codec.encode(exec.query.as_ref()).map_err(|e| {
                                DataFusionError::Internal(format!(
                                    "Failed to encode search query: {e}"
                                ))
                            })?
                        },
                    },
                )),
            };

            proto.encode(buf).map_err(|e| {
                DataFusionError::Internal(format!(
                    "Failed to encode indexlake search execution plan: {e:?}"
                ))
            })?;

            Ok(())
        } else if let Some(exec) = node.downcast_ref::<IndexLakeUpdateExec>() {
            let condition_node = serialize_il_expr(&exec.update.condition)?;

            let assignments = exec
                .update
                .set_map
                .iter()
                .map(|(col, expr)| {
                    let value_node = serialize_il_expr(expr)?;
                    Ok(ExprColumnAssignment {
                        column: col.clone(),
                        value: Some(value_node),
                    })
                })
                .collect::<Result<Vec<_>, DataFusionError>>()?;

            let proto = IndexLakePhysicalPlanNode {
                index_lake_physical_plan_type: Some(IndexLakePhysicalPlanType::Update(
                    IndexLakeUpdateExecNode {
                        namespace_name: exec.lazy_table.namespace_name.clone(),
                        table_name: exec.lazy_table.table_name.clone(),
                        condition: Some(condition_node),
                        assignments,
                    },
                )),
            };

            proto.encode(buf).map_err(|e| {
                DataFusionError::Internal(format!(
                    "Failed to encode indexlake update execution plan: {e:?}"
                ))
            })?;

            Ok(())
        } else if let Some(exec) = node.downcast_ref::<IndexLakeDeleteExec>() {
            let condition_node = serialize_il_expr(&exec.condition)?;

            let proto = IndexLakePhysicalPlanNode {
                index_lake_physical_plan_type: Some(IndexLakePhysicalPlanType::Delete(
                    IndexLakeDeleteExecNode {
                        namespace_name: exec.lazy_table.namespace_name.clone(),
                        table_name: exec.lazy_table.table_name.clone(),
                        condition: Some(condition_node),
                    },
                )),
            };

            proto.encode(buf).map_err(|e| {
                DataFusionError::Internal(format!(
                    "Failed to encode indexlake delete execution plan: {e:?}"
                ))
            })?;

            Ok(())
        } else {
            Err(DataFusionError::NotImplemented(format!(
                "IndexLakePhysicalCodec does not support encoding {}",
                node.name()
            )))
        }
    }
}

fn serialize_schema(schema: &SchemaRef) -> Result<ProtoSchema, DataFusionError> {
    let proto: ProtoSchema = schema
        .as_ref()
        .try_into()
        .map_err(|e| DataFusionError::Internal(format!("Failed to serialize schema: {e:?}")))?;
    Ok(proto)
}

fn parse_schema(proto: Option<ProtoSchema>) -> Result<SchemaRef, DataFusionError> {
    let proto =
        proto.ok_or_else(|| DataFusionError::Internal("Missing schema in protobuf".to_string()))?;
    let schema: arrow::datatypes::Schema = (&proto)
        .try_into()
        .map_err(|e| DataFusionError::Internal(format!("Failed to parse schema: {e:?}")))?;
    Ok(Arc::new(schema))
}

fn serialize_projection(projection: Option<&Vec<usize>>) -> Option<crate::protobuf::Projection> {
    projection.map(|p| crate::protobuf::Projection {
        projection: p.iter().map(|n| *n as u32).collect(),
    })
}

fn parse_projection(projection: Option<&crate::protobuf::Projection>) -> Option<Vec<usize>> {
    projection.map(|p| p.projection.iter().map(|n| *n as usize).collect())
}

fn serialize_insert_op(insert_op: InsertOp) -> i32 {
    let proto = match insert_op {
        InsertOp::Append => datafusion_proto::protobuf::InsertOp::Append,
        InsertOp::Overwrite => datafusion_proto::protobuf::InsertOp::Overwrite,
        InsertOp::Replace => datafusion_proto::protobuf::InsertOp::Replace,
    };
    proto.into()
}

fn parse_insert_op(insert_op: i32) -> Result<InsertOp, DataFusionError> {
    let proto = datafusion_proto::protobuf::InsertOp::try_from(insert_op)
        .map_err(|e| DataFusionError::Internal(format!("Failed to parse insert op: {e:?}")))?;
    match proto {
        datafusion_proto::protobuf::InsertOp::Append => Ok(InsertOp::Append),
        datafusion_proto::protobuf::InsertOp::Overwrite => Ok(InsertOp::Overwrite),
        datafusion_proto::protobuf::InsertOp::Replace => Ok(InsertOp::Replace),
    }
}

fn serialize_scan_partitions(
    partitions: &Arc<Vec<indexlake::table::TableScanPartition>>,
) -> Vec<TableScanPartition> {
    partitions
        .iter()
        .map(|partition| match partition {
            indexlake::table::TableScanPartition::Auto {
                partition_idx,
                partition_count,
            } => TableScanPartition {
                partition_type: Some(table_scan_partition::PartitionType::Auto(
                    TableScanPartitionAuto {
                        partition_idx: *partition_idx as u32,
                        partition_count: *partition_count as u32,
                    },
                )),
            },
            indexlake::table::TableScanPartition::Provided {
                contains_inline_rows,
                data_file_records,
            } => TableScanPartition {
                partition_type: Some(table_scan_partition::PartitionType::Provided(
                    TableScanPartitionProvided {
                        contains_inline_rows: *contains_inline_rows,
                        data_file_records: data_file_records
                            .iter()
                            .map(serialize_data_file_record)
                            .collect(),
                    },
                )),
            },
        })
        .collect()
}

fn parse_scan_partitions(
    proto_partitions: &[TableScanPartition],
) -> Result<Arc<Vec<indexlake::table::TableScanPartition>>, DataFusionError> {
    if proto_partitions.is_empty() {
        return Err(DataFusionError::Internal(
            "Missing scan partitions in indexlake scan exec node".to_string(),
        ));
    }

    let mut partitions = Vec::with_capacity(proto_partitions.len());
    for (idx, partition) in proto_partitions.iter().enumerate() {
        let partition = match &partition.partition_type {
            Some(table_scan_partition::PartitionType::Auto(auto)) => {
                indexlake::table::TableScanPartition::Auto {
                    partition_idx: auto.partition_idx as usize,
                    partition_count: auto.partition_count as usize,
                }
            }
            Some(table_scan_partition::PartitionType::Provided(provided)) => {
                let mut records = Vec::with_capacity(provided.data_file_records.len());
                for record in &provided.data_file_records {
                    records.push(parse_data_file_record(record)?);
                }
                indexlake::table::TableScanPartition::Provided {
                    contains_inline_rows: provided.contains_inline_rows,
                    data_file_records: records,
                }
            }
            None => {
                return Err(DataFusionError::Internal(format!(
                    "Missing partition type for scan partition {idx}"
                )));
            }
        };
        partitions.push(partition);
    }
    Ok(Arc::new(partitions))
}

fn serialize_data_file_record(record: &DataFileRecord) -> DataFile {
    DataFile {
        data_file_id: record.data_file_id.as_bytes().to_vec(),
        table_id: record.table_id.as_bytes().to_vec(),
        format: serialize_data_file_format(record.format),
        relative_path: record.relative_path.clone(),
        size: record.size,
        record_count: record.record_count,
        validity: record.validity.bytes().to_vec(),
        valid_record_count: record.valid_record_count,
    }
}

fn parse_data_file_record(proto_data_file: &DataFile) -> Result<DataFileRecord, DataFusionError> {
    Ok(DataFileRecord {
        data_file_id: Uuid::from_slice(&proto_data_file.data_file_id).map_err(|e| {
            DataFusionError::Internal(format!("Failed to parse data file id: {e:?}"))
        })?,
        table_id: Uuid::from_slice(&proto_data_file.table_id)
            .map_err(|e| DataFusionError::Internal(format!("Failed to parse table id: {e:?}")))?,
        format: parse_data_file_format(proto_data_file.format)?,
        relative_path: proto_data_file.relative_path.clone(),
        size: proto_data_file.size,
        record_count: proto_data_file.record_count,
        valid_record_count: proto_data_file.valid_record_count,
        validity: RowValidity::from(
            proto_data_file.validity.clone(),
            proto_data_file.record_count as usize,
        ),
    })
}

fn serialize_data_file_format(format: DataFileFormat) -> i32 {
    let proto_format = match format {
        DataFileFormat::ParquetV1 => crate::protobuf::DataFileFormat::ParquetV1,
        DataFileFormat::ParquetV2 => crate::protobuf::DataFileFormat::ParquetV2,
    };
    proto_format.into()
}

fn serialize_il_expr(expr: &indexlake::expr::Expr) -> Result<IndexLakeExprNode, DataFusionError> {
    let json = serde_json::to_string(expr).map_err(|e| {
        DataFusionError::Internal(format!("Failed to serialize indexlake expr: {e}"))
    })?;
    Ok(IndexLakeExprNode { json })
}

fn deserialize_il_expr(node: &IndexLakeExprNode) -> Result<indexlake::expr::Expr, DataFusionError> {
    serde_json::from_str(&node.json).map_err(|e| {
        DataFusionError::Internal(format!("Failed to deserialize indexlake expr: {e}"))
    })
}

fn parse_data_file_format(format: i32) -> Result<DataFileFormat, DataFusionError> {
    let proto_format = crate::protobuf::DataFileFormat::try_from(format).map_err(|e| {
        DataFusionError::Internal(format!("Failed to parse data file format: {e:?}"))
    })?;
    match proto_format {
        crate::protobuf::DataFileFormat::ParquetV1 => Ok(DataFileFormat::ParquetV1),
        crate::protobuf::DataFileFormat::ParquetV2 => Ok(DataFileFormat::ParquetV2),
    }
}