Repository navigation
feat(compaction)!: repack a fragment's columns as a compact_files task - #9604
Conversation
Repack a fragment's per-column data files into fewer files without moving rows. Adds CompactionExecutor/CompactionCommitter traits (vertical reuses the existing rewrite path), a horizontal RewriteColumns path committing Operation::Update with an empty fields_modified (indices and overlays preserved), column_layout_stats, and a compaction column_groups option.
Add a generic run_compaction_pipeline<E,C> that both vertical and horizontal compaction run through, so the traits are a real plug point. Route Dataset::rewrite_columns through it (bounded concurrency, no bespoke cleanup). Surface a missing fragment and an uncovered indexed column as errors instead of silently miscounting or dropping a seed. Add tests for column_groups seed routing (ZoneMap), split-preserved-across-compaction, config parsing, and index/overlay preservation.
|
ACTION NEEDED The PR title and description are used as the merge commit message. Please update your PR title and description to match the specification. For details on the error please inspect the "PR Title Check" action. |
Per-fragment count of data files still holding a live field, plus overlay count, read from fragment metadata only. This is the planning input for horizontal compaction and keeps the decision observable.
|
@wjones127 @Xuanwo, picking up the horizontal-compaction thread (#4286, discussion #3995, and the stalled #9291). I built the whole thing out on a branch and split it into reviewable PRs; here's where it stands. The gap, restated: repeated Two things you each asked for shaped the design:
Correctness rests on committing horizontal compaction as Layout of the stack:
A couple of things I'd rather settle with you than alone:
Review of #9606 and #9605 would be much appreciated; #9604 has the full context for the direction question. |
…paction # Conflicts: # rust/lance/src/dataset/optimize.rs
RewriteColumnsCommitter committed against the current manifest version, so in the distributed path a fragment changed between its read and the commit would slip past the conflict check. Carry each rewrite's read version in RewriteColumnsResult and commit against the minimum, mirroring vertical compaction's RewriteResult::read_version. Single-machine rewrite_columns is unaffected (read version == commit version).
Regression test for the read-version binding: a rewrite read at V, committed after a delete lands on the same fragment at V+1, must conflict rather than resurrect the deleted row. Guards the fix so the distributed commit path cannot silently regress.
…paction # Conflicts: # java/lance-jni/src/blocking_dataset.rs # java/src/main/java/org/lance/ColumnLayoutStatistics.java # python/python/lance/dataset.py # rust/lance/src/dataset/compaction_stats.rs # rust/lance/src/dataset/optimize.rs # rust/lance/src/index.rs
|
#9605 has also been merged. @Xuanwo @wjones127 Could you take another look when you have time? Thanks ~ |
…paction # Conflicts: # java/lance-jni/src/optimize.rs # java/src/main/java/org/lance/compaction/CompactionOptions.java # python/python/lance/lance/optimize.pyi # rust/lance/src/dataset/optimize.rs # rust/lance/src/io/commit/conflict_resolver.rs
…paction # Conflicts: # java/lance-jni/src/optimize.rs # java/lance-jni/src/utils.rs # java/src/main/java/org/lance/compaction/Compaction.java # java/src/main/java/org/lance/compaction/CompactionOptions.java # java/src/test/java/org/lance/CompactionTest.java # python/python/lance/_dataset/optimize.py # python/src/dataset/optimize.rs # rust/lance-table/src/transaction/manifest_build.rs # rust/lance/src/dataset/optimize.rs # rust/lance/src/dataset/optimize/planning.rs # rust/lance/src/dataset/optimize/tests.rs
There was a problem hiding this comment.
✅ Gate recommendation: approve.
Repacking through compact_files addresses the files left by repeated backfills while preserving physical values, row identity, deletions and overlays. The planner admits rewrite tasks before repacks under the shared source budgets; use scope="repack_columns" to budget repacks independently. Their byte accounting includes only the data files they read.
Index builds retain coverage across repacks when a complete checked history proves values stayed unchanged. The snapshot-based cleanup checks remain conservative: history gaps, retries, an intervening Merge or publishing prebuilt segments can withdraw coverage, with affected rows scanned until coverage is rebuilt.
Rewrites and repacks commit separately. The original handle lets repacks commit after the planning manifest expires; if repacking fails, the rewrite remains committed. Replan instead of resubmitting those results. The overlapping-value protections continue to reject stale repacks that would overwrite newer values.
Layout statistics #9605 is merged into the base. Broader grouping across write operations remains in #10509.
Please mark this PR with the breaking-change label: Rust lance::dataset::optimize::{CompactionOptions, TaskData, RewriteResult} gain fields, and lance_table::transaction::Operation::DataReplacement gains data_change, so downstream Rust callers must update struct literals and exhaustive patterns.
wjones127
left a comment
There was a problem hiding this comment.
Thanks for working through all of the last round. All four points from my previous review are done:
column_groupsis gone, with #10509 filed for the version that applies to every write.- The file-layout rule now lives in one pure
Fragment::replace_files, used by bothbuild_manifestand the planner. TaskData::repack_columnsbuilds repack tasks.- Python's
DataReplacementhasdata_changeand a round-trip test.
Xuanwo's deleted-rows catch is fixed too. The repack now clears the deletion file before reading, and repack_keeps_deletions compares an include_deleted_rows scan.
Approving. The remaining comments are non-blocking:
- Breaking change: please list what breaks in the PR description.
- FRI gate: repack-only runs are still refused on tables without stable row ids that have pending remaps.
- Test gap: a visible in-place update before a repack isn't covered.
- Repack triggers: a question about what should cause a repack to be planned, and a request to document it.
| /// were only moved to new files (a compaction repack): indices keep | ||
| /// their coverage of the replaced fields, overlays keep shadowing, and | ||
| /// no row is stamped as updated. | ||
| data_change: bool, |
There was a problem hiding this comment.
chore: I'm marking this as breaking (! in the title). Could you add a short "Breaking changes" section to the PR description listing them? Operation::DataReplacement gets a required field, and TaskData, RewriteResult and CompactionOptions gain public fields, so downstream code that builds any of these with a struct literal stops compiling. That description becomes the squash commit, so release notes can pick it up from there.
There was a problem hiding this comment.
Added a "Breaking changes" section listing the new data_change field on Operation::DataReplacement and the new public fields on TaskData, RewriteResult and CompactionOptions, with what to write instead. The Java and Python changes only add API.
| @@ -1409,6 +1541,37 @@ impl DefaultCompactionPlanner { | |||
| reject_eager_remap_over_undrained_fri(dataset).await?; | |||
There was a problem hiding this comment.
issue: The two stable-row-id checks above now skip a repack-only run, but this one doesn't look at scope: on a table without stable row ids, !uses_stable_row_ids() is true, so it always runs. A table that ran a defer_index_remap compaction earlier and still has pending remaps then gets "Cannot eagerly compact..." from scope="repack_columns", even though a repack moves no rows. test_undrained_fri_allows_a_repack_only_plan only covers a stable-row-id table.
Relatedly, all three checks key off scope, while compact_files_with_planner keys its FRI check off whether the plan actually has a rewrite task. So under the default scope=All, a run that turns out to be repack-only is still refused.
What if we ran plan_rewrites first and only ran these checks (and computed eager_remap_capable) when it returned tasks? Then that test could be parameterized over stable row ids.
There was a problem hiding this comment.
Done as you suggested. plan_with_budget now plans first and runs the three checks only when the budget-limited plan holds a rewrite task, which is what compact_files_with_planner keys its check on. test_undrained_fri_allows_a_repack_only_plan now runs with and without stable row ids, under RepackColumns and All; with the old scope-keyed checks, three of the four cases fail. A run that plans no rewrite at all (say, a Hard budget blocking the first one) is no longer refused for a pending FRI; nothing is written in that case.
| #[rstest] | ||
| #[case::nothing(BeforeTheRepack::Nothing, vec![0, 1], "d = 6")] | ||
| #[case::cleaned_up_update(BeforeTheRepack::CleanedUpUpdate, vec![], "d = 100")] | ||
| #[case::in_place_merge(BeforeTheRepack::InPlaceMerge, vec![], "d = 100")] |
There was a problem hiding this comment.
suggestion: Could we add a case here for an in-place update that is not cleaned up? Commit a RewriteColumns update of d on fragment 0 at a visible version, then run the repack, and expect coverage [1].
In the finish, keep_unmoved_rewrites drops d on fragment 0 from the withdrawal because its current file is the repacked one, so this case relies on the CreateIndex check's Update arm having already pruned it. That's the usual ordering, and right now only the cleaned-up and Merge variants are pinned.
There was a problem hiding this comment.
Added as visible_update: an in-place RewriteColumns update of d on fragment 0 at a visible version, then the repack, and the index commits with coverage [1]. Skipping the CreateIndex check's Update arm makes it fail with [0, 1].
| dataset: &Dataset, | ||
| rewritten: &HashSet<u64>, | ||
| ) -> Result<Vec<(TaskData, usize)>> { | ||
| let Some(max_files) = self.options.max_data_files_per_fragment else { |
There was a problem hiding this comment.
question: With scope="repack_columns" and no max_data_files_per_fragment, this run plans nothing, and compaction_plans_no_repack_by_default pins that behavior. As it stands, that looks like a trap for someone who asked only for repacks and forgot the limit.
But I can see it making sense if there are other triggers. For example, after an in-place column rewrite, a fragment's files carry tombstoned columns that are dead in the latest version. That's dead weight in columnar form, much like a lot of deletions, and it could be worth repacking even when no file-count limit is set.
What triggers do you have in mind for planning a repack, now or later? Whatever they are, could the docs list the conditions that cause one to be planned? Then a run that plans nothing is explainable.
There was a problem hiding this comment.
For now the file count is the only trigger. The docs now say so and list when a fragment over the limit is still left alone, and scope="repack_columns" without the limit, or under ForceBinaryCopy, is refused at validation. That can be relaxed once a second trigger exists. Dead slots are a good candidate, and column_layout_stats already reports dead_slot_ratio, but slots aren't bytes and a dead slot in a file with live columns needs a one-file rewrite the planner doesn't plan today, so I filed #11035 for it.
| .unwrap_or_default(); | ||
| // Several groups may name the same fragment (one new file | ||
| // each); they apply to it in order. | ||
| let mut new_files_by_fragment: BTreeMap<u64, Vec<DataFile>> = BTreeMap::new(); |
There was a problem hiding this comment.
praise: Nice. Grouping by fragment and applying replace_files once per fragment also fixes a latent bug in the old arm: two groups naming the same fragment each started from a fresh clone of it, and both got pushed, so the manifest would have listed that fragment twice.
| // A run that rewrites and repacks commits them separately. If the | ||
| // repack commit fails or is interrupted, `new_ds` is at the rewrite's | ||
| // version, which has landed. | ||
| if new_ds.manifest.version != dataset.ds.manifest.version { |
There was a problem hiding this comment.
praise: Good call updating the handle when the rewrite landed but the repack commit failed. Otherwise the Python object would silently sit a version behind what's actually committed.
| /// str : ``"rewrite_fragments"`` for a task that rewrites its fragments, | ||
| /// ``"repack_columns"`` for one that repacks its fragment's columns. | ||
| #[getter] | ||
| pub fn kind(&self) -> &'static str { |
There was a problem hiding this comment.
nitpick: Small parity nit: Python exposes a task's kind but not which columns it will repack, while Java exposes TaskData.getRepackFiles() but no kind. Not a big deal, but it would be nice if both bindings showed the same thing.
…te is planned; refuse repack-only runs that plan nothing
|
friendly ping @wjones127 Can we merge this first so that I can move forward with the follow-up? |
|
Thank you @wjones127 @Xuanwo |
Builds on #9705, which added
data_changeto the format.What's wrong today?
Each
add_columnsbackfill gives every fragment another data file, which slows scans and random reads.compact_filesnever merges them: it picks fragments with many deletions or overlays, or few rows (#4286, #3995).What does this change?
compact_filescan also plan a task that repacks one fragment's columns into fewer data files. Rows don't move, so fragment ids, deletions, overlays and index coverage stay.A fragment no rewrite takes is repacked when it holds its columns in more than
max_data_files_per_fragmentfiles (off by default; also table config). This is the only trigger; #11035 tracks dead slots. A repack merges only files it can empty, at least two at a time. Files with a blob column, part of a column or spilled row lineage stay, and V1 fragments are skipped.scopelimits a run to rewrites or repacks, and repacks are budgeted after rewrites.ForceBinaryCopyplans no repacks, and a repack-only run with no limit or underForceBinaryCopyis refused.How does a repack commit?
commit_compactioncommits rewrites as oneRewrite, then repacks as oneDataReplacement { data_change: false }: index coverage of the moved fields stays, overlays keep shadowing, and row versions don't move. A concurrent change to a moved column, a rewrite or delete of the fragment, or anadd_columnsmakes it retry. The planner's fragment reuse index checks apply only to runs that rewrite.DataReplacementnow takes several groups per fragment, and what it does to a fragment's files is one pure function,Fragment::replace_files, shared bybuild_manifestand the planner.Breaking changes
Rust code that builds these with a struct literal stops compiling:
Operation::DataReplacementgains a requireddata_change: bool;truekeeps the old behavior.TaskDatagainskind,RewriteResultgainsrepacked_files, andCompactionOptionsgainsmax_data_files_per_fragmentandscope. UseTaskData::rewrite_fragmentsorrepack_columns,repacked_files: Noneand..Default::default().Older serialized tasks, results and transactions still read, and an older worker rewrites a repack task's fragment instead. Java and Python only add API.
Known limits
Merge. Segments committed withcommit_existing_index_segmentsalways lose it.How is it tested?
repack_collapses_backfilled_files,repack_keeps_the_biggest_filerepack_keeps_deletions,repack_columns_preserves_data_overlay,repack_keeps_scalar_index,repack_columns_preserves_vector_indexindex_built_across_a_repackMergewithdraws every repacked fragmentrepack_against_concurrent_*,test_conflicts_data_replacementcompaction_rewrites_and_repacks_in_one_run,commit_rejects_a_fragment_in_both_kinds_of_task,repack_commits_after_its_read_version_is_expiredRewritethenDataReplacement; a fragment in both is refused; the repack still commits after its read version is expiredrepack_never_adds_a_file,repack_merges_only_files_it_empties, the lineage, blob, V1 and struct-header casescompaction_plans_no_repack_by_default,repack_only_run_that_plans_nothing_is_refused,repack_is_not_planned_under_force_binary_copy,repack_counts_only_the_files_it_reads_against_the_byte_budgettest_undrained_fri_allows_a_repack_only_plan,test_defer_index_remap_allows_a_repack_only_planRepackColumnsorAlltask_data_without_kind_rewrites_fragments,rewrite_result_without_repacked_files_is_a_rewrite,repack_tasks_run_distributed,testDeserializeTaskAndResultFromOlderVersion(Java)test_data_replacement_data_change_roundtrips,test_data_replacement_applies_several_groups_to_one_fragment,test_data_replacement_data_change_round_trips(Python)data_changeround-trips and onlytruewithdraws coverage; several groups apply to one fragmenttest_compact_files_repacks_columns,test_distributed_repack,test_repack_options_*,test_commit_leaves_dataset_at_the_rewrite_when_the_repack_fails(Python),testRepackColumns(Java)The repack task writes files the way @dshepelev15's #9291 did, and
Dataset::column_layout_statsstarted in @Xuanwo's #8614. Thanks to both.Co-authored-by: dshepelev15 [email protected]
Co-authored-by: Xuanwo [email protected]