Skip to content

[Python] Bound Watch state with a timestamp cursor - #39090

Open
Eliaaazzz wants to merge 5 commits into
apache:masterfrom
Eliaaazzz:python-watch-timestamp-cursor
Open

[Python] Bound Watch state with a timestamp cursor#39090
Eliaaazzz wants to merge 5 commits into
apache:masterfrom
Eliaaazzz:python-watch-timestamp-cursor

Conversation

@Eliaaazzz

@Eliaaazzz Eliaaazzz commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Update (rebased): #39023 merged, so this is again a single commit on master. The merged Watch reworked the internals this PR was written against (polling moved from the tracker into the SDF's process()), so the cursor was re-implemented on the new architecture rather than mechanically rebased. The API is now Watch(..., timestamp_cursor=True) to match the merged constructor-kwargs style. Semantics and the load-test rationale are unchanged. Hash-mode restriction states keep the exact pre-cursor byte format (cursor states use a new envelope tag), a hash-mode restriction switched to cursor mode retires its hash map and seeds the cursor from the map's greatest recorded event time, so the switch stays exactly once, and the out-of-order warning no longer fires while the watermark still holds the element-timestamp seed. Relates to #18459 (the unbounded completed dedup set).

By default Watch dedups by value identity and keeps one hash per distinct output, so the per-input state grows without bound. This adds an opt-in Watch(..., timestamp_cursor=True) that dedups by a high-water-mark timestamp instead: Watch keeps only the greatest event time it has emitted for an input and emits the polled outputs strictly past it, then advances the cursor. No hash set is kept and the poll result is not hashed, so the per-input state and per-checkpoint encoding are O(1) regardless of how many outputs the input produces. It is for sources whose outputs carry strictly increasing event-time timestamps; an output at or below the cursor is treated as already seen, so the default exact dedup remains for arbitrary-relisting or out-of-order sources. This also documents the event-time/watermark contract and adds a throttled late-emission warning.

Testing: 28 unit tests and 5 subtests on the in-memory DirectRunner; yapf 0.43.0, isort 7.0.0, and pylint clean. Load tested on Dataflow Runner v2 (us-east1) against the default hash dedup, 4 inputs emitting 15000 outputs per 1s round over a 240s budget: the cursor processed 6,825,000 outputs versus the default's 1,650,000 in the same budget (4.1x), because the default re-serializes its growing dedup set on every checkpoint (it reached about 300-495K entries per input) while the cursor writes one timestamp; the gap widens with runtime. Both stayed exactly-once and reached JOB_STATE_DONE. Jobs on apache-beam-testing: cursor 2026-06-24_08_45_05-17501676526076065162, default 2026-06-24_08_45_23-5060488636914380336.


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

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

@Eliaaazzz
Eliaaazzz force-pushed the python-watch-timestamp-cursor branch from 85476e4 to 71d6282 Compare June 24, 2026 15:43
@Eliaaazzz
Eliaaazzz marked this pull request as ready for review July 5, 2026 00:49
@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 PR introduces a more scalable deduping strategy for the Watch transform in the Python SDK. By allowing users to opt into a timestamp-based cursor, the transform can now handle high-cardinality sources with O(1) state growth, avoiding the performance degradation associated with the default hash-based deduping set.

Highlights

  • New Watch.with_timestamp_cursor() feature: Added an opt-in deduping mechanism based on event-time timestamps, reducing state complexity to O(1) for monotonic sources.
  • Improved scalability: Eliminated the need for a growing hash set for deduping, significantly improving performance for long-lived, high-cardinality sources.
  • Enhanced observability: Added throttled warnings for late emissions when poll results arrive out of event-time order.
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.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces an experimental Watch transform for the Python SDK, which continuously polls and watches a growing set of outputs for each input element. It supports exact deduplication using 128-bit hashes or O(1) state deduplication using a high-water-mark timestamp cursor. The feedback suggests two improvements: first, ensuring that timestamps are normalized to Timestamp objects before comparison in cursor mode to prevent TypeError exceptions in Python 3; second, converting the input outputs iterable to a list during normalization to safely handle single-use generators or iterators.

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 thread sdks/python/apache_beam/io/watch.py Outdated
Comment on lines +480 to +483
new_outputs = [
output for output in result.outputs
if cursor is None or output.timestamp > cursor
]

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.

high

In _GrowthRestrictionTracker.try_claim, when self._cursor_mode is enabled, the code compares output.timestamp > cursor. However, output.timestamp can be a raw float or integer if the user directly instantiated TimestampedValue without using Timestamp objects (as TimestampedValue accepts int or float for its timestamp). Since cursor is a Timestamp object (or None), comparing a Timestamp with a float or integer will raise a TypeError in Python 3. To prevent comparison errors, normalize output.timestamp to a Timestamp object using Timestamp.of(output.timestamp) before comparison.

Suggested change
new_outputs = [
output for output in result.outputs
if cursor is None or output.timestamp > cursor
]
cursor = restriction.cursor
new_outputs = [
output for output in result.outputs
if cursor is None or Timestamp.of(output.timestamp) > cursor
]

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.

Thanks — this can't happen in practice: TimestampedValue.__init__ coerces its argument with Timestamp.of(timestamp), so by the time an output reaches the tracker its timestamp is always a Timestamp. (The rebased branch reworked this code path, but the invariant is the same.)

Comment on lines +167 to +171
for output in outputs:
if isinstance(output, TimestampedValue):
normalized.append(output)
else:
normalized.append(TimestampedValue(output, default_ts))

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

When iterating over outputs, if the user passes a single-use generator or iterator, iterating over it to normalize elements will consume it. Since outputs is iterated again when constructing the PollResult or during normalization, this can lead to empty outputs or unexpected behavior. Consider converting outputs to a list or tuple first before normalization.

Suggested change
for output in outputs:
if isinstance(output, TimestampedValue):
normalized.append(output)
else:
normalized.append(TimestampedValue(output, default_ts))
outputs = list(outputs)
normalized = []
for output in outputs:
if isinstance(output, TimestampedValue):
normalized.append(output)
else:
normalized.append(TimestampedValue(output, default_ts))

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.

After the rebase onto the merged Watch (#39023), PollResult._normalize materializes outputs into a tuple in one pass, so a single-use iterator is only consumed once and the double-iteration this pointed at no longer exists.

@github-actions

github-actions Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @jrmccluskey for label python.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

@Eliaaazzz
Eliaaazzz force-pushed the python-watch-timestamp-cursor branch from 71d6282 to ac7d761 Compare July 7, 2026 13:43
@github-actions

Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @jrmccluskey

@github-actions

Copy link
Copy Markdown
Contributor

Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment assign to next reviewer:

R: @claudevdm for label python.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

Opt-in timestamp_cursor=True dedups by a high-water-mark timestamp
instead of by key identity: Watch keeps only the greatest event time it
has emitted for an input and emits the polled outputs strictly past it,
so the per-input state and per-checkpoint encoding are O(1) regardless
of how many outputs the input produces. For sources whose outputs carry
strictly increasing event-time timestamps; the default exact hash dedup
remains for arbitrary-relisting or out-of-order sources.

Also documents the event-time/watermark contract, adds a throttled
late-emission warning, and reuses the parent dedup map on idle rounds so
steady-state empty polls stay O(1) in hash mode too.
@Eliaaazzz
Eliaaazzz force-pushed the python-watch-timestamp-cursor branch from ac7d761 to b30751a Compare July 27, 2026 13:55
Comment thread sdks/python/apache_beam/io/watch.py Outdated
poll_interval=Duration(seconds=5),
termination=after_total_of(60))

Watermark and event-time contract

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.

Please keep doc and comments concise thoughout this PR.

Agent has a tendancy of stacking chat history into doc. Sometimes need a fresh session to rewrite things

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.

You are right, that is exactly what happened here. I use AI tooling for drafting and I let the docs absorb the review discussion instead of keeping them clean. I rewrote the docstrings and comments this PR adds from a clean slate, each fact is stated once now, and I have gone through every line myself.

Comment thread sdks/python/apache_beam/io/watch.py Outdated
if tag == 1:
watermark, outputs = self._non_polling_coder.decode(payload)
return _NonPollingGrowthState(PollResult(tuple(outputs), watermark))
if tag == 2:

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.

Prefer enum over raw numbers

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, replaced the raw tag numbers with an IntEnum.

Comment thread sdks/python/apache_beam/io/watch.py Outdated
state.poll_watermark,
list(state.completed.items())))
return self._envelope_coder.encode((0, payload))
list(state.completed.items()),

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.

We should not encode the items when use cursors. The whole point of cursor (with_timestamp) mode is that the saved state doesn't grow with the number of items in poll therefore scalable

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.

Agreed, the cursor state should not carry the items at all. The completed map was already empty at runtime in cursor mode, but the byte format still reserved a slot for it. Cursor states now encode only the termination state, the poll watermark and the cursor, and a new test asserts the encoded size stays constant no matter how many outputs a round claims.

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.

Went one step further and re-derived the payload from what resume actually reads: poll_watermark was never read either, the watermark is restored from the estimator state the runner persists. The cursor payload is now just the termination state and the cursor.

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 round is a single follow up commit on top of the reviewed commit, bc56cb0, covering the three comments. I force pushed by mistake earlier today and restored the reviewed commit so the delta since your review is visible.

@Eliaaazzz Eliaaazzz Jul 29, 2026

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.

One more follow up commit, 098623b: the hash to cursor switch now seeds the cursor from the hash map's greatest recorded event time instead of starting empty, so the switch cannot re-emit already seen outputs.

@Eliaaazzz
Eliaaazzz force-pushed the python-watch-timestamp-cursor branch 2 times, most recently from dde3905 to 3d93c6f Compare July 29, 2026 04:11
Encode cursor states as (termination_state, cursor) behind an IntEnum
envelope tag, drop a stale cursor on hash rounds so the two dedup states
never mix, pin the O(1) encoding with a size test, and rewrite the
docstrings and comments this PR adds to be concise.
@Eliaaazzz
Eliaaazzz force-pushed the python-watch-timestamp-cursor branch from 3d93c6f to bc56cb0 Compare July 29, 2026 04:39
A restriction carried over from hash dedup starts with no cursor, so its
first cursor round re-emitted already seen outputs. The cursor now seeds
from the greatest event time the hash map recorded, keeping the switch
exactly once. Also clarifies the relisting guidance in the
timestamp_cursor docs.
@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.40659% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 60.56%. Comparing base (72d7ae3) to head (098623b).
⚠️ Report is 35 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/io/watch.py 93.40% 6 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #39090      +/-   ##
============================================
+ Coverage     60.52%   60.56%   +0.04%     
  Complexity    20659    20659              
============================================
  Files          3324     3325       +1     
  Lines        318309   318704     +395     
  Branches      17249    17249              
============================================
+ Hits         192644   193018     +374     
- Misses       117036   117057      +21     
  Partials       8629     8629              
Flag Coverage Δ
python 79.83% <93.40%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread sdks/python/apache_beam/io/watch.py Outdated
``output_key_fn(output)`` when one is given. The key coder is inferred when
not passed explicitly and converted to its deterministic form, so equal keys
hash equally across workers and restarts.
hash equally across workers and restarts. ``timestamp_cursor=True`` replaces

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 last sentence sounds cryptic to users. How about this:

(a new paragraph): By default, watch transform internally stores the hash of all items seen. If the incremented items returned by the poll function guarantees monotonic timestamp growth (new items on next poll have timestamp larger than the largest of the previous poll), consider set timestamp_cursor=True for better performance, as it replaces the hash dedup with an O(1) event-time cursor; see :class:Watch.

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.

Thanks, that reads much better. Applied your wording as a new paragraph in f80a95b, with two small grammar touch ups.

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.

2 participants