Skip to content

feat: add physical column layout optimization - #8614

Draft
Xuanwo wants to merge 4 commits into
mainfrom
xuanwo/optimize-columns
Draft

Xuanwo wants to merge 4 commits into
mainfrom
xuanwo/optimize-columns

Conversation

@Xuanwo

@Xuanwo Xuanwo commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Wide datasets that materialize fields independently can accumulate one provider file per field per fragment. This inflates manifests and descriptor traversal, while row compaction is not the right maintenance primitive because it changes row layout and row addresses.

This PR introduces a physical-only OptimizeColumns operation. Callers provide explicit top-level field groups, and Lance rewrites those groups into standard per-fragment data files while preserving logical values, fragment IDs, physical row order, deletion files, stable row IDs, and row-version metadata. A fixed snapshot cutoff materializes visible overlays while newer overlays remain authoritative, and field-level conflict intent allows safe rebasing of disjoint work.

Index coverage is conservatively removed for rewritten fields, including legacy indices whose unknown coverage is recovered during commit. Blob columns reuse the existing rewrite machinery for legacy Blob, Blob v2, nested Blob v2, and external references.

Benchmark

Measured at PR head b308a540 on an EC2 c7i.4xlarge in us-east-2. The dataset has 100,000 rows, 1,000 independently materialized scalar fields, and 64 fragments. Optimization groups 10 fields per output file. Values below are median application-cold full-stream latencies from fresh dataset handles; dataset-open time is measured separately and excluded.

Storage Projection Before After Speedup
Local FS 4 co-located fields 102.3 ms 27.6 ms 3.71x
Local FS 4 scattered fields 91.1 ms 27.1 ms 3.37x
Local FS 100 fields 342.1 ms 191.1 ms 1.79x
Local FS 1,000 fields 11.97 s 3.75 s 3.19x
S3 4 co-located fields 173.2 ms 82.9 ms 2.09x
S3 4 scattered fields 163.8 ms 147.6 ms 1.11x
S3 100 fields 3.20 s 568.2 ms 5.63x
S3 1,000 fields 42.52 s 9.66 s 4.40x

The physical layout shrank from 64,064 to 6,528 live files (-89.8%), while the manifest shrank from 4.78 MB to 1.47 MB (-69.3%). All before/after logical checksums matched.

This is a maintenance operation with a one-time rewrite cost: 58.96 s on local FS and 121.05 s on S3 for this dataset, writing about 418 MB. Grouping also determines read amplification: the deliberately scattered S3 narrow projection improved by only 1.11x while bytes read increased from 1.31 MB to 9.52 MB. Callers should therefore group fields that are commonly read together.

This is an explicit layout-policy API rather than an automatic scheduler. Index coverage may require rebuilding after maintenance, and superseded provider objects remain until normal version retention and cleanup make them collectible. Benchmark harnesses are maintained outside this repository.

@github-actions

Copy link
Copy Markdown
Contributor

Important

This PR touches the Lance format specification.

Substantive changes to the format specification — the .proto definitions
and the spec docs under docs/src/format/ — require a PMC vote before merge.
Minor edits such as typo fixes, wording, or formatting are excluded; use your
judgment.

If this is a meaningful format change:

  • Start a vote following the Lance community voting process.
    Format specification modifications need 3 binding +1 votes (excluding the
    proposer), held on GitHub Discussions, with a minimum voting period of 1 week.
  • Once the vote passes, link the completed vote in this PR. It should not be
    merged until the vote is linked.

@github-actions github-actions Bot added A-format On-disk format: protos and format spec docs enhancement New feature or request labels Aug 18, 2026

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

Providing some high level suggestions for now, since this isn't marked ready for review yet.

Comment thread protos/transaction.proto

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: An alternative simple design would be to just use the existing DataReplacement operation. If you want to represent that fact that values didn't change, you can add a data_change: bool argument that indicates whether data changed or was just moved. The data_change parameter is how I'm implementing this concept in Composite Transactions, so I think it's more aligned with our future roadmap. You can see this in the AddDataFile action here: https://github.com/lance-format/lance/pull/8644/changes#diff-0ad4747ac7f2cd6192e47a4c12b1887a193a66de1d07eb1623518c3fa462c2ffR15-R26

Comment on lines +105 to +107
/// groups: vec![ColumnGroup {
/// fields: vec!["feature_a".into(), "feature_b".into()],
/// }],

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: Instead of having to pass these each time, can we also make this a table configuration? I was making some docs that list all the table config keys, and I noticed we have already added the compaction options there. So I think this might naturally fit amongst those.

Those configs aren't universally enforced, so we should separately make that happen.

}

/// Reorganize selected top-level fields into explicit per-fragment data files.
pub async fn optimize_columns(

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: It would be nice to not have to create a whole new API for this. Ideally this would run in the same compaction jobs. I say this partly to keep API simple. But also if someone is regularly running background maintenance jobs, it's nice to have fewer of those maintenance jobs rather than many separate ones, especially if they might conflict.

Xuanwo pushed a commit that referenced this pull request Oct 26, 2026
This is the format part of #9604, split out the way
[`voting.md`](https://lance.org/community/voting/#lance-format-specification-changes)
asks: the protobuf field, the spec text, and the smallest library change
that keeps the build green. The behavior lands with #9604.

## What changes in the format

`DataReplacement` gets `optional bool data_change = 2`, which says
whether the new files change any value. When it is absent it means true,
which is what every transaction written before the field meant.

With `data_change` false, the writer asserts that the new files hold the
same base values as the files they replace, only laid out in different
files. The commit then keeps index coverage of the replaced fields,
leaves overlays alone because they still hold newer values, and doesn't
move any row's last-updated-at version. A concurrent delete or update
that removes a target fragment, or a `drop_columns` of a replaced field,
makes it retry instead of failing, and a concurrent index build on a
replaced field no longer conflicts with it.

The `DataReplacement` section also gains the rules the spec didn't spell
out:

- one transaction can carry several groups for the same fragment, one
per new file, applied in order, and different groups can carry different
fields;
- each group applies to the fragment as it stands at commit: swap an
exact match, append when none of the fields is covered, otherwise
tombstone the fields where they live and append, and drop a file left
with no schema field and no spilled row lineage;
- a concurrent `Project` that drops a replaced field conflicts, which
the code already does but the spec didn't list.

## Why

Compaction in #9604 repacks a fragment's columns into fewer files. The
values only move, so the three things a replacement does today are wrong
for it: indexes would lose coverage of the fragment for no reason,
tombstoning the overlays would make readers see the older base values
again, and incremental readers would see every repacked row as updated.
@wjones127 suggested this flag on #8614 (r3833888750), to match the
`data_change` on `AddDataFile` in the composite transactions draft
(#8644).

The flag has to live in the transaction file, not only in the commit
call, because concurrent writers read that file to resolve conflicts.
Without it, an index build that races a repack of its column has to
retry.

## Compatibility

A commit with `data_change` false produces a manifest that uses no new
fields, so readers of the table are unaffected.

A library that predates the field reads every replacement as a data
change, as it does today. During conflict resolution that is the
conservative reading: at worst it retries where a newer library
wouldn't. The one case where it reads wrong is when such a library is
handed a serialized `data_change: false` transaction and commits it: it
would tombstone overlays that the moved values don't supersede.
Compaction doesn't do this, because the coordinator builds the
transaction from the task results with its own library.

#9604 writes the field only when it is false, so a data-changing
replacement's transaction file stays the same as today.

## Library change

`proto.rs` ignores the field on read and leaves it unset on write. Until
#9604 lands, every replacement is still applied as a data change, and
the library doesn't yet support several groups for one fragment or
groups with different fields, both of which the spec now allows.
wjones127 pushed a commit that referenced this pull request Nov 16, 2026
#9604)

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

- A run that rewrites and repacks commits two versions until composite
transactions (#8644) land; if the repack fails, the rewrite stays.
- A concurrent index build keeps coverage of repacked fragments only if
its first commit attempt sees every version since its read, none a
`Merge`. Segments committed with `commit_existing_index_segments` always
lose it.
- Grouping columns into files is left to #10509.

## 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]>
@github-actions github-actions Bot added the Stale label Nov 20, 2026
@codecov

codecov Bot commented Nov 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions github-actions Bot removed the Stale label Nov 21, 2026

This branch has not been deployed

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

Labels

A-format On-disk format: protos and format spec docs enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants