You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "stankiewicz (via GitHub)" <gi...@apache.org> on 2026/04/17 11:23:54 UTC
[PR] [Refactor] Support extensible element metadata propagation in ReduceFnRunner [beam]
stankiewicz opened a new pull request, #38230:
URL: https://github.com/apache/beam/pull/38230
## Description
This PR refactors the metadata propagation logic in `ReduceFnRunner` to support extensible metadata.
Previously, metadata tracking (specifically `causedByDrain`) was not stored in state at all during execution in `ReduceFnRunner`, which caused metatada loss failures when firing timers or merging panes. This PR fixes that by introducing a unified state map for element metadata.
To make it easier to add future payloads (such as OpenTelemetry context maps or CDC insert/update markers) without modifying method signatures, this change groups targeted fields into a unified container and offloads combination rules to a clean aggregator class.
### Key Changes
- **Runner Fix**: Added stateful tracking using `METADATA_TAG` (persisting `PipelineMetadata`) in `ReduceFnRunner`, ensuring metadata is no longer lost during grouping.
- **Extensible Container**: Created `PipelineMetadata` (guided by `@AutoValue`) that groups element metadata together.
- **Metadata Combiners**: Encapsulated combination logic within `PipelineMetadataCombiner`.
------------------------
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](https://www.apache.org/licenses/icla.pdf).
See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
GitHub Actions Tests Status (on master branch)
------------------------------------------------------------------------------------------------
[](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Refactor] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4267592631
Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3118193737
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -1009,8 +1029,19 @@ private void prefetchOnTrigger(
ReduceFn<K, InputT, OutputT, W>.Context renamedContext,
final boolean isFinished,
boolean isEndOfWindow,
- CausedByDrain causedByDrain)
+ CombinedMetadata metadata)
throws Exception {
+ ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ CombinedMetadata aggregatedMetadata = metadataState.read();
+ if (aggregatedMetadata == null) {
+ aggregatedMetadata = CombinedMetadata.createDefault();
+ }
+ CombinedMetadata fullyAggregatedMetadata =
+ CombinedMetadataCombiner.of().addInput(aggregatedMetadata, metadata);
+ final CausedByDrain aggregatedCausedByDrain = fullyAggregatedMetadata.causedByDrain();
+ if (isFinished) {
+ metadataState.clear();
+ }
Review Comment:

In `onTrigger`, the metadata from the trigger/timer is combined with the persisted state, but the result is not written back to state if the window remains open (`isFinished == false`). This means that any metadata associated with the trigger (e.g., a drain signal from a timer) will be lost for subsequent panes of the same window. To ensure "stateful tracking" as intended, the aggregated metadata should be persisted if the window remains open.
```suggestion
ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
CombinedMetadata aggregatedMetadata = metadataState.read();
CombinedMetadata fullyAggregatedMetadata =
CombinedMetadataCombiner.of()
.addInput(
aggregatedMetadata == null ? CombinedMetadata.createDefault() : aggregatedMetadata,
metadata);
final CausedByDrain aggregatedCausedByDrain = fullyAggregatedMetadata.causedByDrain();
if (isFinished) {
metadataState.clear();
} else if (!fullyAggregatedMetadata.equals(aggregatedMetadata)) {
metadataState.write(fullyAggregatedMetadata);
}
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -590,6 +595,17 @@ private void processElement(Map<W, W> windowToMergeResult, WindowedValue<InputT>
value.getTimestamp(),
StateStyle.DIRECT,
value.causedByDrain());
+
+ ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ CombinedMetadata currentMetadata = metadataState.read();
+ if (currentMetadata == null) {
+ currentMetadata = CombinedMetadata.createDefault();
+ }
+ CombinedMetadata inputMetadata = CombinedMetadata.create(value.causedByDrain());
+ CombinedMetadata newMetadata =
+ CombinedMetadataCombiner.of().addInput(currentMetadata, inputMetadata);
+ metadataState.write(newMetadata);
Review Comment:

This block introduces a state read and write for every single element processed by `ReduceFnRunner`. This is a significant performance regression, especially for high-throughput pipelines where `causedByDrain` is typically `NORMAL`. Additionally, this logic is currently executed *before* checking if the window is closed (line 609), meaning state is updated even for elements that will be dropped.
Consider optimizing this to avoid state access in the common case and moving it after the `isClosed` check.
```suggestion
if (value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN) {
ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
CombinedMetadata currentMetadata = metadataState.read();
if (currentMetadata == null || currentMetadata.causedByDrain() != CausedByDrain.CAUSED_BY_DRAIN) {
metadataState.write(CombinedMetadata.create(CausedByDrain.CAUSED_BY_DRAIN));
}
}
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadata.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import com.google.auto.value.AutoValue;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.coders.ByteArrayCoder;
+import org.apache.beam.sdk.coders.NullableCoder;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/**
+ * Encapsulates metadata that propagates with elements in the pipeline.
+ *
+ * <p>This metadata is sent along with elements. It currently includes fields like {@link
+ * CausedByDrain}, and is designed to be extensible to support future metadata fields such as
+ * OpenTelemetry context or CDC (Change Data Capture) kind.
+ *
+ * <p>The purpose of this class is to group targeted metadata fields together. This makes it easier
+ * to define combination strategies (e.g., when accumulating state in {@code ReduceFnRunner}) when
+ * multiple elements are merged or grouped, without having to extend method signatures or state
+ * handling for every new metadata field.
+ */
+@AutoValue
+public abstract class CombinedMetadata {
+ public abstract CausedByDrain causedByDrain();
+
+ public static CombinedMetadata create(CausedByDrain causedByDrain) {
+ return new AutoValue_CombinedMetadata(causedByDrain);
+ }
+
+ public static CombinedMetadata createDefault() {
+ return create(CausedByDrain.NORMAL);
+ }
+
+ public static class Coder extends AtomicCoder<CombinedMetadata> {
+ private static final Coder INSTANCE = new Coder();
+
+ public static Coder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
+ if (value == null) {
+ NullableCoder.of(ByteArrayCoder.of()).encode(null, outStream);
+ return;
+ }
+ BeamFnApi.Elements.ElementMetadata.Builder builder =
+ BeamFnApi.Elements.ElementMetadata.newBuilder();
+ builder.setDrain(
+ value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
+ ? BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING);
+
+ NullableCoder.of(ByteArrayCoder.of()).encode(builder.build().toByteArray(), outStream);
Review Comment:

The `Coder` implementation uses `NullableCoder.of(ByteArrayCoder.of())` to wrap the serialized proto bytes. This adds unnecessary overhead (extra bytes for nullability and length prefixing) since `AtomicCoder` can handle the serialization directly. Furthermore, `ByteArrayCoder` is redundant if you are already managing the byte array from the proto. Consider simplifying the coder to write the proto bytes directly to the `OutputStream` with a simple length prefix if necessary.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4416749779
This PR is also causing the following workflow perm-red https://github.com/apache/beam/actions/workflows/beam_PreCommit_Java_PVR_Prism_Loopback.yml?page=2
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "kennknowles (via GitHub)" <gi...@apache.org>.
kennknowles commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3189574401
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadata.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import com.google.auto.value.AutoValue;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/**
+ * Encapsulates metadata that propagates with elements in the pipeline.
+ *
+ * <p>This metadata is sent along with elements. It currently includes fields like {@link
+ * CausedByDrain}, and is designed to be extensible to support future metadata fields such as
+ * OpenTelemetry context or CDC (Change Data Capture) kind.
+ *
+ * <p>The purpose of this class is to group targeted metadata fields together. This makes it easier
+ * to define combination strategies (e.g., when accumulating state in {@code ReduceFnRunner}) when
+ * multiple elements are merged or grouped, without having to extend method signatures or state
+ * handling for every new metadata field.
+ */
+@AutoValue
+public abstract class CombinedMetadata {
+ public abstract CausedByDrain causedByDrain();
+
+ public static CombinedMetadata create(CausedByDrain causedByDrain) {
+ return new AutoValue_CombinedMetadata(causedByDrain);
+ }
+
+ public static CombinedMetadata createDefault() {
+ return create(CausedByDrain.NORMAL);
+ }
+
+ public static class Coder extends AtomicCoder<CombinedMetadata> {
+ private static final Coder INSTANCE = new Coder();
+
+ public static Coder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
+ BeamFnApi.Elements.ElementMetadata proto =
+ BeamFnApi.Elements.ElementMetadata.newBuilder()
+ .setDrain(
+ value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
+ ? BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING)
+ .build();
+ proto.writeDelimitedTo(outStream);
Review Comment:
Is this implemention the same as using `ProtoCoder.of(ElementMetadata.class)` ?
https://github.com/apache/beam/blob/16609ed210b059946638bad019f3f05918bf9bdf/sdks/java/extensions/protobuf/src/main/java/org/apache/beam/sdk/extensions/protobuf/ProtoCoder.java#L116
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadataCombiner.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import org.apache.beam.sdk.transforms.Combine.CombineFn;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/** Combiner for CombinedMetadata. */
+class CombinedMetadataCombiner
Review Comment:
Pretty sure this is the same as `BinaryCombineFn` default implementations. But since I hate inheritance, I'm happy to have it spelled out here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4287839075
@kennknowles this is generally finished, the task :runners:core-java:analyzeClassesDependencies is failing because of an undeclared dependency on beam.model:fn-execution.
I need to add the missing dependency in runners/core-java/build.gradle.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz merged PR #38230:
URL: https://github.com/apache/beam/pull/38230
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "kennknowles (via GitHub)" <gi...@apache.org>.
kennknowles commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3130513851
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -590,6 +595,17 @@ private void processElement(Map<W, W> windowToMergeResult, WindowedValue<InputT>
value.getTimestamp(),
StateStyle.DIRECT,
value.causedByDrain());
+
+ ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ CombinedMetadata currentMetadata = metadataState.read();
+ if (currentMetadata == null) {
+ currentMetadata = CombinedMetadata.createDefault();
+ }
+ CombinedMetadata inputMetadata = CombinedMetadata.create(value.causedByDrain());
+ CombinedMetadata newMetadata =
+ CombinedMetadataCombiner.of().addInput(currentMetadata, inputMetadata);
+ metadataState.write(newMetadata);
Review Comment:
Yes, this is correct. With a combining state, you would do write (without reads) of each thing into a bag, and they are combined on read. It would be a a blocker if we had to read-modify-write on each element.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4388983410
https://docs.google.com/document/d/1yOFbaH5DwcKV96VRYrGAyow9lzqpfAoDs3yvj8_AxRI/edit?usp=sharing
done test for Dataflow v1, v1 with element metadata experiment, v2.
Baseline revision was updated to revision including the change, update was successful. All versions (v1, v2) were combining metadata and v1 with experiment was able to aggregate drain as it has received it correctly from streaming engine
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4373694253
@kennknowles this is ready.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4354547140
Not ready yet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Refactor] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4267586323
R: @kennknowles
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4378889655
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3189755421
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadata.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import com.google.auto.value.AutoValue;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/**
+ * Encapsulates metadata that propagates with elements in the pipeline.
+ *
+ * <p>This metadata is sent along with elements. It currently includes fields like {@link
+ * CausedByDrain}, and is designed to be extensible to support future metadata fields such as
+ * OpenTelemetry context or CDC (Change Data Capture) kind.
+ *
+ * <p>The purpose of this class is to group targeted metadata fields together. This makes it easier
+ * to define combination strategies (e.g., when accumulating state in {@code ReduceFnRunner}) when
+ * multiple elements are merged or grouped, without having to extend method signatures or state
+ * handling for every new metadata field.
+ */
+@AutoValue
+public abstract class CombinedMetadata {
+ public abstract CausedByDrain causedByDrain();
+
+ public static CombinedMetadata create(CausedByDrain causedByDrain) {
+ return new AutoValue_CombinedMetadata(causedByDrain);
+ }
+
+ public static CombinedMetadata createDefault() {
+ return create(CausedByDrain.NORMAL);
+ }
+
+ public static class Coder extends AtomicCoder<CombinedMetadata> {
+ private static final Coder INSTANCE = new Coder();
+
+ public static Coder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
+ BeamFnApi.Elements.ElementMetadata proto =
+ BeamFnApi.Elements.ElementMetadata.newBuilder()
+ .setDrain(
+ value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
+ ? BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING)
+ .build();
+ proto.writeDelimitedTo(outStream);
Review Comment:
it's almost the same, but as discussed, don't want to bring extension dependency.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3187939128
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -1009,8 +1026,22 @@ private void prefetchOnTrigger(
ReduceFn<K, InputT, OutputT, W>.Context renamedContext,
final boolean isFinished,
boolean isEndOfWindow,
- CausedByDrain causedByDrain)
+ CombinedMetadata metadata)
throws Exception {
+ CombiningState<CombinedMetadata, CombinedMetadata, CombinedMetadata> metadataState =
+ directContext.state().access(METADATA_TAG);
+ CombinedMetadata aggregatedMetadata = metadataState.read();
+ if (aggregatedMetadata == null) {
+ aggregatedMetadata = CombinedMetadata.createDefault();
+ }
+ CombinedMetadata fullyAggregatedMetadata =
+ CombinedMetadataCombiner.of().addInput(aggregatedMetadata, metadata);
+ final CausedByDrain aggregatedCausedByDrain = fullyAggregatedMetadata.causedByDrain();
+ if (isFinished) {
+ metadataState.clear();
+ } else if (!metadata.equals(CombinedMetadata.createDefault())) {
+ metadataState.add(metadata);
+ }
Review Comment:

In `onTrigger`, the trigger's `metadata` is added to the state if `isFinished` is false. Since `METADATA_TAG` is a `CombiningState` using `CombinedMetadataCombiner` (which performs a logical OR for `causedByDrain`), adding the same metadata multiple times is idempotent for the current implementation. However, if future metadata fields are added that are not idempotent, this logic might lead to incorrect aggregation. Consider if the trigger's metadata should only be used for the current output pane or if it truly represents a state change that must persist for all future panes of this window.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3126019707
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadata.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import com.google.auto.value.AutoValue;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.coders.ByteArrayCoder;
+import org.apache.beam.sdk.coders.NullableCoder;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/**
+ * Encapsulates metadata that propagates with elements in the pipeline.
+ *
+ * <p>This metadata is sent along with elements. It currently includes fields like {@link
+ * CausedByDrain}, and is designed to be extensible to support future metadata fields such as
+ * OpenTelemetry context or CDC (Change Data Capture) kind.
+ *
+ * <p>The purpose of this class is to group targeted metadata fields together. This makes it easier
+ * to define combination strategies (e.g., when accumulating state in {@code ReduceFnRunner}) when
+ * multiple elements are merged or grouped, without having to extend method signatures or state
+ * handling for every new metadata field.
+ */
+@AutoValue
+public abstract class CombinedMetadata {
+ public abstract CausedByDrain causedByDrain();
+
+ public static CombinedMetadata create(CausedByDrain causedByDrain) {
+ return new AutoValue_CombinedMetadata(causedByDrain);
+ }
+
+ public static CombinedMetadata createDefault() {
+ return create(CausedByDrain.NORMAL);
+ }
+
+ public static class Coder extends AtomicCoder<CombinedMetadata> {
+ private static final Coder INSTANCE = new Coder();
+
+ public static Coder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
+ if (value == null) {
+ NullableCoder.of(ByteArrayCoder.of()).encode(null, outStream);
+ return;
+ }
+ BeamFnApi.Elements.ElementMetadata.Builder builder =
+ BeamFnApi.Elements.ElementMetadata.newBuilder();
+ builder.setDrain(
+ value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
+ ? BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING);
+
+ NullableCoder.of(ByteArrayCoder.of()).encode(builder.build().toByteArray(), outStream);
Review Comment:
this one is interesting.
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -1009,8 +1029,19 @@ private void prefetchOnTrigger(
ReduceFn<K, InputT, OutputT, W>.Context renamedContext,
final boolean isFinished,
boolean isEndOfWindow,
- CausedByDrain causedByDrain)
+ CombinedMetadata metadata)
throws Exception {
+ ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ CombinedMetadata aggregatedMetadata = metadataState.read();
+ if (aggregatedMetadata == null) {
+ aggregatedMetadata = CombinedMetadata.createDefault();
+ }
+ CombinedMetadata fullyAggregatedMetadata =
+ CombinedMetadataCombiner.of().addInput(aggregatedMetadata, metadata);
+ final CausedByDrain aggregatedCausedByDrain = fullyAggregatedMetadata.causedByDrain();
+ if (isFinished) {
+ metadataState.clear();
+ }
Review Comment:
this is good one!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3126082820
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -590,6 +595,17 @@ private void processElement(Map<W, W> windowToMergeResult, WindowedValue<InputT>
value.getTimestamp(),
StateStyle.DIRECT,
value.causedByDrain());
+
+ ValueState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ CombinedMetadata currentMetadata = metadataState.read();
+ if (currentMetadata == null) {
+ currentMetadata = CombinedMetadata.createDefault();
+ }
+ CombinedMetadata inputMetadata = CombinedMetadata.create(value.causedByDrain());
+ CombinedMetadata newMetadata =
+ CombinedMetadataCombiner.of().addInput(currentMetadata, inputMetadata);
+ metadataState.write(newMetadata);
Review Comment:
this is interesting observation, @kennknowles I'm curious about your opinion.
for every windowed value, we accumulate values in bagstate.
for metadata I've decided to implement value state, which requires read, mutate, write per element.
maybe I should rewrite it into CombiningState , would it improve performance?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4373867592
> @kennknowles this is ready.
well, I will go through those comments, and probably improve state..
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38230:
URL: https://github.com/apache/beam/pull/38230#discussion_r3183822825
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -107,6 +108,10 @@ public class ReduceFnRunner<K, InputT, OutputT, W extends BoundedWindow> {
* <li>It uses discarding or accumulation mode according to the {@link WindowingStrategy}.
* </ul>
*/
+ static final StateTag<BagState<CombinedMetadata>> METADATA_TAG =
+ StateTags.makeSystemTagInternal(
+ StateTags.bag("combinedMetadata", CombinedMetadata.Coder.of()));
Review Comment:

Using `BagState` for metadata that is always combined into a single value is inefficient. It leads to O(N) state growth (where N is the number of elements) and O(N) read/merge time during firing. Since the metadata (like `causedByDrain`) follows simple combination rules (e.g., OR logic), it is much more efficient to use a `CombiningState`. This allows the runner to store only the aggregated value and potentially combine updates eagerly, significantly reducing I/O and memory overhead for high-volume windows.
```suggestion
static final StateTag<CombiningState<CombinedMetadata, CombinedMetadata, CombinedMetadata>> METADATA_TAG =
StateTags.makeSystemTagInternal(
StateTags.combiningValue(
"combinedMetadata", CombinedMetadata.Coder.of(), CombinedMetadataCombiner.of()));
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -1009,8 +1025,21 @@ private void prefetchOnTrigger(
ReduceFn<K, InputT, OutputT, W>.Context renamedContext,
final boolean isFinished,
boolean isEndOfWindow,
- CausedByDrain causedByDrain)
+ CombinedMetadata metadata)
throws Exception {
+ BagState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ Iterable<CombinedMetadata> allMetadata = metadataState.read();
+ CombinedMetadata aggregatedMetadata =
+ CombinedMetadataCombiner.of().mergeAccumulators(allMetadata);
Review Comment:

Update this to use the `CombiningState` API. This simplifies the logic as the state already provides the aggregated value directly, avoiding the need to manually call `mergeAccumulators` on an iterable.
```suggestion
CombiningState<CombinedMetadata, CombinedMetadata, CombinedMetadata> metadataState =
directContext.state().access(METADATA_TAG);
CombinedMetadata aggregatedMetadata = metadataState.read();
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadata.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import com.google.auto.value.AutoValue;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.coders.ByteArrayCoder;
+import org.apache.beam.sdk.coders.NullableCoder;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/**
+ * Encapsulates metadata that propagates with elements in the pipeline.
+ *
+ * <p>This metadata is sent along with elements. It currently includes fields like {@link
+ * CausedByDrain}, and is designed to be extensible to support future metadata fields such as
+ * OpenTelemetry context or CDC (Change Data Capture) kind.
+ *
+ * <p>The purpose of this class is to group targeted metadata fields together. This makes it easier
+ * to define combination strategies (e.g., when accumulating state in {@code ReduceFnRunner}) when
+ * multiple elements are merged or grouped, without having to extend method signatures or state
+ * handling for every new metadata field.
+ */
+@AutoValue
+public abstract class CombinedMetadata {
+ public abstract CausedByDrain causedByDrain();
+
+ public static CombinedMetadata create(CausedByDrain causedByDrain) {
+ return new AutoValue_CombinedMetadata(causedByDrain);
+ }
+
+ public static CombinedMetadata createDefault() {
+ return create(CausedByDrain.NORMAL);
+ }
+
+ public static class Coder extends AtomicCoder<CombinedMetadata> {
+ private static final Coder INSTANCE = new Coder();
+
+ public static Coder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
+ if (value == null) {
+ NullableCoder.of(ByteArrayCoder.of()).encode(null, outStream);
+ return;
+ }
+ BeamFnApi.Elements.ElementMetadata.Builder builder =
+ BeamFnApi.Elements.ElementMetadata.newBuilder();
+ builder.setDrain(
+ value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
+ ? BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING);
+
+ NullableCoder.of(ByteArrayCoder.of()).encode(builder.build().toByteArray(), outStream);
+ }
+
+ @Override
+ public CombinedMetadata decode(InputStream inStream) throws IOException {
+ byte[] bytes = NullableCoder.of(ByteArrayCoder.of()).decode(inStream);
+ if (bytes == null) {
+ return CombinedMetadata.createDefault();
+ }
+ BeamFnApi.Elements.ElementMetadata proto =
+ BeamFnApi.Elements.ElementMetadata.parseFrom(bytes);
+
+ CausedByDrain causedByDrain =
+ proto.getDrain() == BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ ? CausedByDrain.CAUSED_BY_DRAIN
+ : CausedByDrain.NORMAL;
+
+ return CombinedMetadata.create(causedByDrain);
+ }
Review Comment:

Simplify the decoding logic to match the delimited proto encoding. `parseDelimitedFrom` returns `null` if the stream is at EOF, which can be used to return the default metadata.
```suggestion
@Override
public CombinedMetadata decode(InputStream inStream) throws IOException {
BeamFnApi.Elements.ElementMetadata proto =
BeamFnApi.Elements.ElementMetadata.parseDelimitedFrom(inStream);
if (proto == null) {
return CombinedMetadata.createDefault();
}
CausedByDrain causedByDrain =
proto.getDrain() == BeamFnApi.Elements.DrainMode.Enum.DRAINING
? CausedByDrain.CAUSED_BY_DRAIN
: CausedByDrain.NORMAL;
return CombinedMetadata.create(causedByDrain);
}
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/CombinedMetadata.java:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.core;
+
+import com.google.auto.value.AutoValue;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import org.apache.beam.model.fnexecution.v1.BeamFnApi;
+import org.apache.beam.sdk.coders.AtomicCoder;
+import org.apache.beam.sdk.coders.ByteArrayCoder;
+import org.apache.beam.sdk.coders.NullableCoder;
+import org.apache.beam.sdk.values.CausedByDrain;
+
+/**
+ * Encapsulates metadata that propagates with elements in the pipeline.
+ *
+ * <p>This metadata is sent along with elements. It currently includes fields like {@link
+ * CausedByDrain}, and is designed to be extensible to support future metadata fields such as
+ * OpenTelemetry context or CDC (Change Data Capture) kind.
+ *
+ * <p>The purpose of this class is to group targeted metadata fields together. This makes it easier
+ * to define combination strategies (e.g., when accumulating state in {@code ReduceFnRunner}) when
+ * multiple elements are merged or grouped, without having to extend method signatures or state
+ * handling for every new metadata field.
+ */
+@AutoValue
+public abstract class CombinedMetadata {
+ public abstract CausedByDrain causedByDrain();
+
+ public static CombinedMetadata create(CausedByDrain causedByDrain) {
+ return new AutoValue_CombinedMetadata(causedByDrain);
+ }
+
+ public static CombinedMetadata createDefault() {
+ return create(CausedByDrain.NORMAL);
+ }
+
+ public static class Coder extends AtomicCoder<CombinedMetadata> {
+ private static final Coder INSTANCE = new Coder();
+
+ public static Coder of() {
+ return INSTANCE;
+ }
+
+ @Override
+ public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
+ if (value == null) {
+ NullableCoder.of(ByteArrayCoder.of()).encode(null, outStream);
+ return;
+ }
+ BeamFnApi.Elements.ElementMetadata.Builder builder =
+ BeamFnApi.Elements.ElementMetadata.newBuilder();
+ builder.setDrain(
+ value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
+ ? BeamFnApi.Elements.DrainMode.Enum.DRAINING
+ : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING);
+
+ NullableCoder.of(ByteArrayCoder.of()).encode(builder.build().toByteArray(), outStream);
+ }
Review Comment:

The coder implementation is unnecessarily complex and inefficient. Using `NullableCoder` and `ByteArrayCoder` inside an `AtomicCoder` adds multiple layers of overhead (null markers, length prefixing). Since `CombinedMetadata` is backed by a proto, we can use the proto's built-in delimited encoding which is more efficient and handles length prefixing naturally. Additionally, `AtomicCoder` implementations should generally be deterministic and not handle nulls unless explicitly intended to be used in a context where nulls are expected (which is not the case for state elements here).
```java
@Override
public void encode(CombinedMetadata value, OutputStream outStream) throws IOException {
BeamFnApi.Elements.ElementMetadata proto =
BeamFnApi.Elements.ElementMetadata.newBuilder()
.setDrain(
value.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN
? BeamFnApi.Elements.DrainMode.Enum.DRAINING
: BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING)
.build();
proto.writeDelimitedTo(outStream);
}
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -1009,8 +1025,21 @@ private void prefetchOnTrigger(
ReduceFn<K, InputT, OutputT, W>.Context renamedContext,
final boolean isFinished,
boolean isEndOfWindow,
- CausedByDrain causedByDrain)
+ CombinedMetadata metadata)
throws Exception {
+ BagState<CombinedMetadata> metadataState = directContext.state().access(METADATA_TAG);
+ Iterable<CombinedMetadata> allMetadata = metadataState.read();
+ CombinedMetadata aggregatedMetadata =
+ CombinedMetadataCombiner.of().mergeAccumulators(allMetadata);
+
+ CombinedMetadata fullyAggregatedMetadata =
+ CombinedMetadataCombiner.of().addInput(aggregatedMetadata, metadata);
+ final CausedByDrain aggregatedCausedByDrain = fullyAggregatedMetadata.causedByDrain();
+ if (isFinished) {
+ metadataState.clear();
+ } else {
+ metadataState.add(metadata);
+ }
Review Comment:

Apply the same optimization here to avoid adding default metadata to the state during trigger firing.
```suggestion
} else if (!metadata.equals(CombinedMetadata.createDefault())) {
metadataState.add(metadata);
}
```
##########
runners/core-java/src/main/java/org/apache/beam/runners/core/ReduceFnRunner.java:
##########
@@ -604,6 +610,11 @@ private void processElement(Map<W, W> windowToMergeResult, WindowedValue<InputT>
continue;
}
+ directContext
+ .state()
+ .access(METADATA_TAG)
+ .add(CombinedMetadata.create(value.causedByDrain()));
Review Comment:

To avoid unnecessary state writes for every element, we should only add metadata to the state if it differs from the default (identity) value. Since `CombinedMetadata.createDefault()` represents the neutral element for combination (e.g., `NORMAL` for drain status), skipping it does not affect the final result but significantly improves performance in the common case where elements are not marked as "caused by drain".
```suggestion
CombinedMetadata metadata = CombinedMetadata.create(value.causedByDrain());
if (!metadata.equals(CombinedMetadata.createDefault())) {
directContext.state().access(METADATA_TAG).add(metadata);
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4387755628
before merging I will do job upgrade test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Refactor] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4267586345
## Summary of Changes
Hello, I'm Gemini Code Assist[^1]! 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 refactors the metadata propagation logic within `ReduceFnRunner` to ensure metadata is correctly maintained throughout the pipeline execution. By introducing a unified stateful container for element metadata and a dedicated aggregator, the change resolves issues where metadata was previously lost during grouping operations and provides a scalable architecture for incorporating additional metadata types in the future.
### Highlights
* **Stateful Metadata Tracking**: Introduced `METADATA_TAG` in `ReduceFnRunner` to persist `PipelineMetadata` in state, preventing metadata loss during grouping and timer firing.
* **Extensible Metadata Container**: Created `PipelineMetadata` using `@AutoValue` to group element metadata, allowing for easier addition of future fields like OpenTelemetry context or CDC markers.
* **Metadata Aggregation**: Implemented `PipelineMetadataCombiner` to encapsulate logic for combining metadata when elements are merged or grouped.
🧠**New Feature in Public Preview:** You can now enable **Memory** 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](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
<details>
<summary><b>Using Gemini Code Assist</b></summary>
<br>
The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
<b>Invoking Gemini</b>
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.
<b>Customization</b>
To customize 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](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
<b>Limitations & Feedback</b>
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: 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](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
</details>
[^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4289350457
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4378641731
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4379001452
new state can and will increase data processed by few percent.
this pipeline had 2% data processed increased.
```
public static void main(String[] args) {
PipelineOptions options = PipelineOptionsFactory.fromArgs(args).create();
Pipeline p = Pipeline.create(options);
p
// Read taxi ride data
.apply("ReadFromPubSub", PubsubIO.readStrings().fromTopic(TAXI_RIDES_TOPIC))
// Convert JSON strings to Beam Rows
.apply("JsonToRow", JsonToRow.withSchema(TAXI_RIDE_INFO_SCHEMA))
// Introduce withKeys transform with random value from 0 to 10
.apply(
"WithRandomKey",
WithKeys.of(
new SerializableFunction<Row, Integer>() {
@Override
public Integer apply(Row input) {
return ThreadLocalRandom.current().nextInt(11);
}
})
.withKeyType(TypeDescriptors.integers()))
// Setup sliding window, with 1 minute period, 5 minute length
.apply(
"SlidingWindow",
Window.<KV<Integer, Row>>into(
SlidingWindows.of(Duration.standardMinutes(5)).every(Duration.standardMinutes(1))))
.apply(
"FilterRows",
ParDo.of(
new DoFn<KV<Integer, Row>, KV<Integer, Row>>() {
@ProcessElement
public void processElement(
@Element KV<Integer, Row> kv, OutputReceiver<KV<Integer, Row>> receiver) {
receiver.builder(kv).setCausedByDrain(CausedByDrain.CAUSED_BY_DRAIN).output();
}
}))
// GroupByKey
.apply("GroupByKey", GroupByKey.<Integer, Row>create())
// ParDo that takes KV<Integer, Iterable<Row>>
.apply(
"ProcessGroupedRows",
ParDo.of(
new DoFn<KV<Integer, Iterable<Row>>, Void>() {
@ProcessElement
public void processElement(
@Element KV<Integer, Iterable<Row>> kv, CausedByDrain drain) {
Integer key = kv.getKey();
Iterable<Row> rows = kv.getValue();
int passengerSum = 0;
for (Row row : rows) {
Integer passengers = row.getInt32("passenger_count");
if (passengers != null) {
passengerSum += passengers;
}
}
System.out.println(
"Partition "
+ key
+ " had a sum of "
+ passengerSum
+ " passengers. Aggregation was drained? - "
+ drain);
}
}));
p.run();
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [Drain] Support extensible element metadata propagation in ReduceFnRunner [beam]
Posted by "stankiewicz (via GitHub)" <gi...@apache.org>.
stankiewicz commented on PR #38230:
URL: https://github.com/apache/beam/pull/38230#issuecomment-4373695997
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org