Skip to content

feat(transaction): add RewriteManifestsAction for manifest compaction - #2543

Open
SreeramGarlapati wants to merge 13 commits into
apache:mainfrom
SreeramGarlapati:feat/rewrite-manifests
Open

SreeramGarlapati wants to merge 13 commits into
apache:mainfrom
SreeramGarlapati:feat/rewrite-manifests

Conversation

@SreeramGarlapati

@SreeramGarlapati SreeramGarlapati commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

What changes are included in this PR?

Adds RewriteManifestsAction, exposed as Transaction::rewrite_manifests(), mirroring Java's BaseRewriteManifests:

  • groups live DataFile entries by partition tuple within the default partition spec
  • rolls new manifests by target_size_bytes (default 8 MiB, mirrors commit.manifest.target-size-bytes)
  • preserves sequence_number, file_sequence_number, and (v3) first_row_id via ManifestWriter::add_existing_file
  • carries forward total-* summary keys; emits manifests-created, manifests-replaced, manifests-kept, entries-processed
  • commits a Replace snapshot

Why a separate path from SnapshotProducer? The producer cannot emit a Replace snapshot today: update_snapshot_summaries (spec/snapshot_summary.rs:337-346) rejects Operation::Replace, summary keys are driven by added_data_files only (transaction/snapshot.rs:373-379), and ManifestProcess::process_manifests is sync (blocks async manifest writes). Once those land, this action will migrate onto the unified path — tracked in #2556.

Scope (Java-parity ceiling): v1/v2/v3 format versions; knob set is target_size_bytes plus inherited snapshot_properties / commit_uuid / key_metadata. Out of scope: rewrite_if predicate, cluster_by, custom spec_id / staging_location, iceberg-datafusion SQL-procedure layer. Manifests bound to non-default specs and DELETE manifests pass through verbatim.

Are these changes tested?

8 inline unit tests covering: missing current snapshot, single-small-manifest no-op, multi-manifest merge preserves sequence numbers (v2), target-size rolls multiple manifests, v3 row lineage + per-entry (first_row_id, sequence_number, file_sequence_number) preservation, summary + Replace operation, partition grouping + catalog commit, idempotency-after-consolidation. Tested on v2 and v3; the rewrite path is format-version-agnostic by construction (v1 uses the same ManifestListWriter::v1 arm).

  • cargo test -p iceberg (1304 passed, 0 failed)
  • cargo clippy -p iceberg --all-targets -- -D warnings
  • cargo fmt --check
  • make check-public-api

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Jul 19, 2026
SreeramGarlapati and others added 13 commits July 20, 2026 06:34
Mirrors Java BaseRewriteManifests semantics: groups DataFile entries by
partition tuple within a single (default) partition spec, rolls new
manifests by target size, and commits a Replace snapshot that preserves
sequence numbers, file_sequence_numbers, and (v3) row lineage via
ManifestWriter::add_existing_file.

Knob set matches Java parity ceiling exactly:
- target_size_bytes (default 8 MiB, per commit.manifest.target-size-bytes)
- snapshot_properties, commit_uuid, key_metadata via builder
…rflow

- Read target size from `commit.manifest.target-size-bytes` table property
  (default 8 MiB), matching Java's default.
- Add Spark-action-style no-op short-circuit: skip when input would already
  fit in a single target-sized manifest (target_num_manifests == 1 && len == 1).
- Promote `generate_unique_snapshot_id` to a free fn in `transaction::snapshot`
  and fix `i64::MIN` overflow by masking with `i64::MAX` instead of negating.
- Trim builder surface (drop `key_metadata`, rename `with_*` -> `set_*`),
  drop redundant defensive invariants, ensure user snapshot_properties go in
  before internal counter keys so the latter can't be clobbered.

cargo test -p iceberg --lib (1302 tests pass), clippy clean, public-api regen.
Apply review-farm pass-2 findings:

- Fix size-rolling proxy (perf BLOCKER): switch from `data_file.file_size_in_bytes`
  (parquet bytes) to a constant `APPROX_BYTES_PER_ENTRY = 256` (manifest entry
  serialization estimate). Java rolls on `ManifestWriter.length()`; using the data
  file size was off by 2-3 orders of magnitude and made target-size meaningless.
- Concurrent manifest loads via `buffer_unordered(16)` + `try_collect` instead of
  sequential `for-await`. Big win on tables with many manifests.
- Drop full `ManifestEntry` clone — store only `(DataFile, snap_id, seq, file_seq)`
  per group to halve the allocation churn during regrouping.
- Drop unused `set_commit_uuid` public API + `commit_uuid` field; uuid is generated
  inline now.
- Drop dead `SnapshotProducer::generate_unique_snapshot_id` pass-through.
- Use `u64::try_from` (not `as u64`) for the manifest_length sum to avoid silent
  wrap on negative values.
- Doc the explicit-subset scope (no rewriteIf, no clusterBy, no specId, no branch
  override; only default-spec data manifests rewritten).
- Doc the `total-*` carry-forward invariant (rewrite-only -> identity).
- Drop `Vec::with_capacity` micro-opts where the input size is small.
- Replace `RangeFrom`-with-`.next().unwrap()` counter with a plain `u64 += 1`
  closure helper.
- Add test_partition_grouping_and_catalog_commit: verifies parent_snapshot_id,
  sequence_number = prev+1, and per-manifest partition tuple homogeneity.
- Adjust test_target_size_rolls_multiple_manifests target to match the new
  per-entry proxy.

cargo test -p iceberg --lib (1303 tests pass), clippy clean.
- trim doc-comment blocks (one-line per item); fold memory-ceiling caveat into struct doc
- inline next_writer closure; capture manifests_replaced before stream; move into stream::iter
- avoid partition-tuple clone on existing-key lookup (get-then-insert)
- lift file_io.new_output() out of FormatVersion match to remove triple clone of manifest_list_path
- inline META_ROOT_PATH constant (used twice)
- let-else for AddSnapshot pattern in test_summary_and_replace_operation
- add test_idempotent_after_consolidation (multi-manifest -> 1 -> no-op on rerun)
- extend test_v3_row_lineage_preserved to assert (sequence_number, file_sequence_number, first_row_id) per-entry
Snapshot::load_manifest_list was removed in apache#2541 in favor of
Table::manifest_list_reader. Update production code and tests to
match. Build was broken on the merge commit; this restores green CI.
…rbatim

Restore the original `if id < 0 { -id }` algorithm and drop the doc
comment. The visibility lift (private associated method →
`pub(crate)` free function) stays so RewriteManifestsAction can share
the helper, but the body is now byte-for-byte identical to upstream.
Synthesized 8-persona review pass:
- Derive bytes_per_entry from input manifests (was hardcoded 256);
  reviewer-empathy BLOCKING fix.
- Trim doc/inline comments to address over-commenting feedback.
- Iterator::partition for kept/to_rewrite split; pre-sized via partition.
- Drop EntryRecord type alias and manifests_* named temporaries.
- u64::try_from for first_row_id (drops dead frid >= 0 guard).
- Tests: rename _v2_ off the v3 test; assert snap_id != parent;
  assert total-files-size carries forward; tighten target-size
  rolling assertion to bound per-manifest entry count.
- bytes_per_entry now derived from input manifest header counts
  (added_files_count + existing_files_count) rather than post-filter
  live entries; addresses reviewer-empathy concern that tombstone-heavy
  manifests would over-estimate per-entry size.
- Floor bytes_per_entry at 1 to avoid degenerate "no rolling" when the
  divisor rounds to zero.
- Drop redundant ManifestFile clone before stream::iter (capture
  manifests_replaced count first, then move to_rewrite into the stream).
- Drop the orphan struct doc-comment for consistency with other
  identifier-self-documenting items.
- Add test_oversized_single_manifest_is_split for the
  to_rewrite.len()==1 && total_size > target rolling branch.
- Pin ErrorKind::PreconditionFailed in test_no_current_snapshot_errors
  (was bare is_err(), didn't differentiate the precondition branch from
  any other failure mode)
- Add test_target_size_from_table_property covering the property-fallback
  branch in TableProperties::PROPERTY_COMMIT_MANIFEST_TARGET_SIZE_BYTES
- Drop redundant assert messages that restated the test name or assertion
- manifests_created/manifests_kept now numeric until the insert site,
  matching manifests_replaced
…r API

Upstream apache#2564 changed `ManifestListWriter::v1/v2/v3` to take
`Box<dyn FileWrite>` instead of `OutputFile` (to prep for encryption).
Mirror sibling `transaction/snapshot.rs` by extracting the writer ahead
of the format-version match.
Resolves clippy manual_checked_division surfaced by the toolchain
bump merged from main. Behavior unchanged.

Co-authored-by: Sreeram Garlapati <[email protected]>
Co-authored-by: Aman Rawat <[email protected]>
@SreeramGarlapati
SreeramGarlapati force-pushed the feat/rewrite-manifests branch from 45aebb0 to c57c5cb Compare July 20, 2026 13:38
@SreeramGarlapati

Copy link
Copy Markdown
Contributor Author

gentle ping @liurenjie1024 - this one's green and mergeable. it adds RewriteManifestsAction for manifest compaction, following the same Action shape as ExpireSnapshotsAction (#2591). would appreciate a review when u have a cycle. cc @dhruvarya-db @laskoviymishka since u both looked at the sibling action.

@github-actions github-actions Bot removed the stale label Jul 21, 2026
accumulated = 0;
min_first_row_id = None;
}
if let Some(frid_u) = data_file.first_row_id.and_then(|f| u64::try_from(f).ok()) {

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.

Does the reader automatically populate the first_row_id inherited from the snapshot/manifest in the data_file? My understanding is that most data_files don't have a materialized first_row_id and that first_row_id will remain None throughout this loop for most cases.

metadata.current_snapshot_id(),
next_seq_num,
),
FormatVersion::V3 => ManifestListWriter::v3(

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 suspect that all of the DataFiles above will have first_row_id as None because we don't inherit it from the Manifest/snapshot on the read paht. If the first_row_id in the new Manifest is None, we will end up matching with this case of the ManifestListWriter and assign new row ids to these existing rows (which seems incorrect).

(Some(writer_next_row_id), None) => {
                        // Case: Unassigned first row ID for data manifest. This is either a new
                        // manifest, or a manifest from a pre-v3 snapshot. We need to assign one.
                        let (existing_rows_count, added_rows_count) =
                            require_row_counts_in_manifest(manifest)?;

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

The partition grouping, target-size rolling, and no-op/idempotence behavior look good. The non-lineage test coverage is also thorough.

I don’t think this should merge yet because the V3 row-lineage path can silently corrupt row IDs.

@dhruvarya-db already pointed out the core issue inline at 187/224: the read path never materializes each file’s first_row_id. As a result, min(DataFile.first_row_id) at field 142 remains None, and the rewritten manifest gets a new ManifestFile.first_row_id range for rows that already had IDs.

The follow-on issue is worse. The commit uses with_row_range(next_row_id, 0), so metadata.next_row_id does not advance. The next FastAppend can then reuse the same range, creating overlapping row IDs.

Java and PyIceberg derive _row_id as manifest.first_row_id + pos, so they would read different IDs for existing rows after the rewrite. This is cross-engine corruption, and test_v3_row_lineage_preserved does not catch it because it only compares per-file first_row_id, which is None on both sides.

The fix should either mirror SnapshotProducer::commit or reject V3 rewrites until per-entry inheritance is implemented.

One other issue: moving generate_unique_snapshot_id into a shared pub(crate) helper makes sense, but the -snapshot_id handling should be fixed at the same time. It panics on i64::MIN in debug builds and wraps to a negative value in release builds. Both FastAppend and RewriteManifests now depend on this helper.

Before merge, I’d address:

  • V3 first_row_id handling, with a regression test that rewrites a manifest and then appends, verifying the ranges do not overlap
  • i64::MIN in the shared snapshot ID helper
  • deterministic manifest ordering instead of buffer_unordered
  • a created == replaced file-count check before commit

The remaining comments are mostly non-blocking. Once the row-lineage issue and shared helper are fixed, I’ll take another pass.

{
let mut written = writer.write_manifest_file().await?;
if format_version == FormatVersion::V3 {
written.first_row_id = min_first_row_id;

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.

Building on @dhruvarya-db's thread on lines 187/224 — agreed the read path never materializes per-file first_row_id, so min_first_row_id stays None and the (Some, None) arm reassigns fresh ranges to existing rows.

The part I'd add is the downstream blast radius. Because we also commit with_row_range(next_row_id, 0), metadata.next_row_id never advances — so the next FastAppend reuses that same range and the two collide. And Java/PyIceberg compute _row_id = manifest.first_row_id + pos, so they'd read remapped ids for rows that were originally in a lower range. That makes it silent cross-engine corruption, not just a local mislabel — which is what I'd block on.

A couple of ways to handle, wdyt:

  • Mirror what Java's BaseRewriteManifests does — drop this written.first_row_id = ... assignment, pass None to ManifestListWriter::v3 for these existing-only manifests, and follow SnapshotProducer::commit (snapshot.rs:485–499): read list_writer.next_row_id() after close and set with_row_range(table_next, assigned - table_next).
  • If materializing per-entry first_row_id in inherit_data is out of scope here, I'd rather return an error on V3 than ship silent corruption behind a passing test.

assert_eq!(snap.row_range(), Some((next_row_id_before, 0)));

let post = collect(&table).await;
assert_eq!(

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 test doesn't actually exercise row-lineage preservation, which is why the bug @dhruvarya-db flagged on lines 187/224 slips through green.

collect only reads entry.data_file().first_row_id (field 142), which is None for every file FastAppend writes, so pre and post are both all-None and pre == post passes no matter what the rewrite does to the manifest ranges. It also asserts added_rows == 0 using the same code path it's meant to verify. What I'd want: fixtures with explicit per-file first_row_id, an assertion on the manifest-level ManifestFile.first_row_id in the post list, a check that no two manifests share a range, and an append-after-rewrite assertion that the new data's range doesn't overlap the rewritten manifests'. That last one is the regression test that locks the contract against the bug above.

let (lhs, rhs) = Uuid::new_v4().as_u64_pair();
let snapshot_id = (lhs ^ rhs) as i64;
if snapshot_id < 0 {
-snapshot_id

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.

Now that this is pub(crate) and shared, I'd fix the negation here.

-snapshot_id on i64::MIN panics in debug and wraps back to i64::MIN (still negative) in release, so the sign-flip silently fails for that one value. Masking the sign bit is always non-negative and drops the branch: let snapshot_id = ((lhs ^ rhs) & i64::MAX as u64) as i64;. It's pre-existing, but promoting it to a shared helper is a good moment to get it right in one place.

let file_io = table.file_io().clone();
async move { m.load_manifest(&file_io).await }
})
.buffer_unordered(16)

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.

buffer_unordered(16) makes the rewritten manifest layout non-deterministic — manifests come back in completion order, so entry grouping and the resulting manifest set aren't reproducible run to run, which also shifts partition-pruning order downstream. I'd use buffered(16) to preserve input order, or sort loaded by manifest path before grouping.

+ u64::from(m.existing_files_count.unwrap_or(0))
})
.sum();
let bytes_per_entry = total_size

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.

Not a blocker, but bytes_per_entry divides on-disk manifest_length by the live-entry count, so deleted/dropped entries still count toward the byte numerator and inflate the estimate — Java sizes against actual bytes written. Fine as a heuristic, but worth a comment noting it can over-split.

seen_seqs.sort();
assert_eq!(seen_seqs, vec![seq_a, seq_b, seq_c]);

assert!(post_list.entries().len() < pre_manifest_count);

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.

< pre_manifest_count is looser than the actual invariant — files in partitions 1 and 2 should consolidate to exactly 2 manifests, so I'd assert == 2. < would still pass if the rewrite silently dropped a partition.

self
}

pub fn set_snapshot_properties(mut self, snapshot_properties: HashMap<String, String>) -> Self {

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.

Not a blocker, but taking a full HashMap and replacing the whole map reads oddly next to the additive set_target_size_bytes. A with_snapshot_property(k, v) that inserts one entry would be more consistent with the builder style — optional.

)
})?;
let data_file = entry.data_file().clone();
let idx = match group_index.get(&data_file.partition) {

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.

Worth documenting on the action: grouping strictly by partition means at least one manifest per partition, so on high-cardinality partitioning this won't actually compact. Java exposes a clusterBy knob for exactly this. I'm not asking for the knob in this PR, just a doc note so callers aren't surprised.

}
}

fn new_manifest_writer(

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 is a near-copy of SnapshotProducer::new_manifest_writer, and the path format differs slightly (this one skips the META_ROOT_PATH const). The row-lineage bug above is partly a consequence of the two paths drifting. Either share the helper or add a "keep in sync with SnapshotProducer" comment so the next change touches both.

let t = tx
.update_table_properties()
.set(
"commit.manifest.target-size-bytes".to_string(),

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.

Small thing — since you just added TableProperties::PROPERTY_COMMIT_MANIFEST_TARGET_SIZE_BYTES, use the const here so a rename can't leave the test asserting a stale key.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Aug 21, 2026
@AlJohri

AlJohri commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Commenting here to avoid stale bot from closing the PR.

@github-actions github-actions Bot removed the stale label Aug 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Sep 23, 2026
@JanKaul

JanKaul commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

Commenting to avoid PR from becoming stale

@github-actions github-actions Bot removed the stale label Sep 24, 2026
JanKaul added a commit to lakekeeper/iceberg-rust that referenced this pull request Oct 20, 2026
…operties and lint APIs

Rebase of apache#2543 onto the fork base (main @ e948f62):

- ManifestFile::load_manifest is gone; load manifests through
  Table::manifest_reader().read(..), in the action and its tests.
- TableProperties constants need an explicit 'static lifetime, and the
  target size now has a #[property] getter, commit_manifest_target_size_bytes,
  like the other properties; the action reads it through that getter, so a
  malformed value is an error instead of silently falling back to the default.
- The crate denies missing_docs: document RewriteManifestsAction and its
  setters.
- Regenerate public-api.txt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Oct 25, 2026
@AlJohri

AlJohri commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Commenting here to avoid stale bot from closing the PR.

@github-actions github-actions Bot removed the stale label Oct 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that’s incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the [email protected] list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Nov 26, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants