Skip to content

fix: choose cheapest blanks when restoring deleted rows - #8946

Merged
wjones127 merged 1 commit into
lance-format:mainfrom
chenyu-x:fix-add-blank
Oct 8, 2026
Merged

wjones127 merged 1 commit into
lance-format:mainfrom
chenyu-x:fix-add-blank

Conversation

@chenyu-x

@chenyu-x chenyu-x commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What

Adding or updating columns can fail with an Arrow offset overflow when a fragment contains many deleted rows and a variable-width column has a large value in its first live row.

The updater restores deleted physical rows with placeholder values. Previously every placeholder copied row zero, so large string, binary, or nested values were repeated for every deleted row.

Root cause

Every data file in a fragment must have the same physical row count. Before writing a new column, DeletionRestorer therefore inserts blank rows at deleted positions.

add_blanks implemented every blank with take(0). For variable-width columns this copied the payload of the first live row once per deleted row. A sufficiently large deletion run could grow the values buffer past the Arrow offset limit even though those placeholder values are never visible to readers.

Independent of the offset overflow, the restorer also appended an entire contiguous deleted run into a single output batch on v2 files (no batch-size cap on the appended blanks), so peak memory scaled with the length of the deleted run rather than the configured batch size. (Thanks @LuciferYang for spotting this.)

Fix

Choose the cheapest valid blank independently for each column:

  • use null when both the dataset write schema and Arrow field are nullable and the file version supports nulls;
  • use empty values for strings and binary arrays;
  • rebuild List, LargeList, and Map offsets without copying child values;
  • recursively optimize Struct and FixedSizeList children;
  • keep using take for fixed-width and dictionary arrays, where copying a value does not increase payload size.

Bound restored and deferred blank batches by the updater batch size. Retain a compact one-row source for layouts that still require take, so trailing deletion runs can be written in bounded chunks without keeping the original batch payload alive.

The write-schema nullability and exact storage-version policies are preserved. Zero batch sizes and unfinished deletion restoration now return descriptive errors.

Tests

Add coverage for:

  • heavy deletion runs with large binary payloads;
  • nullable and non-nullable variable-width columns;
  • file-version-specific null support;
  • dictionary, List, Map, Struct, and FixedSizeList columns;
  • bounded leading and trailing deletion runs;
  • dataset write-schema nullability;
  • add_columns and update_columns integration paths;
  • zero batch sizes and unaccounted deletions at finish.

Fixes #8890

@github-actions github-actions Bot added the bug Something isn't working label Sep 2, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 2, 2026
@LuciferYang

Copy link
Copy Markdown
Contributor

cc @Xuanwo @wjones127 FYI

@LuciferYang

Copy link
Copy Markdown
Contributor

friendly ping @Xuanwo @wjones127

@wjones127 wjones127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation is quite large, and I don't fully understand why it's necessary. Could you answer a few questions on that?

Comment thread rust/lance/src/dataset/versions/mod.rs Outdated
Comment on lines +594 to +598
///
/// The V1 arm is a whitelist rather than a general capability model: it enumerates the
/// types the legacy writer was known to handle when [`validate_nulls`] was added for
/// the hash-join path. Treat a `false` there as "not known to be supported", and
/// prefer to widen it only alongside a legacy round-trip test.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: this seems like it should be a internal comment, not a public comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: this seems like it should be a internal comment, not a public comment.

Resolved. Rebasing onto main replaced my supports_nulls split with main's validate_nulls, so that public doc no longer exists in this PR. I also fixed one stale supports_nulls mention in a test comment to reference validate_nulls.

Comment thread rust/lance/src/dataset/updater.rs Outdated
use arrow::{array::AsArray, datatypes::Int32Type};
use lance_datagen::RowCount;
use rstest::rstest;
enum BlankPlan {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue(blocking): this module is getting vary large. Please move the BlankPlan and it's associated methods into a submodule.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue(blocking): this module is getting vary large. Please move the BlankPlan and it's associated methods into a submodule.

Done. BlankPlan and all its helpers (blank_plan, blank_plans, add_blanks, add_blanks_with_plans, apply_blank_plan, compact_blank_source, and the nested-container helpers) now live in a new dataset/updater/blanks.rs submodule with pub(super) visibility. updater.rs keeps only mod blanks; plus the use blanks::{...} imports.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: how much of the complexity here is created to support formats < 2.1? Could w gate the optimization on 2.1 and get a simpler implementation?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: how much of the complexity here is created to support formats < 2.1? Could w gate the optimization on 2.1 and get a simpler implementation?

Legacy v1 now returns an all-Take plan — byte-for-byte the previous take(0) behavior — so no legacy write path is extended (per the AGENTS.md legacy-boundary guidance), and the cheap per-column blanks run only on 2.0+. I scoped it to 2.0+ rather than 2.1+ because the production incident this fixes is on 2.0 datasets; everything below 2.0 stays frozen.

Comment thread rust/lance/src/dataset/updater.rs Outdated
Comment on lines +1011 to +1014
let mut take_indices = needs_take.then(|| Vec::with_capacity(output_len));
// Indices for `interleave`: `(0, pos)` picks live row `pos` out of the column
// itself, `(1, 0)` picks the column's one-row blank filler.
let mut interleave_indices = needs_interleave.then(|| Vec::with_capacity(output_len));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: is it necessary to branch on these? Why not unconditionally use interleave?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: is it necessary to branch on these? Why not unconditionally use interleave?

The two aren't redundant — each is the cheapest option for its column kind, so the branch is a deliberate cost choice rather than incidental complexity:

Take copies row zero for columns where every value has identical physical cost (fixed-width, and dictionary). For dictionaries this also preserves the shared values buffer; routing them through interleave with a filler would rebuild buffers we otherwise share for free.
Interleave is used only where a synthetic empty/null filler is strictly cheaper than copying row zero (the variable-width types — exactly the ones whose take(0) copy caused the offset overflow).
I documented this rationale on the BlankPlan enum. If you'd still prefer unconditional interleave for a smaller surface, I'm happy to switch — the only cost is losing the dictionary-buffer sharing and the fixed-width fast path.

@LuciferYang

Copy link
Copy Markdown
Contributor

This implementation is quite large, and I don't fully understand why it's necessary. Could you answer a few questions on that?

This PR actually originates from a bug we encountered in real customer scenarios. @chenyu-x can walk through the specific issue.

@chenyu-x

Copy link
Copy Markdown
Contributor Author

This implementation is quite large, and I don't fully understand why it's necessary. Could you answer a few questions on that?

Thanks for the review, and thanks @LuciferYang for the context.

The concrete bug. On a fragment with many deleted rows, add_columns/update_columns fails with an Arrow offset overflow when a variable-width column has a large value in its first live row. add_blanks filled every restored (deleted) position with take(0) — a copy of row zero. For a variable-width column that copies the first live value's payload once per deleted row, so a long deletion run multiplies that payload until the values buffer passes the i32 offset limit — even though those placeholder bytes are never visible to a reader. We hit this in a real customer dataset. A minimal repro: write a fragment, delete most of its rows, then add/update a Binary/Utf8 column whose first surviving row holds a large value.

On the size — you're right, and I'd like to cut it down:

I'll move BlankPlan and its helpers into a submodule (your blocking comment) and switch the supports_nulls doc to an internal comment.
On gating the optimization to 2.1+: a meaningful share of the complexity is the pre-existing legacy (< 2.1) machinery — the supports_nulls whitelist and the DeletionRestorer defer / row-group-size paths. Keeping the old take(0) behavior for < 2.1 and applying the cheap-blank logic only on 2.1+ would both shrink this and align with the "don't extend legacy write paths" guidance in AGENTS.md.

lance-gatekeeper[bot]

This comment was marked as outdated.

@wjones127

Copy link
Copy Markdown
Contributor

On gating the optimization to 2.1+: a meaningful share of the complexity is the pre-existing legacy (< 2.1) machinery — the supports_nulls whitelist and the DeletionRestorer defer / row-group-size paths. Keeping the old take(0) behavior for < 2.1 and applying the cheap-blank logic only on 2.1+ would both shrink this and align with the "don't extend legacy write paths" guidance in AGENTS.md.

If the production bugs are on 2.0 datasets, then I'm open to including that. 1.0 at least seems like a clear case of something we don't need to support as well. It's largely deprecated.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 21, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 21, 2026
@chenyu-x
chenyu-x requested a review from wjones127 September 22, 2026 06:45

@LuciferYang LuciferYang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went through this change independently, since we are the ones who hit the production bug. The root cause and the shape of the fix are both right. Four comments inline, none of them objecting to the approach.

One thing worth adding on necessity, @wjones127: this also fixes a second bug that has not come up yet, and it is easier to verify than the offset overflow. Before this PR, deleted_batch_offsets_in_range ended its loop on Self::is_full(legacy_batch_size, num_rows), and legacy_batch_size is None on v2, so that test was always false. Every included deleted id also bumps last_row_id, so a contiguous deleted run was appended to the current batch in full: a 1M-row run becomes one 1M-row output batch whatever batch size was configured, and each of those rows is a take(0) copy of row zero. That half has nothing to do with variable-width columns. The output batch ignores the configured batch size for every column type, so peak memory tracks the length of the deletion run rather than the batch size. @chenyu-x this is worth putting in the PR description.

On the size, it comes from type coverage rather than version compatibility, which is also why gating at 2.1 would not have bought a simpler implementation: storage_version is read exactly once in blanks.rs, in the matches! at line 192, and the planner has no other version-dependent branch. By function, counting doc plus body, the file is apply_blank_plan 113, apply_fixed_size_list_blank_plan 109, blank_plan 108, add_blanks_with_plans 105, compact_nested_dictionaries 75, blob_blank_plan 62, blank_offsets 60. The FixedSizeList arm is the one no built-in Lance type reaches, which is the third comment below.

I ran no build and no tests. The row-count and ordering argument rests on a model that replicates the restorer (every deletion-vector subset for fragments up to 12 rows crossed with batch sizes 1 to 5, plus 60k trials with random chunk sizes), not on the repo's own suite.

)));
}
};
Ok(Arc::new(MapArray::try_new(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apply_map_blank_plan passes the input's own entries field straight into MapArray::try_new, and arrow 58 rejects there unconditionally: if field.is_nullable() || entries.null_count() != 0. The pre-PR path went through take, whose Map branch ends in MapArray::from(build_unchecked()) and never checks the entries field's nullability.

So a map column whose entries field is declared nullable goes from working to Failed to add blanks: MapArray entries cannot contain nulls on any fragment with deletions, with no null anywhere in the array. Such a map is schema-invalid per the Arrow spec, but Lance keeps it: Field::try_from validates keys_sorted, the entries struct shape and the key field's nullability, not the entries field's own.

project_array in lance-arrow already lets that shape through, with a comment saying it must not gain a new error. The same guard fits here: fall back to Take in blank_plan when the entries field is nullable, and gate the Map arm of compact_nested_dictionaries too, since that one dispatches on the data type. test_map_blanks_reuse_entries only covers the well-formed case, so a nullable-entries case would be worth adding with the fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apply_map_blank_plan passes the input's own entries field straight into MapArray::try_new, and arrow 58 rejects there unconditionally: if field.is_nullable() || entries.null_count() != 0. The pre-PR path went through take, whose Map branch ends in MapArray::from(build_unchecked()) and never checks the entries field's nullability.

So a map column whose entries field is declared nullable goes from working to Failed to add blanks: MapArray entries cannot contain nulls on any fragment with deletions, with no null anywhere in the array. Such a map is schema-invalid per the Arrow spec, but Lance keeps it: Field::try_from validates keys_sorted, the entries struct shape and the key field's nullability, not the entries field's own.

project_array in lance-arrow already lets that shape through, with a comment saying it must not gain a new error. The same guard fits here: fall back to Take in blank_plan when the entries field is nullable, and gate the Map arm of compact_nested_dictionaries too, since that one dispatches on the data type. test_map_blanks_reuse_entries only covers the well-formed case, so a nullable-entries case would be worth adding with the fix.

Good catch — fixed. blank_plan's Map arm now returns BlankPlan::Take when the entries field is nullable, so it never reaches MapArray::try_new (which rejects a nullable entries field in arrow 58). I applied the same guard to the Map arm of compact_nested_dictionaries, since that path also rebuilds through MapArray::try_new. Added test_nullable_map_entries_field_copies_row_zero, which builds that spec-invalid-but-Lance-tolerated shape unchecked and asserts the plan is Take and that add_blanks no longer fails with "MapArray entries cannot contain nulls".

// null for any type it will actually null: v2.0 only forbids struct-level nulls, and
// the planner never nulls a struct (it mirrors row zero's validity), so v2.0+ can be
// treated uniformly.
let cheap_blanks = matches!(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cheap_blanks enumerates V2_0..V2_3, but ConcreteFileVersion only has V1 plus those four, so the condition is just != V1. matches! is not exhaustiveness-checked, so when V2_4 lands nothing flags this.

The new version then falls into the !cheap_blanks early return, every column goes back to take(0), and the overflow this PR fixes is live again on the newest format. Nothing in this PR would go red: test_blank_optimization_gated_on_v2 lists V1/V2_0/V2_1, and none of the e2e cases run LanceFileVersion::Next. The contrast worth noting is that validate_nulls and check_field_conflict both dispatch on an exhaustive match version, so a new version drags the author into those two and only this matches! stays quiet.

Inverting it to !matches!(storage_version, ConcreteFileVersion::V1) says what you mean: v1 is the frozen path, not "the v2 versions we happen to know today".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cheap_blanks enumerates V2_0..V2_3, but ConcreteFileVersion only has V1 plus those four, so the condition is just != V1. matches! is not exhaustiveness-checked, so when V2_4 lands nothing flags this.

The new version then falls into the !cheap_blanks early return, every column goes back to take(0), and the overflow this PR fixes is live again on the newest format. Nothing in this PR would go red: test_blank_optimization_gated_on_v2 lists V1/V2_0/V2_1, and none of the e2e cases run LanceFileVersion::Next. The contrast worth noting is that validate_nulls and check_field_conflict both dispatch on an exhaustive match version, so a new version drags the author into those two and only this matches! stays quiet.

Inverting it to !matches!(storage_version, ConcreteFileVersion::V1) says what you mean: v1 is the frozen path, not "the v2 versions we happen to know today".

Done. Changed cheap_blanks from a matches! to an exhaustive match storage_version { V1 => false, V2_0 | V2_1 | V2_2 | V2_3 => true }, so it now reads as "v1 is the frozen path" rather than "the v2 versions we happen to know today" — matching how validate_nulls and check_field_conflict dispatch. A future format variant is now a compile error here instead of silently falling into the !cheap_blanks early return and reopening the overflow on the newest format.

)?))
}

fn apply_fixed_size_list_blank_plan(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In blank_plan, an FSL whose child plans as Take collapses at line 809, and that covers vectors and multivectors. So apply_fixed_size_list_blank_plan only runs when the child is variable-width: FixedSizeList<Utf8>, or FixedSizeList<Struct<...>> with a variable-width member. Lance supports those, but no built-in Lance type is that shape (bfloat16 is FixedSizeBinary, WKB is Binary, JSON is Utf8 or LargeBinary), and neither is the column in #8890.

These 109 lines are the only place in the file that hand-rolls a parent-to-child index expansion, which is why they need the explicit length check at line 530. What covers them is four unit tests that build the arrays directly: a non-nullable Binary child under a nullable parent, a nullable Binary child under a non-nullable parent, a fixed-width child, and a zero-width list. None has a child plan of Struct, which is the only path through the validity loop in that arm, and no e2e case puts an FSL with a variable-width child through a real writer, while list, map, struct, view, json, blob and legacy all have one.

Either drop the arm and let FSL follow fixed-width columns through Take, saying in the PR that those shapes go back to the old behavior, or add the two missing cases. As it stands the hardest code in the file rests on unit tests alone.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In blank_plan, an FSL whose child plans as Take collapses at line 809, and that covers vectors and multivectors. So apply_fixed_size_list_blank_plan only runs when the child is variable-width: FixedSizeList<Utf8>, or FixedSizeList<Struct<...>> with a variable-width member. Lance supports those, but no built-in Lance type is that shape (bfloat16 is FixedSizeBinary, WKB is Binary, JSON is Utf8 or LargeBinary), and neither is the column in #8890.

These 109 lines are the only place in the file that hand-rolls a parent-to-child index expansion, which is why they need the explicit length check at line 530. What covers them is four unit tests that build the arrays directly: a non-nullable Binary child under a nullable parent, a nullable Binary child under a non-nullable parent, a fixed-width child, and a zero-width list. None has a child plan of Struct, which is the only path through the validity loop in that arm, and no e2e case puts an FSL with a variable-width child through a real writer, while list, map, struct, view, json, blob and legacy all have one.

Either drop the arm and let FSL follow fixed-width columns through Take, saying in the PR that those shapes go back to the old behavior, or add the two missing cases. As it stands the hardest code in the file rests on unit tests alone.

Kept the arm and added a unit test for the case you flagged. test_fixed_size_list_of_struct_blanks uses a FixedSizeList<Struct<Utf8, Int32>> so the child plan is Struct, which is the path that goes through the validity loop. It checks the actual output (variable-width member nulled, fixed-width member copied from row zero, parent validity valid/null/valid), not just the plan shape.

I did try the writer e2e. A FixedSizeList column through a real writer panics in lance-encoding/src/statistics.rs ("compute_stat should only be called once during DataBlock construction"), and it isn't related to blanks: a fully-live FSL with a variable-width child hits the same panic with no deletions at all. I didn't want to drag an unrelated encoder bug into this PR, so I left it at the unit test for now. Can add the e2e once that's fixed.

if self.finished {
return Ok(None);
}
if self.last_input.is_some() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pairing rejection in next (last_input as a state token) and the physical_rows reconciliation in finish pin down the updater's calling contract, and neither depends on how a blank is chosen per column. All four in-tree call sites already pair next with update (merge, update_columns_with_offsets, the add_columns loop in schema_evolution.rs, and the per-fragment update in merge_insert.rs), so neither changes current behavior.

Those two would review better as their own PR, leaving this one as a bugfix with a single root cause. NonZeroU32, the finish stream probe and prefetched_input should stay here: the first is a precondition of the new chunking (take_pending_blanks_with_plans calls min(max_output_rows.get())), and the other two exist because deferring blanks creates the "stream ended while blanks are owed" state that has to be told apart from a caller that stopped polling.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pairing rejection in next (last_input as a state token) and the physical_rows reconciliation in finish pin down the updater's calling contract, and neither depends on how a blank is chosen per column. All four in-tree call sites already pair next with update (merge, update_columns_with_offsets, the add_columns loop in schema_evolution.rs, and the per-fragment update in merge_insert.rs), so neither changes current behavior.

Those two would review better as their own PR, leaving this one as a bugfix with a single root cause. NonZeroU32, the finish stream probe and prefetched_input should stay here: the first is a precondition of the new chunking (take_pending_blanks_with_plans calls min(max_output_rows.get())), and the other two exist because deferring blanks creates the "stream ended while blanks are owed" state that has to be told apart from a caller that stopped polling.

You're right that these two don't depend on the blank choice and don't change behavior at the four call sites. I'd still rather keep them here. They guard the same update/finish flow this PR rewrites for bounded restoration: the physical_rows reconciliation checks the row accounting that deferring blanks changes, and the next pairing token protects that rewritten path. Splitting them means rewriting this flow in one PR and coming back to add its guards in another, reviewed apart from the code they guard. Since they're small and behavior-preserving, keeping them next to the rewrite reads better to me as one bugfix. Happy to pull them out if you'd still prefer that.

@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 23, 2026
@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 23, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Gate recommendation: approve.

The rebase keeps the core fix: deleted-row restoration no longer amplifies variable-width payloads on v2.0+, restored batches remain bounded, and legacy v1 stays on its frozen path. The newer writer boundary still accepts the affected JSON, view, map, and blob-v2 round trips; the nullable-map fallback remains intact.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 23, 2026
.zip(&plans)
.map(|(array, plan)| match plan {
BlankPlan::Interleave(filler) => Ok(filler.clone()),
_ => compact_nested_dictionaries(array.clone()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compact_blank_source only swaps top-level Interleave columns. A blob v2 column plans as a top-level Struct, so its data child is never swapped; List/Map attaches the child array whole; a nested view child keeps every data buffer of the source column, because that is what Arrow's take_byte_view does.

All of that payload is still attached after slice(0, chunk), and the writer defaults to keep_original_array: false, so deep_copy_buffer copies the whole buffer and the page budget is charged for it. A one-million-row leading deleted run with a 5 MB first blob means roughly 977 blank-only batches, so close to 5 GB of pointless memcpy.

Worth making compact_blank_source recurse: swap nested Interleave plans for their fillers, and rebuild a List/Map column whose plan rebuilds offsets as a one-row empty list or map, zeroing the offsets along with the child (swapping only the child makes try_new report an out-of-range offset). Columns that fall back to Take still need their payload, and the recursion has to stop at FixedSizeList, which indexes children by input_row * size.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compact_blank_source only swaps top-level Interleave columns. A blob v2 column plans as a top-level Struct, so its data child is never swapped; List/Map attaches the child array whole; a nested view child keeps every data buffer of the source column, because that is what Arrow's take_byte_view does.

All of that payload is still attached after slice(0, chunk), and the writer defaults to keep_original_array: false, so deep_copy_buffer copies the whole buffer and the page budget is charged for it. A one-million-row leading deleted run with a 5 MB first blob means roughly 977 blank-only batches, so close to 5 GB of pointless memcpy.

Worth making compact_blank_source recurse: swap nested Interleave plans for their fillers, and rebuild a List/Map column whose plan rebuilds offsets as a one-row empty list or map, zeroing the offsets along with the child (swapping only the child makes try_new report an out-of-range offset). Columns that fall back to Take still need their payload, and the recursion has to stop at FixedSizeList, which indexes children by input_row * size.

compact_blank_source only swaps top-level Interleave columns. A blob v2 column plans as a top-level Struct, so its data child is never swapped; List/Map attaches the child array whole; a nested view child keeps every data buffer of the source column, because that is what Arrow's take_byte_view does.

All of that payload is still attached after slice(0, chunk), and the writer defaults to keep_original_array: false, so deep_copy_buffer copies the whole buffer and the page budget is charged for it. A one-million-row leading deleted run with a 5 MB first blob means roughly 977 blank-only batches, so close to 5 GB of pointless memcpy.

Worth making compact_blank_source recurse: swap nested Interleave plans for their fillers, and rebuild a List/Map column whose plan rebuilds offsets as a one-row empty list or map, zeroing the offsets along with the child (swapping only the child makes try_new report an out-of-range offset). Columns that fall back to Take still need their payload, and the recursion has to stop at FixedSizeList, which indexes children by input_row * size.

compact_blank_source now recurses per plan through compact_for_plan. A nested Interleave column becomes its filler, a List or Map becomes one empty row with zeroed offsets, a Struct recurses per child, and Take/FixedSizeList keep the row since they read it. The List/Map children are freshly allocated empty arrays rather than zero-length slices, so they don't keep the source buffers alive. Each column keeps its type, so blank_plans derives the same plan on the compacted source. test_compact_blank_source_drops_variable_width_payload checks the retained buffer size, not just the length.

Comment thread rust/lance/src/dataset/updater.rs Outdated
if next_deleted_id > last_row_id
|| (next_deleted_id == last_row_id
&& Self::is_full(self.legacy_batch_size, num_rows))
|| (next_deleted_id == last_row_id && num_rows == max_output_rows)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cap is num_rows == max_output_rows. num_rows grows by one per deleted row folded in, so it stops only at the exact moment it equals the max and the next deleted id falls on last_row_id. Once it steps past the max the equality never holds again, and the rest of a contiguous deleted run lands in a single output batch, which is the problem this PR sets out to fix.

That cannot happen today because the reader chunks by physical range: read_all_tasks slices RangeFull by batch_size and wrap_with_row_id_and_delete is a 1:1 map that only filters rows inside a batch, so live rows plus in-range deleted rows stay within batch_size. But the debug_assert! at the top only covers the incoming live count, and the existing tests all walk num_rows up to the max from below.

>= behaves identically today. Pairing that with a debug assert on the real invariant would keep a later change to how the reader chunks from silently disabling it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cap is num_rows == max_output_rows. num_rows grows by one per deleted row folded in, so it stops only at the exact moment it equals the max and the next deleted id falls on last_row_id. Once it steps past the max the equality never holds again, and the rest of a contiguous deleted run lands in a single output batch, which is the problem this PR sets out to fix.

That cannot happen today because the reader chunks by physical range: read_all_tasks slices RangeFull by batch_size and wrap_with_row_id_and_delete is a 1:1 map that only filters rows inside a batch, so live rows plus in-range deleted rows stay within batch_size. But the debug_assert! at the top only covers the incoming live count, and the existing tests all walk num_rows up to the max from below.

>= behaves identically today. Pairing that with a debug assert on the real invariant would keep a later change to how the reader chunks from silently disabling it.

Changed the cap to >= and added debug_assert!(num_rows < max_output_rows) before folding an in-range deleted row, which is the invariant the reader's physical-range chunking guarantees today. Behavior is the same now, but a later change to how the reader batches would trip the assert instead of silently putting the rest of a contiguous run into one batch.

// spec forbids such a field, but Lance's `Field` validation lets it through,
// and the old `take` path never checked. Fall back to copying row zero so
// those maps keep working instead of newly failing on a deleted fragment.
if entries_field.is_nullable() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arrow 58's MapArray::try_new rejects on field.is_nullable() || entries.null_count() != 0, and both fallback checks look at the first one only: blank_plan falls back to Take on entries_field.is_nullable(), and compact_nested_dictionaries returns the array untouched on the same field. A map whose entries field is declared non-nullable but whose entries struct carries a null therefore hits "MapArray entries cannot contain nulls" at either construction site.

Such an array can only arrive through new_unchecked or unvalidated ArrayData, and I did not find a path in Lance that builds one, so reachability is unknown. Adding the array's own null_count() to both checks makes them complete.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arrow 58's MapArray::try_new rejects on field.is_nullable() || entries.null_count() != 0, and both fallback checks look at the first one only: blank_plan falls back to Take on entries_field.is_nullable(), and compact_nested_dictionaries returns the array untouched on the same field. A map whose entries field is declared non-nullable but whose entries struct carries a null therefore hits "MapArray entries cannot contain nulls" at either construction site.

Such an array can only arrive through new_unchecked or unvalidated ArrayData, and I did not find a path in Lance that builds one, so reachability is unknown. Adding the array's own null_count() to both checks makes them complete.

Added the entries array's own null_count() to both checks. blank_plan and compact_nested_dictionaries now fall back when the entries field is nullable or the entries struct carries a null, matching arrow's field.is_nullable() || entries.null_count() != 0. Added test_map_entries_struct_null_copies_row_zero, built unchecked since try_new rejects that shape.

/// Anything that is not the logical `{data, uri, ..}` shape falls back to copying row
/// zero, which is what every blank did before this optimization and is always a valid
/// descriptor.
fn blob_blank_plan(array: &ArrayRef) -> BlankPlan {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blank_plan's doc states that the arrow field and the write field "Both must allow nulls, recursively", and is_nullable plus required_write_child_field follow that. blob_blank_plan takes only the array, and decides whether a non-data child can be nulled from the arrow field's is_nullable() alone. blanks.rs:786 checks both schemas for blob-ness; the plan itself checks one.

Both sides' nullability comes from the same place today and I found no entry point where they diverge, so this is a mismatch between the doc and the implementation rather than a reproducible bug. Passing write_field into blob_blank_plan and intersecting the two nullabilities for non-data children would make the function match its doc.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blank_plan's doc states that the arrow field and the write field "Both must allow nulls, recursively", and is_nullable plus required_write_child_field follow that. blob_blank_plan takes only the array, and decides whether a non-data child can be nulled from the arrow field's is_nullable() alone. blanks.rs:786 checks both schemas for blob-ness; the plan itself checks one.

Both sides' nullability comes from the same place today and I found no entry point where they diverge, so this is a mismatch between the doc and the implementation rather than a reproducible bug. Passing write_field into blob_blank_plan and intersecting the two nullabilities for non-data children would make the function match its doc.

blob_blank_plan now takes write_field and nulls a non-data child only when both the batch field and the write schema allow it, the same rule blank_plan uses. If either side pins a child as required it falls back to Take. As you noted the two sides don't diverge on any path today, so the all-nullable case is unchanged and the existing blob round-trip tests still cover it.

// `last_input` is the state token pairing one successful `next` with one
// successful `update`. Clearing it rejects duplicate updates and lets the
// next input batch advance the restorer exactly once.
self.last_input = None;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.last_input = None is the last statement in update, but restore has already walked the deletion vector and advanced current_row_id before it. Any ? in between leaves last_input set while the restorer has moved on, so feeding the same batch again enters restore a second time and double-counts deleted rows.

All four call sites in the repo propagate the error and drop the updater, so this is unreachable today, and finish's physical_rows reconciliation is a second backstop. DeletionRestorer's own doc already says to drop it and start over; update is pub, so the same sentence belongs on its doc too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.last_input = None is the last statement in update, but restore has already walked the deletion vector and advanced current_row_id before it. Any ? in between leaves last_input set while the restorer has moved on, so feeding the same batch again enters restore a second time and double-counts deleted rows.

All four call sites in the repo propagate the error and drop the updater, so this is unreachable today, and finish's physical_rows reconciliation is a second backstop. DeletionRestorer's own doc already says to drop it and start over; update is pub, so the same sentence belongs on its doc too.

Added to the update doc: after an error the restorer may already have advanced past this batch's deleted rows, so the caller should drop the updater and start over rather than call update or finish again.

/// discard row zero's validity, which `apply_blank_plan` preserves.
/// Choose the blank for one column. Never reached for legacy (v1) files (see
/// [`blank_plans`]); v2.0+ can store a null for every type this plans a null for.
fn blank_plan(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two lines just above the signature, "Choose the blank for one column. Never reached for legacy (v1) files...", are appended straight onto the paragraph about structs with no blank line in between. Rustdoc takes blanks.rs:745 as the summary, so this reads as a second summary sentence buried mid-body.

"Never reached for legacy (v1) files" is the most important precondition this function has and would sit better next to the summary, leaving the struct paragraph on its own.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two lines just above the signature, "Choose the blank for one column. Never reached for legacy (v1) files...", are appended straight onto the paragraph about structs with no blank line in between. Rustdoc takes blanks.rs:745 as the summary, so this reads as a second summary sentence buried mid-body.

"Never reached for legacy (v1) files" is the most important precondition this function has and would sit better next to the summary, leaving the struct paragraph on its own.

Moved those lines up under the summary, so the struct paragraph stands on its own again.

@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 8, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Gate recommendation: approve with a non-blocking risk.

The core fix remains worth accepting: deleted-row placeholders no longer duplicate variable-width values, restored batches stay bounded, and legacy v1 behavior remains unchanged.

Recursive Struct/blob source compaction is improved, but the existing retention concern remains for List/Map variable-width children: zero-length slices retain their backing buffers, which the writer can copy again for each deferred blank batch. Genuinely empty typed children would avoid this residual performance cost.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 8, 2026
Adding or updating columns can fail with an Arrow offset overflow when
a fragment contains many deleted rows and a variable-width column has a
large value in its first live row.

The updater restores deleted physical rows with placeholder values.
Previously every placeholder copied row zero, so large string, binary,
or nested values were repeated for every deleted row.

Every data file in a fragment must have the same physical row count.
Before writing a new column, `DeletionRestorer` therefore inserts blank
rows at deleted positions.

`add_blanks` implemented every blank with `take(0)`. For variable-width
columns this copied the payload of the first live row once per deleted
row. A sufficiently large deletion run could grow the values buffer
past the Arrow offset limit even though those placeholder values are
never visible to readers.

V2 files also appended an unbounded trailing deletion run to the current
output batch, allowing one update batch to become much larger than the
configured batch size.

Choose the cheapest valid blank independently for each column:

- use null when both the dataset write schema and Arrow field are
  nullable and the file version supports nulls;
- use empty values for strings and binary arrays;
- rebuild List, LargeList, and Map offsets without copying child values;
- recursively optimize Struct and FixedSizeList children;
- keep using `take` for fixed-width and dictionary arrays, where copying
  a value does not increase payload size.

Bound restored and deferred blank batches by the updater batch size.
Retain a compact one-row source for layouts that still require `take`,
so trailing deletion runs can be written in bounded chunks without
keeping the original batch payload alive.

The write-schema nullability and exact storage-version policies are
preserved. Zero batch sizes and unfinished deletion restoration now
return descriptive errors.

Add coverage for:

- heavy deletion runs with large binary payloads;
- nullable and non-nullable variable-width columns;
- file-version-specific null support;
- dictionary, List, Map, Struct, and FixedSizeList columns;
- bounded leading and trailing deletion runs;
- dataset write-schema nullability;
- `add_columns` and `update_columns` integration paths;
- zero batch sizes and unaccounted deletions at finish.

Fixes lance-format#8890
@lance-gatekeeper lance-gatekeeper Bot removed K-risk Latest Gatekeeper recommendation includes a non-blocking risk. K-approved Latest Gatekeeper recommendation permits acceptance. labels Oct 8, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Gate recommendation: approve.

The retained-buffer risk from the previous assessment is resolved: List, LargeList, and Map blank sources now use genuinely empty typed children, so deferred blank batches no longer carry the source payload. The deleted-row overflow fix and batch bounds remain intact, with schema nullability and frozen v1 behavior preserved.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 8, 2026
@chenyu-x
chenyu-x requested a review from LuciferYang October 8, 2026 10:46
// `FixedSizeList` indexes its child by `input_row * size` and `Take` copies the row
// outright, so both need the source payload; still GC dictionaries behind them.
BlankPlan::FixedSizeList { .. } | BlankPlan::Take => {
compact_nested_dictionaries(array.clone())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compact_for_plan sends every Take/FixedSizeList column through compact_nested_dictionaries, and its FSL arm rebuilds the array with the checked try_new_with_length even when there's no dictionary inside. Before this PR these columns only went through take, which ends in build_unchecked and never runs that check. Compaction happens on row 0 of the first live batch, so a FixedSizeList<Float32> that declares its item non-nullable but has a null in row 0 used to write fine and now fails with Found unmasked nulls for non-nullable FixedSizeListArray field "item", as long as the fragment has deletions after that batch.

pyarrow and the FFI import both accept such an array. I reproduced this with add_columns on V2_2: base writes it, head fails, and with the null in row 3 instead both succeed.

Returning early from compact_nested_dictionaries when the data type has no Dictionary anywhere inside should fix it. Vector columns then skip the rebuild and behave like the old take.

/// over 2 GiB of allocation, which is not something a unit test should do. Keeping
/// the buffer flat is what makes the overflow unreachable at any scale.
#[test]
fn test_heavy_deletion_blanks_cost_no_payload_bytes() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The doc comment on test_heavy_deletion_blanks_cost_no_payload_bytes says reproducing the offset overflow needs over 2 GiB of allocation, so the test only checks the mechanism. That isn't the case: Arrow's take_bytes checks each offset as it accumulates and returns OffsetOverflowError before it allocates any values. With 2111 rows, a 1 MiB value in row 0 and rows 1..=2100 deleted, add_columns on base hits the #8890 error (Failed to add blanks: Offset overflow error) in 0.03 s and about 83 MB RSS on a debug build, and head writes it.

None of the e2e tests writes a V2_0 dataset, and #8890 is update_columns on v2.0. A V2_0 case like this, ideally through update_columns, would cover the actual bug, and the doc comment can be fixed in the same change. I'd use about 3 MiB for the value so one default 1024-row batch of copies still reaches 2 GiB. At 1 MiB it only fails on base because base also folds the whole deleted run into one batch, so a regression in blank selection alone wouldn't trip it.

@@ -0,0 +1,1087 @@
// SPDX-License-Identifier: Apache-2.0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

praise: Thanks for splitting this out. The planning and materialization code now has a clear home and updater.rs is easier to follow.

@wjones127
wjones127 merged commit 0402c08 into lance-format:main Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

update_columns on a heavily deleted fragment fails with "Failed to add blanks: Offset overflow error"

3 participants