Skip to content

feat(transaction): make ApplyState reusable across staged transaction steps - #11203

Open
geruh wants to merge 3 commits into
lance-format:will/transaction-v2-action-constructorsfrom
geruh:feat/reusable-apply-state
Open

geruh wants to merge 3 commits into
lance-format:will/transaction-v2-action-constructorsfrom
geruh:feat/reusable-apply-state

Conversation

@geruh

@geruh geruh commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This prepares ApplyState for staged transactions, where each operation needs to see earlier changes before the transaction commits.

ApplyState now owns its working state and supports applying checked steps and building intermediate manifests. Failed checked steps leave the previous state unchanged. Repeated manifest builds preserve row ID allocations and reservations.

Fragment patches and shared bookkeeping avoid copying the base fragment list for every step. Validation tracks changes since the last successful check, and later steps can supply newly loaded spilled row lineage.

The existing CompositeOperation commit path uses the same application and manifest building code.

Stacked on #11014. The dataset-level staged transaction API follows separately.

note: temporarily pointing to above branch :)

Why incremental state and validation

If each staged step clones the full Vec<Fragment> and runs a full build_manifest to validate, staging k steps on a n-fragment table costs O(k * n) even when each step only appends or touches a few fragments.

flowchart LR
  S0["ApplyState (Arc base fragments)"] -->|"apply_step_checked"| C["Clone Arcs + apply step"]
  C -->|"fragments / indices / reservations only"| V1["Validate UnvalidatedScope.dirty_fragments"]
  C -->|"schema / config / FRI / MemWAL / legacy blob"| V2["Fallback: build_manifest"]
  V1 -->|"Ok"| S1["Keep new ApplyState"]
  V2 -->|"Ok"| S1
  V1 -.->|"Err"| S0
  V2 -.->|"Err"| S0
Loading

WorkingFragments keeps base fragments shared behind Arc and tracks edits in a BTreeMap patch set (with lazy DropField masking), so cloning ApplyState for rollback safety and checking touched fragments scales with the staged edits rather than base table size.

Testing

  • git diff --check
  • cargo fmt --all -- --check
  • CARGO_INCREMENTAL=0 cargo clippy -p lance-table -p lance --tests --benches --no-deps -- -D warnings
  • CARGO_INCREMENTAL=0 cargo test -p lance-table --lib
  • CARGO_INCREMENTAL=0 cargo test -p lance-table --doc
  • CARGO_INCREMENTAL=0 cargo test -p lance --lib dataset::tests::dataset_transactions
  • CARGO_INCREMENTAL=0 cargo test -p lance --lib io::commit::conflict_resolver::tests

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

@github-actions github-actions Bot added A-java Java bindings + JNI enhancement New feature or request labels Nov 17, 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 Nov 17, 2026
@geruh
geruh force-pushed the feat/reusable-apply-state branch from 9738c6b to 8f5839a Compare November 17, 2026 21:41
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 17, 2026
@geruh
geruh changed the base branch from main to will/transaction-v2-action-constructors November 17, 2026 21:44
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 17, 2026
#[derive(Clone)]
enum AddedFragment {
Present(u64),
Removed { fresh_row_ids: u64 },

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.

This keeps the row IDs of later staged fragments unchanged when an earlier fragment is removed. An intermediate manifest may already have exposed those IDs.

Comment on lines +529 to +540
fn tombstone_dropped_field(&mut self, field_id: i32, schema: &Schema) -> Result<()> {
Arc::make_mut(&mut self.dropped_fields).insert(field_id);
if self.patched.is_empty() {
return Ok(());
}
let single = BTreeSet::from([field_id]);
let live = schema_field_ids(schema);
for patched in self.patched.values_mut().flatten() {
tombstone_fields_in_fragment(Arc::make_mut(patched), &single, &live)?;
}
Ok(())
}

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.

This applies drops to patched fragments now and defers masking base fragments until they are read or assembled. V1 files keep their field positions until every field in the file has been dropped.

}
self.unvalidated = UnvalidatedScope::default();

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.

This scope includes changes from earlier unchecked steps too. We clear it only after validation succeeds so a later checked step cannot overlook them.

Comment on lines +712 to +740
pub fn extend_spilled_row_lineage(&mut self, loaded: &SpilledRowLineage) -> Result<()> {
if loaded.is_empty() {
return Ok(());
}
if self.spilled_row_lineage.is_empty() {
self.spilled_row_lineage = Arc::new(loaded.clone());
return Ok(());
}
let mut updates = Vec::new();
for (&fragment_id, incoming) in loaded {
match self.spilled_row_lineage.get(&fragment_id) {
Some(existing) => {
let (merged, added) =
merge_loaded_row_lineage(existing, incoming, fragment_id)?;
if added {
updates.push((fragment_id, merged));
}
}
None => updates.push((fragment_id, incoming.clone())),
}
}
if !updates.is_empty() {
let map = Arc::make_mut(&mut self.spilled_row_lineage);
for (fragment_id, merged) in updates {
map.insert(fragment_id, merged);
}
}
Ok(())
}

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.

Later steps may need lineage that earlier steps never loaded. Entries can be partial, so this fills missing sequences while preserving existing ones. The caller must load them from the base version.

@geruh
geruh force-pushed the feat/reusable-apply-state branch from 8f5839a to 7ab301e Compare November 17, 2026 22:04
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 17, 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 restack onto #11014 preserves the fragment-reuse source-state guard from #8646. The reusable-state assessment is unchanged.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 17, 2026
@geruh

geruh commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Local Criterion benchmarks (cargo bench --profile release-with-debug) for why WorkingFragments + incremental validation matters on large tables:

  1. 1,000 sequential apply_step_checked appends, comparing naive owned ApplyState (full Vec<Fragment> clone + build_manifest per step, commit 486666387) vs WorkingFragments + incremental validation (commit d5969abea):
Base Table Fragments Naive Owned ApplyState (486666387) WorkingFragments + Incremental Check (d5969abea)
10,000 1.91 s 15.70 ms
100,000 26.95 s 15.55 ms
  1. Scaling by staged transaction length on a 100,000-fragment base table (793269ce9 single-step, d5969abea cumulative), showing per-step cost grows with staged edits rather than base table size:
Benchmark (100,000 Base Fragments) Point Estimate
Single apply_step_checked after 0 prior steps 1.02 µs
Single apply_step_checked after 100 prior steps 3.86 µs
Single apply_step_checked after 1,000 prior steps 31.89 µs
Single apply_step_checked after 5,000 prior steps 174.94 µs
Cumulative 100 checked append steps 271.48 µs
Cumulative 500 checked append steps 4.29 ms
Cumulative 1,000 checked append steps 16.42 ms
Cumulative 2,000 checked append steps 63.68 ms

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. and removed K-approved Latest Gatekeeper recommendation permits acceptance. labels Nov 17, 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.

Thanks Drew, this is a nice step toward staged transactions. Making ApplyState own its state with copy-on-write fragments is a clean way to reuse it across steps, and the benchmarks make a clear case for the incremental path. The per-step snapshot-vs-single-build test gives me a lot of confidence the commit path still produces the same manifest.

Nothing here blocks, since the module is experimental. Encouraged:

  • Row id contract (most important). Burned slots keep intermediate row ids stable while staging, but a retry renumbers them. I'd like to settle what callers may rely on before the dataset-level API builds on it.
  • API surface. The build config comes in at four places, and apply_step/validate_step_invariants duplicate apply_step_checked. Narrowing both would leave one way to do each thing.
  • Smaller items: a submodule for WorkingFragments, and a couple of nits.


/// One fragment this operation added, in the order it was added.
///
/// A removed fragment keeps its slot because an intermediate manifest build may

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: What's the contract for row ids a caller sees in an intermediate manifest? This keeps them stable while staging, but on a retry the rebase renumbers them anyway. In the rebase test, the staged fragment's ids move from 1000..1010 to 1010..1020:

let rebased_ids: Vec<u64> = rebased.fragments.iter().map(|f| f.id).collect();
assert_eq!(rebased_ids, vec![0, 1, 2, 3, 4]);
assert_eq!(
inline_row_ids(rebased.fragments.iter().find(|f| f.id == 3).unwrap()),
(1010..1020).collect::<Vec<_>>()
);
assert_eq!(
inline_row_ids(rebased.fragments.iter().find(|f| f.id == 4).unwrap()),
(1020..1030).collect::<Vec<_>>()
);
assert_eq!(rebased.next_row_id, 1030);

So anything a later step persists against those ids (say an index segment over a staged fragment on a stable row id table) would be wrong after a retry. If the staged API will rely on these ids, I think a retry needs to detect that and fail rather than renumber. If it won't, do we need the burned slots at all? They also change the one-shot CompositeOperation path: adding and then removing a fragment in one operation now uses up its 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.

yeah this was an important point in the transaction layer anything that reads or depends on intermediate row ids pins read_version so a concurrent commit fails instead of renumbering on retry

we still need the burned slots even without retries though. if step 1 adds frag A, step 2 adds frag B and the caller reads its row ids, and step 3 removes frag A, frag B needs to keep the same row ids in step 3 and the final commit. added a doc note on ApplyState explaining this

@wjones127
wjones127 force-pushed the will/transaction-v2-action-constructors branch from c7965e8 to 840f6eb Compare November 18, 2026 01:46
@geruh
geruh force-pushed the feat/reusable-apply-state branch from 7ab301e to 25891e3 Compare November 18, 2026 18:55
/// # }
/// ```
#[derive(Clone)]
pub struct ApplyState {

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.

thoughts: I wonder if it would be cleaner to call this the working state of a manifest or dataset like: ManifestWorkingState. Since the functions are technically modifying the state of a manifest

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.

It's a little long, but I agree it's better than ApplyState. 👍

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.

thought: A shorter option with the same idea: WorkingManifest. It pairs with WorkingFragments, and .build() would then read well. Your call, though. ManifestWorkingState is also fine.

@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 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.

Thanks Drew, this addresses everything I raised. LGTM.

/// # }
/// ```
#[derive(Clone)]
pub struct ApplyState {

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.

thought: A shorter option with the same idea: WorkingManifest. It pairs with WorkingFragments, and .build() would then read well. Your call, though. ManifestWorkingState is also fine.

@wjones127
wjones127 force-pushed the will/transaction-v2-action-constructors branch from 840f6eb to 66eb547 Compare November 30, 2026 17:54
@geruh
geruh force-pushed the feat/reusable-apply-state branch from 21745ec to 2798da3 Compare November 30, 2026 20:14
@wjones127
wjones127 force-pushed the will/transaction-v2-action-constructors branch from de69e45 to 7acc64d Compare December 1, 2026 19:11
@geruh
geruh force-pushed the feat/reusable-apply-state branch from 2798da3 to 0394862 Compare December 1, 2026 23:32

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-java Java bindings + JNI enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants