Skip to content

[Iceberg CDC] Add Snapshot Changelog Scanner#38836

Draft
ahmedabu98 wants to merge 1 commit into
apache:masterfrom
ahmedabu98:iceberg_changelogscanner
Draft

[Iceberg CDC] Add Snapshot Changelog Scanner#38836
ahmedabu98 wants to merge 1 commit into
apache:masterfrom
ahmedabu98:iceberg_changelogscanner

Conversation

@ahmedabu98
Copy link
Copy Markdown
Contributor

@ahmedabu98 ahmedabu98 commented Jun 5, 2026

Adds a DoFn that scans each incoming snapshot and plans batches of changelog scan tasks. Each batch is routed to the appropriate downstream path depending on its contents and size. There's a lot of details in the java doc, but to summarize:

  • Unidirectional changes, such as append-only inserts or delete-only work, are routed to a fast path that can be read and emitted directly.
  • Small bidirectional groups are routed to a local in-memory resolver.
  • Large bidirectional groups are routed to the distributed resolution path where rows are grouped by primary key then passed to a resolver

We perform a few optimizations to limit the amount of data we need to resolve:

  • non-overwrite snapshots can bypass update resolution
  • if partition specs are derived from PK fields, we narrow down to per-partition analysis
  • non-overlapping opposing tasks can bypass update resolution

Note: "update resolution" is logic that compares inserts and deletes to check if an update has occurred.

Part of #38831


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request adds a new ChangelogScanner to the Iceberg IO connector in Apache Beam. The scanner is designed to efficiently process Iceberg snapshots by categorizing changelog tasks into different paths based on their complexity and size. By implementing smart routing and leveraging partition and file-level metadata, the change significantly reduces the data volume requiring a costly CoGroupByKey shuffle, improving overall performance for CDC workloads.

Highlights

  • New Changelog Scanner: Introduced a new ChangelogScanner DoFn that processes Iceberg snapshots to plan changelog scan tasks.
  • Intelligent Task Routing: Implemented logic to route tasks based on complexity: unidirectional changes bypass shuffling, small bidirectional groups are resolved in-memory, and large bidirectional groups are routed to a distributed resolution path.
  • Partition Optimization: Added optimization to narrow down change analysis to individual partitions when partition specs are derived from primary key fields.
  • File-Level Overlap Analysis: Added file-level metadata analysis to identify non-overlapping opposing tasks, allowing them to bypass the expensive CoGroupByKey shuffle.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@ahmedabu98 ahmedabu98 marked this pull request as draft June 5, 2026 19:40
@ahmedabu98
Copy link
Copy Markdown
Contributor Author

Need to merge #38821 first

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces Iceberg CDC support by adding ChangelogDescriptor, ChangelogScanner, and corresponding unit tests. The ChangelogScanner optimizes data processing by routing changelog tasks into unidirectional, small bidirectional, or large bidirectional paths. The review feedback highlights a critical issue where instance variables in the DoFn could leak state or cause a NullPointerException, suggests an early return optimization when primary key fields are empty, and recommends removing unused helper methods in both the scanner and its test suite.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +220 to +234
public void process(@Element Long snapshotId, MultiOutputReceiver out) throws IOException {
resetLocalMetrics();
// not using getRefreshed because upstream Watch should have already refreshed the
// table to a state where this snapshot exists
this.table = SerializableTable.copyOf(TableCache.get(scanConfig.getTableIdentifier()));
this.snapshot = table.snapshot(snapshotId);

// refresh on miss
if (this.snapshot == null) {
this.table =
SerializableTable.copyOf(TableCache.getRefreshed(scanConfig.getTableIdentifier()));
this.snapshot =
checkStateNotNull(
table.snapshot(snapshotId), "Could not retrieve table snapshot: %s", snapshotId);
}
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.

critical

The table and snapshot fields are instance variables of the DoFn. Since Beam runners can reuse DoFn instances across multiple elements, these fields can leak state from previous elements if they are not reset. Furthermore, if TableCache.get() returns null (e.g., on a cache miss), calling table.snapshot(snapshotId) directly will throw a NullPointerException before the 'refresh on miss' block is ever reached.

To fix both issues, reset the instance fields at the start of process and perform a null check on the cached table before attempting to retrieve the snapshot.

Suggested change
public void process(@Element Long snapshotId, MultiOutputReceiver out) throws IOException {
resetLocalMetrics();
// not using getRefreshed because upstream Watch should have already refreshed the
// table to a state where this snapshot exists
this.table = SerializableTable.copyOf(TableCache.get(scanConfig.getTableIdentifier()));
this.snapshot = table.snapshot(snapshotId);
// refresh on miss
if (this.snapshot == null) {
this.table =
SerializableTable.copyOf(TableCache.getRefreshed(scanConfig.getTableIdentifier()));
this.snapshot =
checkStateNotNull(
table.snapshot(snapshotId), "Could not retrieve table snapshot: %s", snapshotId);
}
@ProcessElement
public void process(@Element Long snapshotId, MultiOutputReceiver out) throws IOException {
resetLocalMetrics();
this.table = null;
this.snapshot = null;
Table cachedTable = TableCache.get(scanConfig.getTableIdentifier());
if (cachedTable != null) {
this.table = SerializableTable.copyOf(cachedTable);
this.snapshot = this.table.snapshot(snapshotId);
}
// refresh on miss
if (this.snapshot == null) {
this.table =
SerializableTable.copyOf(TableCache.getRefreshed(scanConfig.getTableIdentifier()));
this.snapshot =
checkStateNotNull(
table.snapshot(snapshotId), "Could not retrieve table snapshot: %s", snapshotId);
}

Comment on lines +261 to +273
boolean metricsAvailable = true;
MetricsConfig metricsConfig = MetricsConfig.forTable(table);
Collection<String> pkFields = table.schema().identifierFieldNames();
for (String field : pkFields) {
MetricsModes.MetricsMode mode = metricsConfig.columnMode(field);
if (!(mode instanceof MetricsModes.Full) && !(mode instanceof MetricsModes.Truncate)) {
metricsAvailable = false;
break;
}
}
if (metricsAvailable) {
scan = scan.includeColumnStats(pkFields);
}
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.

medium

If pkFields is empty, metricsAvailable remains true, which leads to calling scan.includeColumnStats(Collections.emptyList()). If there are no primary keys, we cannot perform file-level overlap analysis anyway. Returning early when pkFields is empty avoids unnecessary overhead.

    Collection<String> pkFields = table.schema().identifierFieldNames();
    if (pkFields.isEmpty()) {
      return scan;
    }
    boolean metricsAvailable = true;
    MetricsConfig metricsConfig = MetricsConfig.forTable(table);
    for (String field : pkFields) {
      MetricsModes.MetricsMode mode = metricsConfig.columnMode(field);
      if (!(mode instanceof MetricsModes.Full) && !(mode instanceof MetricsModes.Truncate)) {
        metricsAvailable = false;
        break;
      }
    }
    if (metricsAvailable) {
      scan = scan.includeColumnStats(pkFields);
    }

Comment on lines +927 to +929
static String name(String path) {
return Iterables.getLast(Splitter.on("-").split(path));
}
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.

medium

The name helper method is unused in this class. Removing it keeps the codebase clean and avoids an unused dependency on Splitter (which can also be removed from the imports if this is the only usage).

Comment on lines +311 to +318
private static StructLike partition(long id) {
PartitionKey partitionKey = new PartitionKey(IDENTITY_ID_SPEC, SINGLE_PK_SCHEMA);
GenericRecord record = GenericRecord.create(SINGLE_PK_SCHEMA);
record.setField("id", id);
record.setField("data", "partition-" + id);
partitionKey.partition(record);
return partitionKey;
}
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.

medium

The partition helper method is unused in the test class. Removing it keeps the test file clean.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant