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
//! Scoped Parquet and inline index backfills.
use std::{
collections::{BTreeSet, HashMap, HashSet},
sync::Arc,
};
use bytes::Bytes;
use futures::{StreamExt, TryStreamExt, stream};
use object_store::path::Path;
use super::{BACKFILL_FILE_READ_CONCURRENCY, ReadOnlyCatalog};
use crate::{
catalog::{
ColumnId, DataFileInfo, DeleteFileInfo, FileIndexEntry, IndexEntry, IndexId, TableId,
resolve_data_path,
},
data_file::{self, DataStore},
error::{Error, Result},
store::{handle::ReadHandle, inline as store_inline, key::InlineOperation},
};
async fn collect_immediate_backfill<'a>(
files: impl Iterator<Item = DataFileInfo> + 'a,
object_store: DataStore,
metrics: Arc<data_file::ScopedReadMetrics>,
positions: &[usize],
resolve: impl Fn(&str, bool) -> Path,
killed_positions: &'a HashMap<u64, HashSet<u64>>,
) -> Result<Vec<IndexEntry>> {
// Each future drains its file completely, so the one buffer below is the
// whole read window; a second stage would hold a window of its own.
stream::iter(files)
.map(move |file| {
let object_store = object_store.clone();
let metrics = Arc::clone(&metrics);
let path = resolve(&file.path, file.path_is_relative);
let dead_positions = killed_positions.get(&file.id.get());
async move {
data_file::scoped_read_entry_batches(
data_file::ParquetFile::new(
object_store,
path,
file.file_size_bytes,
file.footer_size,
)
.with_metrics(metrics),
positions,
data_file::ScopedRows::All,
data_file::RowIdSource::Resolve {
row_id_start: file.row_id_start,
},
)
.await?
.try_fold(Vec::new(), move |mut entries, batch| async move {
entries.extend(batch.into_iter().filter_map(|entry| {
let dead = dead_positions
.is_some_and(|positions| positions.contains(&entry.ordinal));
(!dead).then_some(IndexEntry {
row_id: entry.row_id,
values: entry.values,
})
}));
Ok(entries)
})
.await
}
})
.buffer_unordered(BACKFILL_FILE_READ_CONCURRENCY)
.try_fold(Vec::new(), |mut entries, file_entries| async move {
entries.extend(file_entries);
Ok(entries)
})
.await
}
pub(super) async fn collect_inline_delete_positions(
session_handle: ReadHandle<'_>,
table_id: u64,
) -> Result<HashMap<u64, HashSet<u64>>> {
let killed = store_inline::scan_inline_file_deletes(session_handle, table_id)
.await?
.into_iter()
.fold(
HashMap::<u64, HashSet<u64>>::new(),
|mut killed, (data_file_id, row_id, _)| {
killed.entry(data_file_id).or_default().insert(row_id);
killed
},
);
Ok(killed)
}
/// Folds inline file-deletes into the delete-file positions of the same
/// target. Both name a physical position within their file, so one map
/// serves both.
pub(super) fn merge_killed_positions(
killed_positions: &mut HashMap<u64, HashSet<u64>>,
inline_killed: HashMap<u64, HashSet<u64>>,
) {
for (data_file_id, positions) in inline_killed {
killed_positions
.entry(data_file_id)
.or_default()
.extend(positions);
}
}
/// The recorded inline schema of each distinct version in `schema_versions`,
/// fetched concurrently.
pub(super) async fn read_inline_schemas(
session_handle: ReadHandle<'_>,
table: TableId,
schema_versions: impl IntoIterator<Item = u64>,
) -> Result<HashMap<u64, Bytes>> {
let schema_versions: BTreeSet<u64> = schema_versions.into_iter().collect();
stream::iter(
schema_versions
.into_iter()
.map(|schema_version| async move {
let record =
store_inline::read_inline_schema(session_handle, table.get(), schema_version)
.await?
.ok_or_else(|| {
Error::Corruption(format!(
"no inline schema for table {table} version {schema_version}"
))
})?;
Ok::<_, Error>((schema_version, record))
}),
)
.buffer_unordered(BACKFILL_FILE_READ_CONCURRENCY)
.try_collect()
.await
}
pub(super) async fn collect_delete_positions<'a>(
files: impl Iterator<Item = DeleteFileInfo> + 'a,
object_store: DataStore,
metrics: Arc<data_file::ScopedReadMetrics>,
resolve: &'a impl Fn(&str, bool) -> Path,
) -> Result<HashMap<u64, HashSet<u64>>> {
stream::iter(files.map(|file| {
let path = resolve(&file.path, file.path_is_relative);
let object_store = object_store.clone();
let metrics = Arc::clone(&metrics);
async move {
let positions = data_file::delete_file_positions(
data_file::ParquetFile::new(
object_store,
path,
file.file_size_bytes,
file.footer_size,
)
.with_metrics(metrics),
)
.await?;
Ok::<_, Error>((file.data_file_id.get(), positions))
}
}))
.buffer_unordered(BACKFILL_FILE_READ_CONCURRENCY)
.try_fold(
HashMap::<u64, HashSet<u64>>::new(),
|mut killed, (data_file_id, positions)| async move {
killed.entry(data_file_id).or_default().extend(positions);
Ok(killed)
},
)
.await
}
impl ReadOnlyCatalog {
/// Derives the index entries for a file the extension path registers, by
/// scoped-reading it. The caller resolves each of the index's columns to
/// its physical position in the file and passes them in the index's
/// column order. `file_size` and `footer_size` are DuckLake's recorded
/// values. The returned entries feed
/// [`crate::Transaction::register_data_file`].
///
/// A file carrying an embedded row-id column is refused: its rows
/// already have ids.
///
/// # Errors
///
/// Returns [`Error::Corruption`] if the file cannot be read or a column
/// type does not match its Parquet type, or [`Error::Constraint`] for a
/// non-indexable column type or a file carrying an embedded row-id
/// column.
pub async fn scoped_file_index_entries(
&self,
object_store: DataStore,
path: &Path,
file_size: u64,
footer_size: u64,
index: IndexId,
indexed_positions: &[usize],
) -> Result<Vec<FileIndexEntry>> {
let entries = data_file::scoped_read_recorded_entries(
data_file::ParquetFile::new(object_store, path.clone(), file_size, footer_size)
.with_metrics(self.data_read_metrics()),
indexed_positions,
data_file::ScopedRows::All,
data_file::RowIdSource::Ordinal,
)
.await?
.into_iter()
.map(|entry| FileIndexEntry {
index,
ordinal: entry.row_id,
values: entry.values,
})
.collect();
Ok(entries)
}
/// Backfills an index over a table's live data by scoped-reading every
/// live file from `object_store` (the `DATA_PATH` store) and deriving one
/// entry per row — the extension-path build for a table that already
/// holds data. The returned entries feed `create_index`'s backfill.
/// Indexed columns are located by resolving each field id to its physical
/// position (the file's columns follow the table's column order).
///
/// Row ids resolve per file: the embedded row-id column when the file
/// carries one (rewrite and flush output), else `row_id_start +
/// ordinal`. Rows already dead — named by a delete file's positions or
/// by an inline file-delete, both physical — are excluded, so entries
/// stay live-only.
///
/// # Errors
///
/// Returns [`Error::NotFound`] if the table or a column is not live,
/// [`Error::Constraint`] for a non-indexable type, or
/// [`Error::Corruption`] if a file cannot be read or names no row-id
/// source.
pub async fn scoped_backfill_entries(
&self,
object_store: DataStore,
data_prefix: &str,
table: TableId,
columns: &[ColumnId],
) -> Result<Vec<IndexEntry>> {
let session = self.begin_read().await?;
let snapshot = self.head_view(session.handle()).await?;
let positions = snapshot.column_positions(table, columns)?;
let table_prefix = snapshot.table_data_prefix(table)?;
let resolve = |path: &str, is_relative: bool| {
let relative = resolve_data_path(data_prefix, &table_prefix, path, is_relative);
object_store::path::Path::from(relative.as_str())
};
// Entries are live-only. Both kinds of deletion name a physical
// position within their target file, so they fold into one map.
let inline_deletes = collect_inline_delete_positions(session.handle(), table.get());
let metrics = self.data_read_metrics();
let delete_files = collect_delete_positions(
snapshot.delete_files_of(table).into_iter(),
object_store.clone(),
Arc::clone(&metrics),
&resolve,
);
let (inline_killed, mut killed_positions) =
futures::try_join!(inline_deletes, delete_files)?;
merge_killed_positions(&mut killed_positions, inline_killed);
let outcome = collect_immediate_backfill(
snapshot.data_files_of(table).into_iter(),
object_store,
metrics,
&positions,
resolve,
&killed_positions,
)
.await;
session.finish();
outcome
}
/// Backfill entries for a table's live **inline** rows, by scanning its
/// inline chunks — the counterpart to [`Self::scoped_backfill_entries`]
/// for rows moraine holds in the store rather than external files.
/// Tombstoned (inline-deleted) rows are excluded; a NULL indexed value
/// yields a `None`, so `IS NULL` finds the row. Reads the catalog store,
/// so it needs no data object store.
///
/// # Errors
///
/// [`Error::NotFound`] if a column is not live, or [`Error::Corruption`]
/// if a chunk names no recorded schema or cannot be decoded.
pub async fn inline_backfill_entries(
&self,
table: TableId,
columns: &[ColumnId],
) -> Result<Vec<IndexEntry>> {
let session = self.begin_read().await?;
let snapshot = self.head_view(session.handle()).await?;
let positions = snapshot.column_positions(table, columns)?;
// A tombstone ends only versions begun before it. UPDATE can
// reinsert the same row id in the tombstone's snapshot, and that
// newer value is live and must be indexed.
let (dead, chunks) = futures::try_join!(
async {
Ok::<_, Error>(
store_inline::scan_inline_deletes(session.handle(), table.get())
.await?
.into_iter()
.map(|(row_id, deletion)| (row_id, deletion.end_snapshot))
.collect::<HashMap<u64, u64>>(),
)
},
store_inline::scan_inline_chunks(session.handle(), table.get()),
)?;
let schema_versions = chunks.iter().filter_map(|(operation, _)| match operation {
InlineOperation::Insert { schema_version, .. } => Some(*schema_version),
_ => None,
});
let schemas = read_inline_schemas(session.handle(), table, schema_versions)
.await?
.into_iter()
.map(|(schema_version, record)| {
let schema = data_file::decode_inline_schema(record)?;
Ok::<_, Error>((schema_version, schema))
})
.collect::<Result<HashMap<_, _>>>()?;
let mut entries = Vec::new();
for (op, chunk) in chunks {
let InlineOperation::Insert {
schema_version,
begin_snapshot,
..
} = op
else {
continue;
};
let schema = schemas.get(&schema_version).cloned().ok_or_else(|| {
Error::Corruption(format!(
"no inline schema for table {table} version {schema_version}"
))
})?;
let scoped = data_file::inline_batch_entries(
schema,
&chunk.body,
&positions,
chunk.row_id_start,
)?;
entries.extend(
scoped
.into_iter()
.filter(|entry| {
dead.get(&entry.row_id)
.is_none_or(|end_snapshot| begin_snapshot >= *end_snapshot)
})
.map(|entry| IndexEntry {
row_id: entry.row_id,
values: entry.values,
}),
);
}
session.finish();
Ok(entries)
}
}