Skip to content

feat(compaction)!: repack a fragment's columns as a compact_files task - #9604

Merged
wjones127 merged 99 commits into
lance-format:mainfrom
LuciferYang:feat/horizontal-compaction
Nov 16, 2026
Merged

wjones127 merged 99 commits into
lance-format:mainfrom
LuciferYang:feat/horizontal-compaction

Conversation

@LuciferYang

@LuciferYang LuciferYang commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #9705, which added data_change to the format.

What's wrong today?

Each add_columns backfill gives every fragment another data file, which slows scans and random reads. compact_files never merges them: it picks fragments with many deletions or overlays, or few rows (#4286, #3995).

What does this change?

compact_files can 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_fragment files (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.

scope limits a run to rewrites or repacks, and repacks are budgeted after rewrites. ForceBinaryCopy plans no repacks, and a repack-only run with no limit or under ForceBinaryCopy is refused.

How does a repack commit?

commit_compaction commits rewrites as one Rewrite, then repacks as one DataReplacement { 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 an add_columns makes it retry. The planner's fragment reuse index checks apply only to runs that rewrite.

DataReplacement now takes several groups per fragment, and what it does to a fragment's files is one pure function, Fragment::replace_files, shared by build_manifest and the planner.

Breaking changes

Rust code that builds these with a struct literal stops compiling:

  • Operation::DataReplacement gains a required data_change: bool; true keeps the old behavior.
  • TaskData gains kind, RewriteResult gains repacked_files, and CompactionOptions gains max_data_files_per_fragment and scope. Use TaskData::rewrite_fragments or repack_columns, repacked_files: None and ..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

How is it tested?

Test What it pins
repack_collapses_backfilled_files, repack_keeps_the_biggest_file backfilled files collapse in one commit, values and fragment ids unchanged; the layout over a limit of 2; a second run commits nothing
repack_keeps_deletions, repack_columns_preserves_data_overlay, repack_keeps_scalar_index, repack_columns_preserves_vector_index deleted rows keep their base values; overlays still shadow; BTree and IVF_PQ keep uuid and coverage and return the same rows
index_built_across_a_repack an index built before a repack keeps its coverage; a visible in-place update withdraws its fragment; a cleaned-up update or a Merge withdraws every repacked fragment
repack_against_concurrent_*, test_conflicts_data_replacement which concurrent changes a repack commits over and which make it retry
compaction_rewrites_and_repacks_in_one_run, commit_rejects_a_fragment_in_both_kinds_of_task, repack_commits_after_its_read_version_is_expired a mixed run commits Rewrite then DataReplacement; a fragment in both is refused; the repack still commits after its read version is expired
repack_never_adds_a_file, repack_merges_only_files_it_empties, the lineage, blob, V1 and struct-header cases the merge rules
compaction_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_budget defaults, refusals and the byte budget
test_undrained_fri_allows_a_repack_only_plan, test_defer_index_remap_allows_a_repack_only_plan a repack-only plan isn't refused for pending remaps, with or without stable row ids, under RepackColumns or All
task_data_without_kind_rewrites_fragments, rewrite_result_without_repacked_files_is_a_rewrite, repack_tasks_run_distributed, testDeserializeTaskAndResultFromOlderVersion (Java) older tasks and results read as rewrites; repack tasks survive serde and commit together
test_data_replacement_data_change_roundtrips, test_data_replacement_applies_several_groups_to_one_fragment, test_data_replacement_data_change_round_trips (Python) data_change round-trips and only true withdraws coverage; several groups apply to one fragment
test_compact_files_repacks_columns, test_distributed_repack, test_repack_options_*, test_commit_leaves_dataset_at_the_rewrite_when_the_repack_fails (Python), testRepackColumns (Java) options, table config, task kind and layout stats through the bindings; the Python handle follows a landed rewrite

The repack task writes files the way @dshepelev15's #9291 did, and Dataset::column_layout_stats started in @Xuanwo's #8614. Thanks to both.

Co-authored-by: dshepelev15 [email protected]
Co-authored-by: Xuanwo [email protected]

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.
@github-actions

Copy link
Copy Markdown
Contributor

ACTION NEEDED
Lance follows the Conventional Commits specification for release automation.

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.
@LuciferYang LuciferYang changed the title Horizontal compaction via a pluggable compaction pipeline (overview) horizontal compaction via a pluggable compaction pipeline (overview) Sep 29, 2026
@LuciferYang

Copy link
Copy Markdown
Contributor Author

@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 add_columns backfills leave a fragment split across many per-column files, which slows scans and random reads, and compact_files can't help because it's vertical and its candidate check never looks at per-fragment file count. Horizontal compaction repacks a fragment's columns into fewer files without moving rows, so indices and row addresses stay valid.

Two things you each asked for shaped the design:

Correctness rests on committing horizontal compaction as Operation::Update{RewriteColumns} with an empty fields_modified, reusing the existing transaction path instead of adding a new Operation. Empty means index-maintenance prunes nothing (coverage kept) and overlay tombstoning is a no-op (overlays carried forward, still shadowing). I tested the parts that were only argued before: a vector index keeps its uuid and coverage across a rewrite of the indexed column and returns the same KNN; a data overlay survives a rewrite of an unrelated column; the file count drops from three to one after two backfills.

Layout of the stack:

A couple of things I'd rather settle with you than alone:

  • Dataset::rewrite_columns reuses the RewriteColumns name that merge-insert already uses for a different operation. Keep it for continuity with feat: keep column groups through compaction and add rewrite_columns #9291, or rename (say repack_columns) to avoid the collision?
  • The framework keeps vertical and horizontal as separate entries committing their own operation, rather than one planner emitting both task kinds (which would need a CompactionPlan wire-format change). Does that match what you had in mind, or did you want the unified planner?

Review of #9606 and #9605 would be much appreciated; #9604 has the full context for the direction question.

@LuciferYang LuciferYang changed the title horizontal compaction via a pluggable compaction pipeline (overview) feat: horizontal compaction via a pluggable compaction pipeline (overview) Sep 29, 2026
@github-actions github-actions Bot added the enhancement New feature or request label Sep 29, 2026
@LuciferYang
LuciferYang marked this pull request as ready for review September 29, 2026 14:31

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 29, 2026
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).
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 29, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Sep 29, 2026
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.
@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Sep 29, 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 29, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 2, 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 Oct 2, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

…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
lance-gatekeeper[bot]

This comment was marked as outdated.

@LuciferYang

Copy link
Copy Markdown
Contributor Author

#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
lance-gatekeeper[bot]

This comment was marked as outdated.

…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

@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.

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 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.

Thanks for working through all of the last round. All four points from my previous review are done:

  • column_groups is 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 both build_manifest and the planner.
  • TaskData::repack_columns builds repack tasks.
  • Python's DataReplacement has data_change and 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,

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.

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.

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.

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?;

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: 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.

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.

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")]

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.

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.

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.

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 {

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: 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.

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.

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();

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: 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 {

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: 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 {

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: 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
@LuciferYang

Copy link
Copy Markdown
Contributor Author

friendly ping @wjones127 Can we merge this first so that I can move forward with the follow-up?

@LuciferYang

Copy link
Copy Markdown
Contributor Author

Thank you @wjones127 @Xuanwo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-docs Documentation A-java Java bindings + JNI A-python Python bindings breaking-change enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants