[Dataflow Streaming] [Multi Key] Prepare StreamingModeExecutionContext and StreamingWorkScheduler for multi-key execution.#38814
Conversation
…oring for multi-key execution.
|
R: @scwhittle |
|
Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment |
|
@scwhittle FYI on this, i'll update after validating presubmits and when it is ready for review. |
Summary of ChangesHello, 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 introduces the foundational infrastructure required for multi-key execution in Dataflow streaming. By updating the execution context, scheduler, and reader iterators, the changes enable the system to process multiple keys within a single bundle. These modifications are primarily structural, setting the stage for future PRs that will implement the specific failure handling and queue polling logic required for full multi-key support. Highlights
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 AssistThe 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
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 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
|
There was a problem hiding this comment.
Code Review
This pull request refactors the Dataflow streaming execution context and work processing to support batching and key chaining, allowing the worker to advance to the next key in a group when elements are exhausted. Key changes include updating StreamingModeExecutionContext to manage multiple executed works and output builders, refactoring StreamingWorkScheduler to handle work batches, and updating reader iterators to support key transitions. The review feedback highlights several critical improvement opportunities: a potential memory leak in StreamingModeExecutionContext.clear() from not nullifying key and work references, a deadlock risk in Work caused by executing listener callbacks inside synchronized blocks, a potential NullPointerException in exception logging when getWorkItem() is null, and unsafe mutation of a shared outputBuilder in StreamingWorkScheduler.
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.
| } catch (IOException e) { | ||
| LOG.warn( | ||
| "Failed to close reader for {}-{}", computationId, getWorkItem().getShardingKey(), e); | ||
| } |
There was a problem hiding this comment.
If getWorkItem() returns null (which is possible if the context is cleared or not yet initialized), calling getWorkItem().getShardingKey() inside the catch block will throw a NullPointerException. This will mask the original IOException thrown by activeReader.close(), making debugging very difficult.
Please add a null check for getWorkItem() before accessing the sharding key.
} catch (IOException e) {
Windmill.WorkItem workItem = getWorkItem();
long shardingKey = workItem != null ? workItem.getShardingKey() : -1L;
LOG.warn(
"Failed to close reader for {}-{}", computationId, shardingKey, e);
}|
R: @scwhittle this is ready for review. Thanks! |
| * | ||
| * @implNote Once closed, it cannot be reused. | ||
| */ | ||
| // TODO(m-trieu): See if this can be combined/cleaned up with StreamingModeExecutionContext as the |
There was a problem hiding this comment.
should we get rid of this and merge into StreamingModeExecutionContext
There was a problem hiding this comment.
We should be able to merge things into StreamingModeExecutionContext. Today ComputationWorkExecutor owns both StreamingModeExecutionContext and MapTaskExecutor. The tricky bit seems to be that MapTaskExecutor's creation depends on StreamingModeExecutionContext. So we need to create StreamingModeExecutionContext before the MapTaskExecutor. We could store MapTaskExecutor in StreamingModeExecutionContext after constructing both.
I think we can do that separately, since it looks like it will pull in a bit of unrelated changes.
There was a problem hiding this comment.
Sounds good, might be a nice simplification to follow up with.
| Instant processingTime = | ||
| computeProcessingTime(newWork.getWorkItem().getTimers().getTimersList()); | ||
| if (!getAllStepContexts().isEmpty()) { | ||
| // This must be only created once for a workItem as token validation will fail if the same |
There was a problem hiding this comment.
not sure what this means, I don't see any guard against recreating it. I'm wondering if there are cases with retries etc that we could get the same key and possibly same work token. Should we guard against that somehow?
There was a problem hiding this comment.
It is an old comment that i moved here.
stateCache.forKey internally checks if the input workToken is > the last seen workToken, else will invalidate the in-memory cache and returns a new ForKey cache. I think that is why the comment says do this once per workitem.
I'm wondering if there are cases with retries etc that we could get the same key and possibly same work token. Should we guard against that somehow?
IIUC, the worktoken check in stateCache.forKey guards against this.
There was a problem hiding this comment.
Separate from the logic here, I was wondering if we want/need to try to prevent processing a batch with the same key multiple times
There was a problem hiding this comment.
ActiveWorkState manages the retries and multiple work items for same key. It make sures there is only one work item active at a time for a key. I think we can rely on that and don't need to add deduping logic in the context.
# Conflicts: # runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingModeExecutionContext.java
| * | ||
| * @implNote Once closed, it cannot be reused. | ||
| */ | ||
| // TODO(m-trieu): See if this can be combined/cleaned up with StreamingModeExecutionContext as the |
There was a problem hiding this comment.
Sounds good, might be a nice simplification to follow up with.
| Instant processingTime = | ||
| computeProcessingTime(newWork.getWorkItem().getTimers().getTimersList()); | ||
| if (!getAllStepContexts().isEmpty()) { | ||
| // This must be only created once for a workItem as token validation will fail if the same |
There was a problem hiding this comment.
Separate from the logic here, I was wondering if we want/need to try to prevent processing a batch with the same key multiple times
Resolved conflicts in StreamingModeExecutionContext.java and StreamingModeExecutionContextTest.java. Fixed compilation error in Work.java by removing duplicate getComputationId() method. TAG=agy CONV=143daaa5-e902-4d26-820d-cf1af2babb84
|
@scwhittle could you take another look? |
| String computationId = computationState.getComputationId(); | ||
| ByteString key = workItem.getKey(); | ||
| work.setProcessingThreadName(Thread.currentThread().getName()); | ||
| work.setState(Work.State.PROCESSING); |
There was a problem hiding this comment.
the first item is set to PROCESSING here and then others are set to PROCESSING as they are added to the batch. But the first remains PROCESSING until it is transferred to QUEUED. This might confuse user worker latency analysis, we attribute too much user processing time to that particular key and if we have N items taking a second each we would have O(N^2) total processing seconds instead of N. Should we add a new POST_PROCESSING_QUEUED or something?
There was a problem hiding this comment.
I think that is a good idea. Will tackle it in a separate PR.
| private KeyTransitionListener createKeyTransitionListener() { | ||
| return (oldWork, newWork) -> { | ||
| setLoggingContextWorkId(newWork.getLatencyTrackingId()); | ||
| newWork.setProcessingThreadName(oldWork.getProcessingThreadName()); |
There was a problem hiding this comment.
see above, maybe we should set oldWork state to somethign showing it is waiting for the batch
There was a problem hiding this comment.
Yes, would like to tackle it in a separate PR.
| List<Work> workBatch, | ||
| List<Windmill.WorkItemCommitRequest> workItemCommits) { | ||
| Preconditions.checkState( | ||
| workBatch.size() == 1, "Expected single-key work batch, got: " + workBatch.size()); |
There was a problem hiding this comment.
check taht commits and batch are same size?
| // either here or in DFE. | ||
| if (work.getWorkItem().hasTimers()) { | ||
| stageInfo.timerProcessingMsecs().addValue(processingTimeMsecs); | ||
| recordProcessingTime(stageInfo, workBatch, work, processingStartTimeNanos); |
There was a problem hiding this comment.
could we simplify here by just creating a single-element workBatch if workBatch is null? and then just using the batch for this method and below
There was a problem hiding this comment.
good idea, done.
| private @Nullable WorkExecutor workExecutor; | ||
| private boolean finishKeyCalled = false; | ||
|
|
||
| @SuppressWarnings("UnusedVariable") |
There was a problem hiding this comment.
any idea why these suppressions are needed?
There was a problem hiding this comment.
It is because we are not reading from the variables workQueueExecutor yet, future PRs have logic to read from these variables. Will remove the suppressions in future PRs.
Private field 'workQueueExecutor' is assigned but never accessed is the warning that shows up in ide.
| private @Nullable WindowedValue<KeyedWorkItem<K, T>> current = null; | ||
|
|
||
| @Override | ||
| public boolean start() throws IOException { |
There was a problem hiding this comment.
can we just implement start() and advance() with a helper method taking a bool on whether or not to advance initially? seems safer if there is more setup/checking added before processing an item
| // Ensure that the invalidated dofn had tearDown called on them. | ||
| assertEquals(1, TestExceptionInvalidatesCacheFn.tearDownCallCount.get()); | ||
| assertEquals(2, TestExceptionInvalidatesCacheFn.setupCallCount.get()); | ||
| assertEquals(2, TestExceptionInvalidatesCacheFn.tearDownCallCount.get()); |
There was a problem hiding this comment.
I should have explained this :(
The test makes UnboundedReader::getCheckpointMark throw. In the old code, UnboundedReader::getCheckpointMark was called after calling finishBundle, so teardown was not called by pardo abort().
In the new code finishKey() calls UnboundedReader::getCheckpointMark, it happens before finishBundle, so the DoFn's teardown got called one more time.
There was a problem hiding this comment.
So it seems now that we are not caching this DoFn for more things that might happen in flushInternal which was previously separate from user code execution?
For the multi-key case this seems needed because we haven't called finishBundle yet and thus have incomplete dofn lifecycle. However if it is the final key (or only key) within a batch we may be not caching dofns as aggressively as previously when they are still valid to use.
We could defer the final finishKey if advance will return false? I'm worried that there might be more effects for single-key processing than we realize if there are cases where checkpoints do have errors since dofn construction is expensive.
| // First call | ||
| executionContext.finishKey(); | ||
| // Second call - should not throw any Exception | ||
| executionContext.finishKey(); |
There was a problem hiding this comment.
when does this happen? add a comment here why we want this to be the case
There was a problem hiding this comment.
The reader iterators call finishKey() in advance(). I initially was throwing if finishKey got called twice. Gemini said iterator advance() needs to be reentrant, so make finishKey to ignore future calls.
| .build()) | ||
| .build(); | ||
|
|
||
| // Set up context.advance() to mock transition |
There was a problem hiding this comment.
this seems a bit odd to test this way by just mocking out responses. It seems better suited for a test once support of multiple items via advance is actually within the context.
There was a problem hiding this comment.
The tests helped validate the logic in the Iterator where it calls context.advance(). mocked context.advance() to test the iterator logic in isolation.
| when(mockContext.getWork()).thenReturn(work1); | ||
|
|
||
| // Mock transition behaviour of context.advance() | ||
| when(mockContext.advance()) |
There was a problem hiding this comment.
ditto seems a bit odd to mock this in here
There was a problem hiding this comment.
Same as above. These tests help validate the logic in the Iterator where it calls context.advance(). mocked context.advance() to test the iterator logic in isolation. We could consider using the real context once it supports multi key bundles.
| try { | ||
| return keyCoder.decode(work.getWorkItem().getKey().newInput(), Coder.Context.OUTER); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Failed to decode key during processing", e); |
There was a problem hiding this comment.
should we wrap as CoderException instead of RuntimeException?
|
|
||
| // Returns the windmill WorkItem proto for the current Work | ||
| public Windmill.WorkItem getWorkItem() { | ||
| return checkStateNotNull( |
There was a problem hiding this comment.
how about moving this checkSTateNotNull message to getWork() and then just have return getWork().getWorkItem();
here
| // Ensure that the invalidated dofn had tearDown called on them. | ||
| assertEquals(1, TestExceptionInvalidatesCacheFn.tearDownCallCount.get()); | ||
| assertEquals(2, TestExceptionInvalidatesCacheFn.setupCallCount.get()); | ||
| assertEquals(2, TestExceptionInvalidatesCacheFn.tearDownCallCount.get()); |
There was a problem hiding this comment.
So it seems now that we are not caching this DoFn for more things that might happen in flushInternal which was previously separate from user code execution?
For the multi-key case this seems needed because we haven't called finishBundle yet and thus have incomplete dofn lifecycle. However if it is the final key (or only key) within a batch we may be not caching dofns as aggressively as previously when they are still valid to use.
We could defer the final finishKey if advance will return false? I'm worried that there might be more effects for single-key processing than we realize if there are cases where checkpoints do have errors since dofn construction is expensive.
I think the comment is on a stale diff, the code is now rethrowing CoderExceptions and wraping other IOExceptions. |
Done. Moved last flushStateInternal outside the doFn lifecycle. |
|
Internal tests passing, going to merge. |
Adds interfaces and methods for advancing work items in a multi key bundle. Nothing functional changes yet. Following PRs will update failure handling logic and implement StreamingModeExecutionContext::advance to poll more items from BoundedQueueExecutor.