lance_table/transaction/operation.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4//! The vocabulary of changes a transaction can describe.
5//!
6//! Each [`Operation`] variant names one kind of change and carries exactly the
7//! inputs needed to apply it: the fragments to add, the fields that were
8//! rewritten, the indices that were rebuilt. Applying them is
9//! [`super::manifest_build`]; deciding whether two of them collide is
10//! [`super::conflicts`].
11
12use crate::format::key_existence::KeyExistenceFilter;
13use crate::format::overlay::DataOverlayFile;
14use crate::format::{BasePath, DataFile, Fragment, IndexFile, IndexMetadata};
15use crate::system_index::mem_wal::CompactedSsTable;
16use crate::transaction::UpdateMap;
17use lance_core::datatypes::Schema;
18use lance_core::deepsize::DeepSizeOf;
19use roaring::RoaringBitmap;
20use std::collections::HashMap;
21use uuid::Uuid;
22
23#[derive(Debug, Clone, DeepSizeOf, PartialEq)]
24pub struct DataReplacementGroup(pub u64, pub DataFile);
25
26/// Overlay files to append to a single fragment, in order (the last entry is
27/// newest). The overlays are appended to the fragment's existing `overlays`
28/// list rather than replacing it, so overlays written by concurrent commits are
29/// preserved. Each overlay's `committed_version` is stamped to the new dataset
30/// version at commit time (re-stamped on retry).
31#[derive(Debug, Clone, DeepSizeOf, PartialEq)]
32pub struct DataOverlayGroup {
33 pub fragment_id: u64,
34 pub overlays: Vec<DataOverlayFile>,
35}
36
37/// An operation on a dataset.
38#[derive(Debug, Clone, DeepSizeOf)]
39pub enum Operation {
40 /// Adding new fragments to the dataset. The fragments contained within
41 /// haven't yet been assigned a final ID.
42 Append { fragments: Vec<Fragment> },
43 /// Updated fragments contain those that have been modified with new deletion
44 /// files. The deleted fragment IDs are those that should be removed from
45 /// the manifest.
46 Delete {
47 updated_fragments: Vec<Fragment>,
48 deleted_fragment_ids: Vec<u64>,
49 predicate: String,
50 },
51 /// Overwrite the entire dataset with the given fragments. This is also
52 /// used when initially creating a table.
53 ///
54 /// The fragments are newly written ones and are assigned fresh ids at commit
55 /// time, continuing from the dataset's highest id ever used; the ids they
56 /// arrive with are ignored.
57 ///
58 /// A fragment carrying a deletion file is rejected. A deletion file's path
59 /// embeds the fragment id, so it cannot follow its fragment to the new id:
60 /// minting a fragment and giving it a deletion file are mutually exclusive in
61 /// one transaction. Use [`Self::Delete`] to commit deletions against existing
62 /// fragments, or [`Self::Merge`] to change their schema.
63 Overwrite {
64 fragments: Vec<Fragment>,
65 schema: Schema,
66 config_upsert_values: Option<HashMap<String, String>>,
67 initial_bases: Option<Vec<BasePath>>,
68 },
69 /// A new index has been created.
70 CreateIndex {
71 /// The new secondary indices,
72 /// any existing indices with the same name will be replaced.
73 new_indices: Vec<IndexMetadata>,
74 /// The indices that have been modified.
75 removed_indices: Vec<IndexMetadata>,
76 },
77 /// Data is rewritten but *not* modified. This is used for things like
78 /// compaction or re-ordering. Contains the old fragments and the new
79 /// ones that have been replaced.
80 ///
81 /// This operation will modify the row addresses of existing rows and
82 /// so any existing index covering a rewritten fragment will need to be
83 /// remapped.
84 Rewrite {
85 /// Groups of fragments that have been modified
86 groups: Vec<RewriteGroup>,
87 /// Indices that have been updated with the new row addresses
88 rewritten_indices: Vec<RewrittenIndex>,
89 /// The fragment reuse index to be created or updated to
90 frag_reuse_index: Option<IndexMetadata>,
91 },
92 /// Replace data in a column in the dataset with new data. This is used for
93 /// null column population where we replace an entirely null column with a
94 /// new column that has data.
95 ///
96 /// This operation will only allow replacing files that contain the same schema
97 /// e.g. if the original files contain columns A, B, C and the new files contain
98 /// only columns A, B then the operation is not allowed. As we would need to split
99 /// the original files into two files, one with column A, B and the other with column C.
100 ///
101 /// Corollary to the above: the operation will also not allow replacing files unless the
102 /// affected columns all have the same datafile layout across the fragments being replaced.
103 ///
104 /// e.g. if fragments being replaced contain files with different schema layouts on
105 /// the column being replaced, the operation is not allowed.
106 /// say `frag_1: [A] [B, C]` and `frag_2: [A, B] [C]` and we are trying to replace column A
107 /// with a new column A, the operation is not allowed.
108 DataReplacement {
109 replacements: Vec<DataReplacementGroup>,
110 },
111 /// Attach overlay files to fragments, supplying new values for a subset of
112 /// `(physical offset, field)` cells without rewriting the fragments' base
113 /// data files. See [`DataOverlayFile`] and the Data Overlay Files
114 /// specification for resolution, coverage, and versioning rules.
115 DataOverlay { groups: Vec<DataOverlayGroup> },
116 /// Merge a new column in
117 /// 'fragments' is the final fragments include all data files, the new fragments must align with old ones at rows.
118 /// 'schema' is not forced to include existed columns, which means we could use Merge to drop column data
119 Merge {
120 fragments: Vec<Fragment>,
121 schema: Schema,
122 /// Set when this merge makes no nullability-affecting schema change:
123 /// it introduces no field that data staged against an earlier schema
124 /// could not safely omit. Without the assertion the merge conflicts
125 /// with concurrent appends in either commit order, since a stale
126 /// append omits new columns entirely and its rows read as null.
127 preserves_nullability: bool,
128 },
129 /// Restore an old version of the database
130 Restore { version: u64 },
131 /// Reserves fragment ids for future use
132 /// This can be used when row ids need to be known before a transaction
133 /// has been committed. It is used during a rewrite operation to allow
134 /// indices to be remapped to the new row ids as part of the operation.
135 ReserveFragments { num_fragments: u32 },
136
137 /// Update values in the dataset.
138 ///
139 /// Updates are generally vertical or horizontal.
140 ///
141 /// A vertical update adds new rows. In this case, the updated_fragments
142 /// will only have existing rows deleted and will not have any new fields added.
143 /// All new data will be contained in new_fragments.
144 /// This is what is used by a merge_insert that matches the whole schema and what
145 /// is used by the dataset updater.
146 ///
147 /// A horizontal update adds new columns. In this case, the updated fragments
148 /// may have fields removed or added. It is even possible for a field to be tombstoned
149 /// and then added back in the same update. (which is a field modification). If any
150 /// fields are modified in this way then they need to be added to the fields_modified list.
151 /// This way we can correctly update the indices.
152 /// This is what is used by a merge insert that does not match the whole schema.
153 Update {
154 /// Ids of fragments that have been moved
155 removed_fragment_ids: Vec<u64>,
156 /// Fragments that have been updated
157 updated_fragments: Vec<Fragment>,
158 /// Fragments that have been added
159 new_fragments: Vec<Fragment>,
160 /// The fields that have been modified
161 fields_modified: Vec<u32>,
162 /// MemWAL SSTables to mark as compacted after this transaction.
163 compacted_sstables: Vec<CompactedSsTable>,
164 /// The fields that used to judge whether to preserve the new frag's id into
165 /// the frag bitmap of the specified indices.
166 fields_for_preserving_frag_bitmap: Vec<u32>,
167 /// The mode of update
168 update_mode: Option<UpdateMode>,
169 /// Optional filter for detecting conflicts on inserted row keys.
170 /// Only tracks keys from INSERT operations during merge insert, not updates.
171 inserted_rows_filter: Option<KeyExistenceFilter>,
172 /// Physical row offsets (per fragment) that matched `update_columns` for RewriteColumns.
173 /// `None` means callers did not supply offsets; `build_manifest` skips partial refresh then.
174 updated_fragment_offsets: Option<UpdatedFragmentOffsets>,
175 },
176
177 /// Project to a new schema.
178 Project {
179 schema: Schema,
180 /// Set when this projection makes no nullability-affecting schema
181 /// change, as a rename or a drop does not. A nullability tightening
182 /// must not set this: its producer proved the claim by scanning at its
183 /// read version, so a concurrent write can falsify it and the
184 /// projection conflicts with value-writes in either commit order.
185 preserves_nullability: bool,
186 },
187
188 /// Update the dataset configuration and metadata.
189 ///
190 /// Schema or field metadata updates conflict with a concurrent
191 /// [`Self::Merge`] in either commit order. A merge carries complete schema
192 /// state from its read version, so rebasing the operations could discard
193 /// metadata installed by the other transaction.
194 UpdateConfig {
195 config_updates: Option<UpdateMap>,
196 table_metadata_updates: Option<UpdateMap>,
197 schema_metadata_updates: Option<UpdateMap>,
198 field_metadata_updates: HashMap<i32, UpdateMap>,
199 },
200 /// Update SSTable compaction progress in the MemWAL index.
201 ///
202 /// This is used during merge-insert to atomically record which
203 /// SSTables have been compacted into the base table.
204 UpdateMemWalState {
205 compacted_sstables: Vec<CompactedSsTable>,
206 },
207
208 /// Clone a dataset.
209 Clone {
210 is_shallow: bool,
211 ref_name: Option<String>,
212 ref_version: u64,
213 ref_path: String,
214 branch_name: Option<String>,
215 },
216
217 // Update base paths in the dataset (currently only supports adding new bases).
218 UpdateBases {
219 /// The new base paths to add to the manifest.
220 new_bases: Vec<BasePath>,
221 },
222}
223
224#[derive(Debug, Clone, PartialEq, DeepSizeOf)]
225pub enum UpdateMode {
226 /// rows are deleted in current fragments and rewritten in new fragments.
227 /// This is most optimal when the majority of columns are being rewritten
228 /// or only a few rows are being updated.
229 RewriteRows,
230
231 /// within each fragment, columns are fully rewritten and inserted as new data files.
232 /// Old versions of columns are tombstoned. This is most optimal when most rows are affected
233 /// but a small subset of columns are affected.
234 RewriteColumns,
235}
236
237/// Matched physical row offsets per fragment for a partial [`UpdateMode::RewriteColumns`] update.
238///
239/// Used with stable row IDs so `build_manifest` can refresh row-level version
240/// metadata only for rows that were rewritten.
241#[derive(Debug, Clone, PartialEq, Eq, Default)]
242pub struct UpdatedFragmentOffsets(pub HashMap<u64, RoaringBitmap>);
243
244impl DeepSizeOf for UpdatedFragmentOffsets {
245 fn deep_size_of_children(&self, context: &mut lance_core::deepsize::Context) -> usize {
246 self.0.iter().fold(0_usize, |acc, (frag_id, bitmap)| {
247 acc + frag_id.deep_size_of_children(context)
248 + (bitmap.len() as usize).saturating_mul(std::mem::size_of::<u32>())
249 })
250 }
251}
252
253impl std::fmt::Display for Operation {
254 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255 match self {
256 Self::Append { .. } => write!(f, "Append"),
257 Self::Delete { .. } => write!(f, "Delete"),
258 Self::Overwrite { .. } => write!(f, "Overwrite"),
259 Self::CreateIndex { .. } => write!(f, "CreateIndex"),
260 Self::Rewrite { .. } => write!(f, "Rewrite"),
261 Self::Merge { .. } => write!(f, "Merge"),
262 Self::Restore { .. } => write!(f, "Restore"),
263 Self::ReserveFragments { .. } => write!(f, "ReserveFragments"),
264 Self::Update { .. } => write!(f, "Update"),
265 Self::Project { .. } => write!(f, "Project"),
266 Self::UpdateConfig { .. } => write!(f, "UpdateConfig"),
267 Self::DataReplacement { .. } => write!(f, "DataReplacement"),
268 Self::DataOverlay { .. } => write!(f, "DataOverlay"),
269 Self::Clone { .. } => write!(f, "Clone"),
270 Self::UpdateMemWalState { .. } => write!(f, "UpdateMemWalState"),
271 Self::UpdateBases { .. } => write!(f, "UpdateBases"),
272 }
273 }
274}
275
276#[derive(Debug, Clone, PartialEq)]
277pub struct RewrittenIndex {
278 pub old_id: Uuid,
279 pub new_id: Uuid,
280 pub new_index_details: prost_types::Any,
281 pub new_index_version: u32,
282 /// Files in the new index with their sizes.
283 /// Empty list from older writers that didn't persist this field.
284 pub new_index_files: Option<Vec<IndexFile>>,
285}
286
287impl DeepSizeOf for RewrittenIndex {
288 fn deep_size_of_children(&self, context: &mut lance_core::deepsize::Context) -> usize {
289 self.new_index_details
290 .type_url
291 .deep_size_of_children(context)
292 + self.new_index_details.value.deep_size_of_children(context)
293 }
294}
295
296#[derive(Debug, Clone, DeepSizeOf)]
297pub struct RewriteGroup {
298 pub old_fragments: Vec<Fragment>,
299 pub new_fragments: Vec<Fragment>,
300}
301
302impl PartialEq for RewriteGroup {
303 fn eq(&self, other: &Self) -> bool {
304 fn compare_vec<T: PartialEq>(a: &[T], b: &[T]) -> bool {
305 a.len() == b.len() && a.iter().all(|f| b.contains(f))
306 }
307 compare_vec(&self.old_fragments, &other.old_fragments)
308 && compare_vec(&self.new_fragments, &other.new_fragments)
309 }
310}
311
312impl Operation {
313 pub fn name(&self) -> &str {
314 match self {
315 Self::Append { .. } => "Append",
316 Self::Delete { .. } => "Delete",
317 Self::Overwrite { .. } => "Overwrite",
318 Self::CreateIndex { .. } => "CreateIndex",
319 Self::Rewrite { .. } => "Rewrite",
320 Self::Merge { .. } => "Merge",
321 Self::ReserveFragments { .. } => "ReserveFragments",
322 Self::Restore { .. } => "Restore",
323 Self::Update { .. } => "Update",
324 Self::Project { .. } => "Project",
325 Self::UpdateConfig { .. } => "UpdateConfig",
326 Self::DataReplacement { .. } => "DataReplacement",
327 Self::DataOverlay { .. } => "DataOverlay",
328 Self::UpdateMemWalState { .. } => "UpdateMemWalState",
329 Self::Clone { .. } => "Clone",
330 Self::UpdateBases { .. } => "UpdateBases",
331 }
332 }
333}