You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "junaiddshaukat (via GitHub)" <gi...@apache.org> on 2026/07/26 15:25:37 UTC
[PR] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
junaiddshaukat opened a new pull request, #39494:
URL: https://github.com/apache/beam/pull/39494
## Summary
Part of #18479.
Adds real windowing (and the triggering machinery that comes with it) to the Kafka Streams runner's GroupByKey, which until now only handled the global window. The approach follows the Flink and Spark portable runners: run Beam's `ReduceFnRunner` on the runner side, backed by Kafka Streams state and timers. Design discussed on the dev@ list and with the mentor beforehand.
## What changed
The global-window `GroupByKeyProcessor` is replaced by `WindowedGroupByKeyProcessor`, which drives `ReduceFnRunner` per key — the same way `GroupAlsoByWindowViaWindowSetNewDoFn` does — over two new backends:
- **`KafkaStreamsStateInternals`** — Beam's `StateInternals` over a Kafka Streams `KeyValueStore`. Each state cell (value, bag, combining, watermark-hold) is one store entry under a composite key `key | namespace | tag`, so a window's state lives in its own namespace and writes go straight to the changelogged store. Modelled on the Spark runner's `SparkStateInternals`.
- **`KafkaStreamsTimerInternals`** — timers persisted in a store keyed by timer identity. On each input-watermark advance the processor scans for event-time timers whose fire time has passed and replays them through `ReduceFnRunner.onTimers`, which is what makes windows emit their panes.
`GroupByKeyTranslator` hydrates the input PCollection's `WindowingStrategy` from the pipeline proto and wires the state and timer stores. Windowing, the default trigger, panes, allowed lateness and timestamp combiners all come from `ReduceFnRunner`.
## Test harness: dropped the manual repartition round-trip
While testing this I found that `KafkaStreamsTestRunner.roundTripInternalTopics` was delivering every record through the GroupByKey repartition topic **twice**. `TopologyTestDriver` (Kafka Streams 3.9) already loops an internal repartition topic from its sink back to its source within a driver step, so the manual round-trip was redundant and double-fed the topic. The previous global-window GroupByKey masked this because it fired every key once at the terminal watermark and then latched; a correctly windowed GroupByKey emits a late pane for the duplicate delivery, which surfaced the bug.
Removed the round-trip machinery. Advancing the wall clock now drives the whole pipeline to completion, and the full runner suite confirms `TopologyTestDriver` loops internal topics on its own.
## Results
`validatesRunner` goes from 44 to 49 tests:
| Suite | Before | After |
| --- | --- | --- |
| `GroupByKeyTest$BasicTests` | 7 | 9 (timestamp combiners un-sickbayed) |
| `GroupByKeyTest$WindowTests` | 0 (whole class sickbayed) | 3 |
`WindowTests.testGroupByKeyMergingWindows` stays sickbayed: session (merging) windows need `ReduceFnRunner`'s merging window set to move per-window state as windows merge, which this first pass does not implement. Fixed and sliding windows, the default trigger and timestamp combiners all work. Merging windows and richer triggers land in a follow-up.
Also adds a focused runner unit test (`FixedWindowGroupByKeyTest`) that groups the same key across two fixed windows, and folds the `#39452` reference into the `LifecycleTests` sickbay comment.
## Testing
```
./gradlew :runners:kafka-streams:validatesRunner # 49 tests, 0 failures
./gradlew :runners:kafka-streams:build # unit tests + spotless + checker + errorprone
```
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "junaiddshaukat (via GitHub)" <gi...@apache.org>.
junaiddshaukat commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3656513582
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/KafkaStreamsStateInternals.java:
##########
@@ -0,0 +1,393 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.StateNamespace;
+import org.apache.beam.runners.core.StateTag;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.coders.InstantCoder;
+import org.apache.beam.sdk.coders.ListCoder;
+import org.apache.beam.sdk.state.BagState;
+import org.apache.beam.sdk.state.CombiningState;
+import org.apache.beam.sdk.state.MapState;
+import org.apache.beam.sdk.state.MultimapState;
+import org.apache.beam.sdk.state.OrderedListState;
+import org.apache.beam.sdk.state.ReadableState;
+import org.apache.beam.sdk.state.SetState;
+import org.apache.beam.sdk.state.State;
+import org.apache.beam.sdk.state.StateBinder;
+import org.apache.beam.sdk.state.StateContext;
+import org.apache.beam.sdk.state.StateSpec;
+import org.apache.beam.sdk.state.ValueState;
+import org.apache.beam.sdk.state.WatermarkHoldState;
+import org.apache.beam.sdk.transforms.Combine.CombineFn;
+import org.apache.beam.sdk.transforms.CombineWithContext;
+import org.apache.beam.sdk.transforms.windowing.TimestampCombiner;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.CombineFnUtil;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * A {@link StateInternals} for one key, backed by a Kafka Streams {@link KeyValueStore}.
+ *
+ * <p>Beam addresses a state cell by {@code (key, StateNamespace, StateTag)}; a windowed pipeline
+ * puts each window's state in its own namespace. Every cell is stored as one entry in the shared
+ * per-transform store under a composite byte key {@code len(key)|key | len(ns)|ns | len(tag)|tag},
+ * so all cells for one Beam key share a prefix and a whole key's state can be range-scanned. The
+ * value is the cell's contents encoded with its Beam {@link Coder}. Writing straight to the store
+ * (rather than buffering and flushing) keeps this restart-safe for free: the store is changelogged
+ * and, under exactly-once, its writes commit atomically with the input offsets.
+ *
+ * <p>Modeled on the Spark runner's {@code SparkStateInternals}; the difference is that each cell
+ * reads and writes its own store entry instead of an in-memory table, so there is no separate
+ * persist step.
+ */
+class KafkaStreamsStateInternals<K> implements StateInternals {
+
+ private final @NonNull K key;
+ private final byte[] encodedKey;
+ private final KeyValueStore<byte[], byte[]> store;
+
+ KafkaStreamsStateInternals(
+ @NonNull K key, byte[] encodedKey, KeyValueStore<byte[], byte[]> store) {
+ this.key = key;
+ this.encodedKey = encodedKey;
+ this.store = store;
+ }
+
+ @Override
+ public Object getKey() {
+ return key;
+ }
+
+ @Override
+ public <T extends State> T state(
+ StateNamespace namespace, StateTag<T> address, StateContext<?> c) {
+ return address.getSpec().bind(address.getId(), new KafkaStreamsStateBinder(namespace, c));
+ }
+
+ /** The composite store key for one cell: {@code len|key len|namespace len|tagId}. */
+ private byte[] compositeKey(StateNamespace namespace, String id) {
Review Comment:
Done, it now builds into one exactly-sized array with System.arraycopy, and caches the key | namespace prefix, which is reused across the several tags one ReduceFnRunner turn touches. That removes the stream growth and the final copy.
I kept the length prefixes rather than a separator, though: an encoded key is arbitrary coder output and a namespace stringKey can contain any byte too, so key="a/b", ns="c" and key="a", ns="b/c" would produce the same bytes with any separator. The prefixes are also what lets the timer scan read the encoded key back out (your comment below). I moved the byte helpers into StoreKeys and wrote the reasoning there.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "junaiddshaukat (via GitHub)" <gi...@apache.org>.
junaiddshaukat commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3656511259
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/KafkaStreamsTimerInternals.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import org.apache.beam.runners.core.StateNamespace;
+import org.apache.beam.runners.core.TimerInternals;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * A {@link TimerInternals} for one key, backed by a shared Kafka Streams timer {@link
+ * KeyValueStore} for a GroupByKey.
+ *
+ * <p>Kafka Streams has no per-key timer service, so timers are persisted like any other state. A
+ * timer is stored under a key built from its identity — {@code key | domain | timerFamily | timerId
+ * | namespace} — so setting a timer with the same identity overwrites the previous one and deleting
+ * it removes exactly that entry, matching {@link TimerInternals}' contract. The value is the {@link
+ * TimerData} encoded with {@link TimerInternals.TimerDataCoderV2}, which carries the fire time.
+ *
+ * <p>Firing is driven by {@link WindowedGroupByKeyProcessor}: on a watermark advance it scans the
+ * store for event-time timers whose fire time has passed and replays them through {@link
+ * org.apache.beam.runners.core.ReduceFnRunner#onTimers}. Scanning the whole store per advance is
+ * O(timers); acceptable for this first windowing support and replaceable with a fire-time-ordered
+ * index later, the same way the initial GroupByKey buffered eagerly.
+ *
+ * <p>This instance reports the current input-watermark and processing times it was constructed with
+ * (the caller advances them as reports arrive); it never fires timers itself.
+ */
+class KafkaStreamsTimerInternals implements TimerInternals {
+
+ private final byte[] encodedKey;
+ private final KeyValueStore<byte[], byte[]> timerStore;
+ private final TimerInternals.TimerDataCoderV2 timerCoder;
+ private final Instant inputWatermarkTime;
+ private final Instant processingTime;
+
+ KafkaStreamsTimerInternals(
+ byte[] encodedKey,
+ KeyValueStore<byte[], byte[]> timerStore,
+ Coder<? extends BoundedWindow> windowCoder,
+ Instant inputWatermarkTime,
+ Instant processingTime) {
+ this.encodedKey = encodedKey;
+ this.timerStore = timerStore;
+ this.timerCoder = TimerInternals.TimerDataCoderV2.of(windowCoder);
+ this.inputWatermarkTime = inputWatermarkTime;
+ this.processingTime = processingTime;
+ }
+
+ @Override
+ public void setTimer(
+ StateNamespace namespace,
+ String timerId,
+ String timerFamilyId,
+ Instant target,
+ Instant outputTimestamp,
+ TimeDomain timeDomain) {
+ setTimer(TimerData.of(timerId, timerFamilyId, namespace, target, outputTimestamp, timeDomain));
+ }
+
+ @Override
+ public void setTimer(TimerData timerData) {
+ timerStore.put(timerStoreKey(encodedKey, timerData), encodeTimer(timerData));
+ }
+
+ @Override
+ public void deleteTimer(
+ StateNamespace namespace, String timerId, String timerFamilyId, TimeDomain timeDomain) {
+ timerStore.delete(timerStoreKey(encodedKey, timerId, timerFamilyId, timeDomain, namespace));
+ }
+
+ @Override
+ public void deleteTimer(StateNamespace namespace, String timerId, String timerFamilyId) {
+ throw new UnsupportedOperationException(
+ "Deleting a timer without a time domain is not supported; the domain is part of a timer's"
+ + " store identity.");
+ }
+
+ @Override
+ public void deleteTimer(TimerData timerKey) {
+ timerStore.delete(timerStoreKey(encodedKey, timerKey));
+ }
+
+ @Override
+ public Instant currentProcessingTime() {
+ return processingTime;
+ }
+
+ @Override
+ public @Nullable Instant currentSynchronizedProcessingTime() {
+ return null;
+ }
+
+ @Override
+ public Instant currentInputWatermarkTime() {
+ return inputWatermarkTime;
+ }
+
+ @Override
+ public @Nullable Instant currentOutputWatermarkTime() {
+ return null;
Review Comment:
Added. currentOutputWatermarkTime no longer returns null — it now returns the watermark the GroupByKey has actually published, which trails the input watermark by the pending holds (the watermark-hold comment below).
currentSynchronizedProcessingTime still returns null, and I documented why: it's the slowest processing time across the job's workers, which needs cross-instance coordination our watermark reports only carry for event time. TimerInternals allows null, and nothing on the paths supported today reads it — it's for processing-time triggers, which land with processing-time timer support in the follow-up, the same work that would supply it.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "junaiddshaukat (via GitHub)" <gi...@apache.org>.
junaiddshaukat commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3656507901
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/WindowedGroupByKeyProcessor.java:
##########
@@ -0,0 +1,284 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.core.NullSideInputReader;
+import org.apache.beam.runners.core.ReduceFnRunner;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.SystemReduceFn;
+import org.apache.beam.runners.core.TimerInternals.TimerData;
+import org.apache.beam.runners.core.triggers.ExecutableTriggerStateMachine;
+import org.apache.beam.runners.core.triggers.TriggerStateMachines;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.construction.TriggerTranslation;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.WindowedValue;
+import org.apache.beam.sdk.values.WindowingStrategy;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.io.BaseEncoding;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes a windowed {@code GroupByKey} by driving Beam's {@link ReduceFnRunner} — the same
+ * windowing + triggering state machine the Flink and Spark portable runners use — with Kafka
+ * Streams state and timers behind it.
+ *
+ * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key
+ * is co-located here. For each data record this builds a {@link ReduceFnRunner} for that key over a
+ * {@link KafkaStreamsStateInternals} and {@link KafkaStreamsTimerInternals} (both backed by
+ * persistent stores) and feeds the element in; the runner assigns it to windows, updates the
+ * trigger state, and sets any timers it needs. When the aggregated input watermark advances, every
+ * event-time timer whose fire time has passed is replayed through {@code onTimers}, which is what
+ * makes windows emit their panes. The runner is stateless between records — all durable state lives
+ * in the stores — so a fresh one per record is correct, mirroring {@code
+ * GroupAlsoByWindowViaWindowSetNewDoFn}.
+ *
+ * <p>This first version supports the default trigger and non-merging windows well; richer triggers,
+ * processing-time timers and session (merging) windows build on the same machinery in a follow-up.
+ */
+class WindowedGroupByKeyProcessor<K, V, W extends BoundedWindow>
+ implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WindowedGroupByKeyProcessor.class);
+
+ private final String stateStoreName;
+ private final String timerStoreName;
+ private final String transformId;
+ private final Coder<K> keyCoder;
+ private final WindowingStrategy<?, W> windowingStrategy;
+ private final Coder<? extends BoundedWindow> windowCoder;
+ private final RunnerApi.Trigger triggerProto;
+ private final SystemReduceFn<K, V, Iterable<V>, Iterable<V>, W> reduceFn;
+ private final PipelineOptions options;
+
+ private final WatermarkAggregator watermarkAggregator;
+ private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+ private Instant inputWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+
+ private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context;
+ private @Nullable KeyValueStore<byte[], byte[]> stateStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerStore;
+
+ WindowedGroupByKeyProcessor(
+ String stateStoreName,
+ String timerStoreName,
+ String transformId,
+ Set<String> upstreamTransformIds,
+ Coder<K> keyCoder,
+ Coder<V> valueCoder,
+ WindowingStrategy<?, W> windowingStrategy,
+ PipelineOptions options) {
+ this.stateStoreName = stateStoreName;
+ this.timerStoreName = timerStoreName;
+ this.transformId = transformId;
+ this.keyCoder = keyCoder;
+ this.windowingStrategy = windowingStrategy;
+ this.windowCoder = windowingStrategy.getWindowFn().windowCoder();
+ this.triggerProto = TriggerTranslation.toProto(windowingStrategy.getTrigger());
+ this.reduceFn = SystemReduceFn.buffering(valueCoder);
+ this.options = options;
+ this.watermarkAggregator = new WatermarkAggregator(upstreamTransformIds);
+ }
+
+ @Override
+ public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) {
+ this.context = context;
+ this.stateStore = context.getStateStore(stateStoreName);
+ this.timerStore = context.getStateStore(timerStoreName);
+ }
+
+ @Override
+ public void process(Record<byte[], KStreamsPayload<?>> record) {
+ KStreamsPayload<?> payload = record.value();
+ if (payload == null) {
+ LOG.warn(
+ "GroupByKey {} dropping record with null payload (external write or tombstone)",
+ transformId);
+ return;
+ }
+ if (payload.isData()) {
+ processData(record, payload);
+ return;
+ }
+ watermarkAggregator.observe(payload.asWatermark());
+ Instant advanced = watermarkAggregator.advance();
+ if (advanced.isAfter(lastForwardedWatermark)) {
+ inputWatermark = advanced;
+ fireDueEventTimeTimers(record, advanced);
+ lastForwardedWatermark = advanced;
+ forwardWatermark(record, advanced.getMillis());
+ }
+ }
+
+ private void processData(Record<byte[], KStreamsPayload<?>> record, KStreamsPayload<?> payload) {
+ byte[] encodedKey = record.key();
+ if (encodedKey == null) {
+ throw new IllegalStateException("GroupByKey data record is missing its key");
+ }
+ @SuppressWarnings("unchecked")
+ WindowedValue<KV<K, V>> element = (WindowedValue<KV<K, V>>) payload.getData();
+ K key = decodeKey(encodedKey);
+ WindowedValue<V> valueElement = element.withValue(element.getValue().getValue());
+ runReduceFn(
+ record, encodedKey, key, Collections.singletonList(valueElement), Collections.emptyList());
+ }
+
+ /** Fires every event-time timer whose fire time is at or before the new input watermark. */
+ private void fireDueEventTimeTimers(
+ Record<byte[], KStreamsPayload<?>> record, Instant watermark) {
+ KeyValueStore<byte[], byte[]> timers = checkInitialized(timerStore);
+ // Group due timers by the Beam key they belong to; a key's timers fire together in one
+ // ReduceFnRunner turn. Whole-store scan per advance is O(timers) — see the class doc.
+ Map<String, DueTimers> dueByKey = new LinkedHashMap<>();
+ List<byte[]> firedStoreKeys = new ArrayList<>();
+ try (KeyValueIterator<byte[], byte[]> it = timers.all()) {
Review Comment:
Fixed, this was the right call. Timers are now in two stores: the identity store (key/domain/family/id/namespace → index key) for overwrite and delete, and a new index store keyed domain | fireTimestamp | identity whose value is the TimerData.
Firing is now one range() over (-inf, watermark] on the index, so the cost is proportional to the timers actually due rather than to the number of keys holding a timer, and no decode is needed to decide whether a timer is due. Timestamps are written sign-flipped big-endian so the unsigned byte order Kafka Streams compares keys by matches numeric order — negative timestamps included.
KafkaStreamsTimerInternalsTest covers the range scan, negative timestamps, replacing a timer (the old index entry must go, or it would still fire at the original time), deletion, two keys sharing the index, and processing-time timers being excluded from the event-time scan.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "junaiddshaukat (via GitHub)" <gi...@apache.org>.
junaiddshaukat commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3656509877
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/KafkaStreamsTimerInternals.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import org.apache.beam.runners.core.StateNamespace;
+import org.apache.beam.runners.core.TimerInternals;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * A {@link TimerInternals} for one key, backed by a shared Kafka Streams timer {@link
+ * KeyValueStore} for a GroupByKey.
+ *
+ * <p>Kafka Streams has no per-key timer service, so timers are persisted like any other state. A
+ * timer is stored under a key built from its identity — {@code key | domain | timerFamily | timerId
+ * | namespace} — so setting a timer with the same identity overwrites the previous one and deleting
+ * it removes exactly that entry, matching {@link TimerInternals}' contract. The value is the {@link
+ * TimerData} encoded with {@link TimerInternals.TimerDataCoderV2}, which carries the fire time.
+ *
+ * <p>Firing is driven by {@link WindowedGroupByKeyProcessor}: on a watermark advance it scans the
+ * store for event-time timers whose fire time has passed and replays them through {@link
+ * org.apache.beam.runners.core.ReduceFnRunner#onTimers}. Scanning the whole store per advance is
+ * O(timers); acceptable for this first windowing support and replaceable with a fire-time-ordered
+ * index later, the same way the initial GroupByKey buffered eagerly.
+ *
+ * <p>This instance reports the current input-watermark and processing times it was constructed with
+ * (the caller advances them as reports arrive); it never fires timers itself.
+ */
+class KafkaStreamsTimerInternals implements TimerInternals {
+
+ private final byte[] encodedKey;
+ private final KeyValueStore<byte[], byte[]> timerStore;
+ private final TimerInternals.TimerDataCoderV2 timerCoder;
+ private final Instant inputWatermarkTime;
+ private final Instant processingTime;
+
+ KafkaStreamsTimerInternals(
+ byte[] encodedKey,
+ KeyValueStore<byte[], byte[]> timerStore,
+ Coder<? extends BoundedWindow> windowCoder,
+ Instant inputWatermarkTime,
+ Instant processingTime) {
+ this.encodedKey = encodedKey;
+ this.timerStore = timerStore;
+ this.timerCoder = TimerInternals.TimerDataCoderV2.of(windowCoder);
+ this.inputWatermarkTime = inputWatermarkTime;
+ this.processingTime = processingTime;
+ }
+
+ @Override
+ public void setTimer(
+ StateNamespace namespace,
+ String timerId,
+ String timerFamilyId,
+ Instant target,
+ Instant outputTimestamp,
+ TimeDomain timeDomain) {
+ setTimer(TimerData.of(timerId, timerFamilyId, namespace, target, outputTimestamp, timeDomain));
+ }
+
+ @Override
+ public void setTimer(TimerData timerData) {
+ timerStore.put(timerStoreKey(encodedKey, timerData), encodeTimer(timerData));
+ }
+
+ @Override
+ public void deleteTimer(
+ StateNamespace namespace, String timerId, String timerFamilyId, TimeDomain timeDomain) {
+ timerStore.delete(timerStoreKey(encodedKey, timerId, timerFamilyId, timeDomain, namespace));
+ }
+
+ @Override
+ public void deleteTimer(StateNamespace namespace, String timerId, String timerFamilyId) {
+ throw new UnsupportedOperationException(
+ "Deleting a timer without a time domain is not supported; the domain is part of a timer's"
+ + " store identity.");
+ }
+
+ @Override
+ public void deleteTimer(TimerData timerKey) {
+ timerStore.delete(timerStoreKey(encodedKey, timerKey));
+ }
+
+ @Override
+ public Instant currentProcessingTime() {
+ return processingTime;
+ }
+
+ @Override
+ public @Nullable Instant currentSynchronizedProcessingTime() {
+ return null;
+ }
+
+ @Override
+ public Instant currentInputWatermarkTime() {
+ return inputWatermarkTime;
+ }
+
+ @Override
+ public @Nullable Instant currentOutputWatermarkTime() {
+ return null;
+ }
+
+ private byte[] encodeTimer(TimerData timerData) {
+ try {
+ return CoderUtils.encodeToByteArray(timerCoder, timerData);
+ } catch (CoderException e) {
+ throw new RuntimeException("Failed to encode timer " + timerData, e);
+ }
+ }
+
+ /** The store key for a timer's identity. Package-visible so the processor can build/scan it. */
+ static byte[] timerStoreKey(byte[] encodedKey, TimerData timerData) {
+ return timerStoreKey(
+ encodedKey,
+ timerData.getTimerId(),
+ timerData.getTimerFamilyId(),
+ timerData.getDomain(),
+ timerData.getNamespace());
+ }
+
+ static byte[] timerStoreKey(
+ byte[] encodedKey,
+ String timerId,
+ String timerFamilyId,
+ TimeDomain domain,
+ StateNamespace namespace) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ writeSegment(out, encodedKey);
Review Comment:
Thanks, kept it exactly for that reason. The scan reads the encoded key back out of the key, so the prefixes have to stay here. I wrote that down in StoreKeys so it doesn't get "optimized" away later.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "je-ik (via GitHub)" <gi...@apache.org>.
je-ik commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3663870390
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/WindowedGroupByKeyProcessor.java:
##########
@@ -0,0 +1,323 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.core.NullSideInputReader;
+import org.apache.beam.runners.core.ReduceFnRunner;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.SystemReduceFn;
+import org.apache.beam.runners.core.TimerInternals.TimerData;
+import org.apache.beam.runners.core.triggers.ExecutableTriggerStateMachine;
+import org.apache.beam.runners.core.triggers.TriggerStateMachines;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.construction.TriggerTranslation;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.WindowedValue;
+import org.apache.beam.sdk.values.WindowingStrategy;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.io.BaseEncoding;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes a windowed {@code GroupByKey} by driving Beam's {@link ReduceFnRunner} — the same
+ * windowing + triggering state machine the Flink and Spark portable runners use — with Kafka
+ * Streams state and timers behind it.
+ *
+ * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key
+ * is co-located here. For each data record this builds a {@link ReduceFnRunner} for that key over a
+ * {@link KafkaStreamsStateInternals} and {@link KafkaStreamsTimerInternals} (both backed by
+ * persistent stores) and feeds the element in; the runner assigns it to windows, updates the
+ * trigger state, and sets any timers it needs. When the aggregated input watermark advances, every
+ * event-time timer whose fire time has passed is replayed through {@code onTimers}, which is what
+ * makes windows emit their panes. The runner is stateless between records — all durable state lives
+ * in the stores — so a fresh one per record is correct, mirroring {@code
+ * GroupAlsoByWindowViaWindowSetNewDoFn}.
+ *
+ * <p>This first version supports the default trigger and non-merging windows well; richer triggers,
+ * processing-time timers and session (merging) windows build on the same machinery in a follow-up.
+ */
+class WindowedGroupByKeyProcessor<K, V, W extends BoundedWindow>
+ implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WindowedGroupByKeyProcessor.class);
+
+ private final String stateStoreName;
+ private final String holdsIndexStoreName;
+ private final String timerStoreName;
+ private final String timerIndexStoreName;
+ private final String transformId;
+ private final Coder<K> keyCoder;
+ private final WindowingStrategy<?, W> windowingStrategy;
+ private final Coder<? extends BoundedWindow> windowCoder;
+ private final RunnerApi.Trigger triggerProto;
+ private final SystemReduceFn<K, V, Iterable<V>, Iterable<V>, W> reduceFn;
+ private final PipelineOptions options;
+
+ private final WatermarkAggregator watermarkAggregator;
+ private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+ private Instant inputWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+
+ private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context;
+ private @Nullable KeyValueStore<byte[], byte[]> stateStore;
+ private @Nullable KeyValueStore<byte[], byte[]> holdsIndexStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerIndexStore;
+
+ WindowedGroupByKeyProcessor(
+ String stateStoreName,
+ String holdsIndexStoreName,
+ String timerStoreName,
+ String timerIndexStoreName,
+ String transformId,
+ Set<String> upstreamTransformIds,
+ Coder<K> keyCoder,
+ Coder<V> valueCoder,
+ WindowingStrategy<?, W> windowingStrategy,
+ PipelineOptions options) {
+ this.stateStoreName = stateStoreName;
+ this.holdsIndexStoreName = holdsIndexStoreName;
+ this.timerStoreName = timerStoreName;
+ this.timerIndexStoreName = timerIndexStoreName;
+ this.transformId = transformId;
+ this.keyCoder = keyCoder;
+ this.windowingStrategy = windowingStrategy;
+ this.windowCoder = windowingStrategy.getWindowFn().windowCoder();
+ this.triggerProto = TriggerTranslation.toProto(windowingStrategy.getTrigger());
+ this.reduceFn = SystemReduceFn.buffering(valueCoder);
+ this.options = options;
+ this.watermarkAggregator = new WatermarkAggregator(upstreamTransformIds);
+ }
+
+ @Override
+ public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) {
+ this.context = context;
+ this.stateStore = context.getStateStore(stateStoreName);
+ this.holdsIndexStore = context.getStateStore(holdsIndexStoreName);
+ this.timerStore = context.getStateStore(timerStoreName);
+ this.timerIndexStore = context.getStateStore(timerIndexStoreName);
+ }
+
+ @Override
+ public void process(Record<byte[], KStreamsPayload<?>> record) {
+ KStreamsPayload<?> payload = record.value();
+ if (payload == null) {
+ LOG.warn(
+ "GroupByKey {} dropping record with null payload (external write or tombstone)",
+ transformId);
+ return;
+ }
+ if (payload.isData()) {
+ processData(record, payload);
+ return;
+ }
+ watermarkAggregator.observe(payload.asWatermark());
+ Instant advanced = watermarkAggregator.advance();
+ if (advanced.isAfter(inputWatermark)) {
+ inputWatermark = advanced;
+ fireDueEventTimeTimers(record, advanced);
+ }
+ // Firing may have emitted panes and released their holds, so the output watermark is computed
+ // after it.
+ Instant output = outputWatermark();
+ if (output.isAfter(lastForwardedWatermark)) {
+ lastForwardedWatermark = output;
+ forwardWatermark(record, output.getMillis());
+ }
+ }
+
+ /**
+ * The watermark to publish downstream: the input watermark, held back by the earliest watermark
+ * hold any pending pane has taken.
+ *
+ * <p>{@link ReduceFnRunner} takes a hold for buffered elements that have not been emitted yet, at
+ * the timestamp their pane will carry. Forwarding the raw input watermark would tell downstream
+ * that nothing earlier is coming while those panes are still buffered, and the elements would
+ * then arrive late against the watermark we had already published.
+ */
+ private Instant outputWatermark() {
+ Instant minHold =
+ KafkaStreamsStateInternals.minWatermarkHold(checkInitialized(holdsIndexStore));
+ return minHold == null || inputWatermark.isBefore(minHold) ? inputWatermark : minHold;
+ }
+
+ private void processData(Record<byte[], KStreamsPayload<?>> record, KStreamsPayload<?> payload) {
+ byte[] encodedKey = record.key();
+ if (encodedKey == null) {
+ throw new IllegalStateException("GroupByKey data record is missing its key");
+ }
+ @SuppressWarnings("unchecked")
+ WindowedValue<KV<K, V>> element = (WindowedValue<KV<K, V>>) payload.getData();
+ K key = decodeKey(encodedKey);
+ WindowedValue<V> valueElement = element.withValue(element.getValue().getValue());
+ runReduceFn(
+ record, encodedKey, key, Collections.singletonList(valueElement), Collections.emptyList());
+ }
+
+ /**
+ * Fires every event-time timer whose fire time is at or before the new input watermark.
+ *
+ * <p>The timers to fire are found by range-scanning the fire-time-ordered index over exactly the
+ * window {@code (-inf, watermark]}, so the cost is proportional to the number of timers that are
+ * actually due rather than to the number of keys that hold a timer.
+ */
+ private void fireDueEventTimeTimers(
+ Record<byte[], KStreamsPayload<?>> record, Instant watermark) {
+ KeyValueStore<byte[], byte[]> identityStore = checkInitialized(timerStore);
+ KeyValueStore<byte[], byte[]> indexStore = checkInitialized(timerIndexStore);
+ // Group the due timers by the Beam key they belong to; a key's timers fire together in one
+ // ReduceFnRunner turn.
+ Map<String, DueTimers> dueByKey = new LinkedHashMap<>();
+ List<byte[]> firedIndexKeys = new ArrayList<>();
+ try (KeyValueIterator<byte[], byte[]> it =
+ indexStore.range(
+ KafkaStreamsTimerInternals.dueEventTimeRangeStart(),
+ KafkaStreamsTimerInternals.dueEventTimeRangeEnd(watermark.getMillis()))) {
+ while (it.hasNext()) {
+ org.apache.kafka.streams.KeyValue<byte[], byte[]> entry = it.next();
+ TimerData timer = KafkaStreamsTimerInternals.decodeTimer(windowCoder, entry.value);
+ byte[] encodedKey =
+ KafkaStreamsTimerInternals.encodedKeyOf(
+ KafkaStreamsTimerInternals.identityKeyOf(entry.key));
+ dueByKey
+ .computeIfAbsent(
+ BaseEncoding.base16().encode(encodedKey), k -> new DueTimers(encodedKey))
+ .timers
+ .add(timer);
+ firedIndexKeys.add(entry.key);
+ }
+ }
+ // Clear the fired timers from both stores before replaying them, since onTimers may
+ // legitimately
+ // set new ones — including at the same identity.
+ for (byte[] indexKey : firedIndexKeys) {
+ indexStore.delete(indexKey);
+ identityStore.delete(KafkaStreamsTimerInternals.identityKeyOf(indexKey));
+ }
+ for (DueTimers due : dueByKey.values()) {
Review Comment:
Here we will hit an issue - as you mentioned timers can set new timers. Beam model must ensure that timers are fired _in order_ (otherwise consistency can break), so if we extract timers 1 and 2 for firing and firing timer 1 sets new timer 3 for time between 1 and 2, we need to fire in order 1, 3, 2, although timer 3 was not existing before timer 1 was fired.
There should be a validates runner test for this, so we can postpone the solution for now.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "je-ik (via GitHub)" <gi...@apache.org>.
je-ik commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3663870390
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/WindowedGroupByKeyProcessor.java:
##########
@@ -0,0 +1,323 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.core.NullSideInputReader;
+import org.apache.beam.runners.core.ReduceFnRunner;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.SystemReduceFn;
+import org.apache.beam.runners.core.TimerInternals.TimerData;
+import org.apache.beam.runners.core.triggers.ExecutableTriggerStateMachine;
+import org.apache.beam.runners.core.triggers.TriggerStateMachines;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.construction.TriggerTranslation;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.WindowedValue;
+import org.apache.beam.sdk.values.WindowingStrategy;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.io.BaseEncoding;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes a windowed {@code GroupByKey} by driving Beam's {@link ReduceFnRunner} — the same
+ * windowing + triggering state machine the Flink and Spark portable runners use — with Kafka
+ * Streams state and timers behind it.
+ *
+ * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key
+ * is co-located here. For each data record this builds a {@link ReduceFnRunner} for that key over a
+ * {@link KafkaStreamsStateInternals} and {@link KafkaStreamsTimerInternals} (both backed by
+ * persistent stores) and feeds the element in; the runner assigns it to windows, updates the
+ * trigger state, and sets any timers it needs. When the aggregated input watermark advances, every
+ * event-time timer whose fire time has passed is replayed through {@code onTimers}, which is what
+ * makes windows emit their panes. The runner is stateless between records — all durable state lives
+ * in the stores — so a fresh one per record is correct, mirroring {@code
+ * GroupAlsoByWindowViaWindowSetNewDoFn}.
+ *
+ * <p>This first version supports the default trigger and non-merging windows well; richer triggers,
+ * processing-time timers and session (merging) windows build on the same machinery in a follow-up.
+ */
+class WindowedGroupByKeyProcessor<K, V, W extends BoundedWindow>
+ implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WindowedGroupByKeyProcessor.class);
+
+ private final String stateStoreName;
+ private final String holdsIndexStoreName;
+ private final String timerStoreName;
+ private final String timerIndexStoreName;
+ private final String transformId;
+ private final Coder<K> keyCoder;
+ private final WindowingStrategy<?, W> windowingStrategy;
+ private final Coder<? extends BoundedWindow> windowCoder;
+ private final RunnerApi.Trigger triggerProto;
+ private final SystemReduceFn<K, V, Iterable<V>, Iterable<V>, W> reduceFn;
+ private final PipelineOptions options;
+
+ private final WatermarkAggregator watermarkAggregator;
+ private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+ private Instant inputWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+
+ private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context;
+ private @Nullable KeyValueStore<byte[], byte[]> stateStore;
+ private @Nullable KeyValueStore<byte[], byte[]> holdsIndexStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerIndexStore;
+
+ WindowedGroupByKeyProcessor(
+ String stateStoreName,
+ String holdsIndexStoreName,
+ String timerStoreName,
+ String timerIndexStoreName,
+ String transformId,
+ Set<String> upstreamTransformIds,
+ Coder<K> keyCoder,
+ Coder<V> valueCoder,
+ WindowingStrategy<?, W> windowingStrategy,
+ PipelineOptions options) {
+ this.stateStoreName = stateStoreName;
+ this.holdsIndexStoreName = holdsIndexStoreName;
+ this.timerStoreName = timerStoreName;
+ this.timerIndexStoreName = timerIndexStoreName;
+ this.transformId = transformId;
+ this.keyCoder = keyCoder;
+ this.windowingStrategy = windowingStrategy;
+ this.windowCoder = windowingStrategy.getWindowFn().windowCoder();
+ this.triggerProto = TriggerTranslation.toProto(windowingStrategy.getTrigger());
+ this.reduceFn = SystemReduceFn.buffering(valueCoder);
+ this.options = options;
+ this.watermarkAggregator = new WatermarkAggregator(upstreamTransformIds);
+ }
+
+ @Override
+ public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) {
+ this.context = context;
+ this.stateStore = context.getStateStore(stateStoreName);
+ this.holdsIndexStore = context.getStateStore(holdsIndexStoreName);
+ this.timerStore = context.getStateStore(timerStoreName);
+ this.timerIndexStore = context.getStateStore(timerIndexStoreName);
+ }
+
+ @Override
+ public void process(Record<byte[], KStreamsPayload<?>> record) {
+ KStreamsPayload<?> payload = record.value();
+ if (payload == null) {
+ LOG.warn(
+ "GroupByKey {} dropping record with null payload (external write or tombstone)",
+ transformId);
+ return;
+ }
+ if (payload.isData()) {
+ processData(record, payload);
+ return;
+ }
+ watermarkAggregator.observe(payload.asWatermark());
+ Instant advanced = watermarkAggregator.advance();
+ if (advanced.isAfter(inputWatermark)) {
+ inputWatermark = advanced;
+ fireDueEventTimeTimers(record, advanced);
+ }
+ // Firing may have emitted panes and released their holds, so the output watermark is computed
+ // after it.
+ Instant output = outputWatermark();
+ if (output.isAfter(lastForwardedWatermark)) {
+ lastForwardedWatermark = output;
+ forwardWatermark(record, output.getMillis());
+ }
+ }
+
+ /**
+ * The watermark to publish downstream: the input watermark, held back by the earliest watermark
+ * hold any pending pane has taken.
+ *
+ * <p>{@link ReduceFnRunner} takes a hold for buffered elements that have not been emitted yet, at
+ * the timestamp their pane will carry. Forwarding the raw input watermark would tell downstream
+ * that nothing earlier is coming while those panes are still buffered, and the elements would
+ * then arrive late against the watermark we had already published.
+ */
+ private Instant outputWatermark() {
+ Instant minHold =
+ KafkaStreamsStateInternals.minWatermarkHold(checkInitialized(holdsIndexStore));
+ return minHold == null || inputWatermark.isBefore(minHold) ? inputWatermark : minHold;
+ }
+
+ private void processData(Record<byte[], KStreamsPayload<?>> record, KStreamsPayload<?> payload) {
+ byte[] encodedKey = record.key();
+ if (encodedKey == null) {
+ throw new IllegalStateException("GroupByKey data record is missing its key");
+ }
+ @SuppressWarnings("unchecked")
+ WindowedValue<KV<K, V>> element = (WindowedValue<KV<K, V>>) payload.getData();
+ K key = decodeKey(encodedKey);
+ WindowedValue<V> valueElement = element.withValue(element.getValue().getValue());
+ runReduceFn(
+ record, encodedKey, key, Collections.singletonList(valueElement), Collections.emptyList());
+ }
+
+ /**
+ * Fires every event-time timer whose fire time is at or before the new input watermark.
+ *
+ * <p>The timers to fire are found by range-scanning the fire-time-ordered index over exactly the
+ * window {@code (-inf, watermark]}, so the cost is proportional to the number of timers that are
+ * actually due rather than to the number of keys that hold a timer.
+ */
+ private void fireDueEventTimeTimers(
+ Record<byte[], KStreamsPayload<?>> record, Instant watermark) {
+ KeyValueStore<byte[], byte[]> identityStore = checkInitialized(timerStore);
+ KeyValueStore<byte[], byte[]> indexStore = checkInitialized(timerIndexStore);
+ // Group the due timers by the Beam key they belong to; a key's timers fire together in one
+ // ReduceFnRunner turn.
+ Map<String, DueTimers> dueByKey = new LinkedHashMap<>();
+ List<byte[]> firedIndexKeys = new ArrayList<>();
+ try (KeyValueIterator<byte[], byte[]> it =
+ indexStore.range(
+ KafkaStreamsTimerInternals.dueEventTimeRangeStart(),
+ KafkaStreamsTimerInternals.dueEventTimeRangeEnd(watermark.getMillis()))) {
+ while (it.hasNext()) {
+ org.apache.kafka.streams.KeyValue<byte[], byte[]> entry = it.next();
+ TimerData timer = KafkaStreamsTimerInternals.decodeTimer(windowCoder, entry.value);
+ byte[] encodedKey =
+ KafkaStreamsTimerInternals.encodedKeyOf(
+ KafkaStreamsTimerInternals.identityKeyOf(entry.key));
+ dueByKey
+ .computeIfAbsent(
+ BaseEncoding.base16().encode(encodedKey), k -> new DueTimers(encodedKey))
+ .timers
+ .add(timer);
+ firedIndexKeys.add(entry.key);
+ }
+ }
+ // Clear the fired timers from both stores before replaying them, since onTimers may
+ // legitimately
+ // set new ones — including at the same identity.
+ for (byte[] indexKey : firedIndexKeys) {
+ indexStore.delete(indexKey);
+ identityStore.delete(KafkaStreamsTimerInternals.identityKeyOf(indexKey));
+ }
+ for (DueTimers due : dueByKey.values()) {
Review Comment:
Here we will hit an issue - as you mentioned timers can set new timers. Beam model must ensure that timers are fired _in order_ (otherwise consistency can break), so if we extract timers 1 and 2 for firing and firing timer 1 sets new timer 3 for time between 1 and 2, we need to fire in order 1, 3, 2, although timer 3 was not existing before timer 1 was fired.
There should be a validates runner for this, so we can postpone the solution for now.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #39494:
URL: https://github.com/apache/beam/pull/39494#issuecomment-5084122729
> [!CAUTION]
> The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "je-ik (via GitHub)" <gi...@apache.org>.
je-ik commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3655454892
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/WindowedGroupByKeyProcessor.java:
##########
@@ -0,0 +1,284 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.core.NullSideInputReader;
+import org.apache.beam.runners.core.ReduceFnRunner;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.SystemReduceFn;
+import org.apache.beam.runners.core.TimerInternals.TimerData;
+import org.apache.beam.runners.core.triggers.ExecutableTriggerStateMachine;
+import org.apache.beam.runners.core.triggers.TriggerStateMachines;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.construction.TriggerTranslation;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.WindowedValue;
+import org.apache.beam.sdk.values.WindowingStrategy;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.io.BaseEncoding;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes a windowed {@code GroupByKey} by driving Beam's {@link ReduceFnRunner} — the same
+ * windowing + triggering state machine the Flink and Spark portable runners use — with Kafka
+ * Streams state and timers behind it.
+ *
+ * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key
+ * is co-located here. For each data record this builds a {@link ReduceFnRunner} for that key over a
+ * {@link KafkaStreamsStateInternals} and {@link KafkaStreamsTimerInternals} (both backed by
+ * persistent stores) and feeds the element in; the runner assigns it to windows, updates the
+ * trigger state, and sets any timers it needs. When the aggregated input watermark advances, every
+ * event-time timer whose fire time has passed is replayed through {@code onTimers}, which is what
+ * makes windows emit their panes. The runner is stateless between records — all durable state lives
+ * in the stores — so a fresh one per record is correct, mirroring {@code
+ * GroupAlsoByWindowViaWindowSetNewDoFn}.
+ *
+ * <p>This first version supports the default trigger and non-merging windows well; richer triggers,
+ * processing-time timers and session (merging) windows build on the same machinery in a follow-up.
+ */
+class WindowedGroupByKeyProcessor<K, V, W extends BoundedWindow>
+ implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WindowedGroupByKeyProcessor.class);
+
+ private final String stateStoreName;
+ private final String timerStoreName;
+ private final String transformId;
+ private final Coder<K> keyCoder;
+ private final WindowingStrategy<?, W> windowingStrategy;
+ private final Coder<? extends BoundedWindow> windowCoder;
+ private final RunnerApi.Trigger triggerProto;
+ private final SystemReduceFn<K, V, Iterable<V>, Iterable<V>, W> reduceFn;
+ private final PipelineOptions options;
+
+ private final WatermarkAggregator watermarkAggregator;
+ private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+ private Instant inputWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+
+ private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context;
+ private @Nullable KeyValueStore<byte[], byte[]> stateStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerStore;
+
+ WindowedGroupByKeyProcessor(
+ String stateStoreName,
+ String timerStoreName,
+ String transformId,
+ Set<String> upstreamTransformIds,
+ Coder<K> keyCoder,
+ Coder<V> valueCoder,
+ WindowingStrategy<?, W> windowingStrategy,
+ PipelineOptions options) {
+ this.stateStoreName = stateStoreName;
+ this.timerStoreName = timerStoreName;
+ this.transformId = transformId;
+ this.keyCoder = keyCoder;
+ this.windowingStrategy = windowingStrategy;
+ this.windowCoder = windowingStrategy.getWindowFn().windowCoder();
+ this.triggerProto = TriggerTranslation.toProto(windowingStrategy.getTrigger());
+ this.reduceFn = SystemReduceFn.buffering(valueCoder);
+ this.options = options;
+ this.watermarkAggregator = new WatermarkAggregator(upstreamTransformIds);
+ }
+
+ @Override
+ public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) {
+ this.context = context;
+ this.stateStore = context.getStateStore(stateStoreName);
+ this.timerStore = context.getStateStore(timerStoreName);
+ }
+
+ @Override
+ public void process(Record<byte[], KStreamsPayload<?>> record) {
+ KStreamsPayload<?> payload = record.value();
+ if (payload == null) {
+ LOG.warn(
+ "GroupByKey {} dropping record with null payload (external write or tombstone)",
+ transformId);
+ return;
+ }
+ if (payload.isData()) {
+ processData(record, payload);
+ return;
+ }
+ watermarkAggregator.observe(payload.asWatermark());
+ Instant advanced = watermarkAggregator.advance();
+ if (advanced.isAfter(lastForwardedWatermark)) {
+ inputWatermark = advanced;
+ fireDueEventTimeTimers(record, advanced);
+ lastForwardedWatermark = advanced;
+ forwardWatermark(record, advanced.getMillis());
+ }
+ }
+
+ private void processData(Record<byte[], KStreamsPayload<?>> record, KStreamsPayload<?> payload) {
+ byte[] encodedKey = record.key();
+ if (encodedKey == null) {
+ throw new IllegalStateException("GroupByKey data record is missing its key");
+ }
+ @SuppressWarnings("unchecked")
+ WindowedValue<KV<K, V>> element = (WindowedValue<KV<K, V>>) payload.getData();
+ K key = decodeKey(encodedKey);
+ WindowedValue<V> valueElement = element.withValue(element.getValue().getValue());
+ runReduceFn(
+ record, encodedKey, key, Collections.singletonList(valueElement), Collections.emptyList());
+ }
+
+ /** Fires every event-time timer whose fire time is at or before the new input watermark. */
+ private void fireDueEventTimeTimers(
+ Record<byte[], KStreamsPayload<?>> record, Instant watermark) {
+ KeyValueStore<byte[], byte[]> timers = checkInitialized(timerStore);
+ // Group due timers by the Beam key they belong to; a key's timers fire together in one
+ // ReduceFnRunner turn. Whole-store scan per advance is O(timers) — see the class doc.
+ Map<String, DueTimers> dueByKey = new LinkedHashMap<>();
+ List<byte[]> firedStoreKeys = new ArrayList<>();
+ try (KeyValueIterator<byte[], byte[]> it = timers.all()) {
+ while (it.hasNext()) {
+ org.apache.kafka.streams.KeyValue<byte[], byte[]> entry = it.next();
+ TimerData timer = decodeTimer(entry.value);
+ if (timer.getDomain() != TimeDomain.EVENT_TIME || timer.getTimestamp().isAfter(watermark)) {
+ continue;
+ }
+ byte[] encodedKey = KafkaStreamsTimerInternals.encodedKeyOf(entry.key);
+ dueByKey
+ .computeIfAbsent(
+ BaseEncoding.base16().encode(encodedKey), k -> new DueTimers(encodedKey))
+ .timers
+ .add(timer);
+ firedStoreKeys.add(entry.key);
+ }
+ }
+ // Remove fired timers before replaying them; onTimers may legitimately set new ones.
+ for (byte[] storeKey : firedStoreKeys) {
+ timers.delete(storeKey);
+ }
+ for (DueTimers due : dueByKey.values()) {
+ runReduceFn(
+ record, due.encodedKey, decodeKey(due.encodedKey), Collections.emptyList(), due.timers);
+ }
+ }
+
+ private void runReduceFn(
+ Record<byte[], KStreamsPayload<?>> record,
+ byte[] encodedKey,
+ @NonNull K key,
+ List<WindowedValue<V>> elements,
+ List<TimerData> timers) {
+ StateInternals stateInternals =
+ new KafkaStreamsStateInternals<>(key, encodedKey, checkInitialized(stateStore));
+ KafkaStreamsTimerInternals timerInternals =
+ new KafkaStreamsTimerInternals(
+ encodedKey, checkInitialized(timerStore), windowCoder, inputWatermark, Instant.now());
+ ReduceFnRunner<K, V, Iterable<V>, W> runner =
+ new ReduceFnRunner<>(
+ key,
+ windowingStrategy,
+ ExecutableTriggerStateMachine.create(
+ TriggerStateMachines.stateMachineForTrigger(triggerProto)),
+ stateInternals,
+ timerInternals,
+ output -> forwardData(record, encodedKey, output),
+ NullSideInputReader.empty(),
+ reduceFn,
+ options);
+ try {
+ runner.processElements(elements);
+ runner.onTimers(timers);
+ runner.persist();
+ } catch (Exception e) {
+ throw new RuntimeException("GroupByKey " + transformId + " failed to run windowing", e);
+ }
+ }
+
+ private void forwardData(
+ Record<byte[], KStreamsPayload<?>> trigger,
+ byte[] encodedKey,
+ WindowedValue<KV<K, Iterable<V>>> output) {
+ ProcessorContext<byte[], KStreamsPayload<?>> ctx = checkInitialized(context);
+ ctx.forward(
+ new Record<byte[], KStreamsPayload<?>>(
+ encodedKey, KStreamsPayload.data(output), trigger.timestamp()));
+ }
+
+ private void forwardWatermark(Record<byte[], KStreamsPayload<?>> trigger, long watermarkMillis) {
Review Comment:
It seems we must apply watermark holds here, if I'm not missing something.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #39494:
URL: https://github.com/apache/beam/pull/39494#issuecomment-5084224880
Assigning reviewers:
R: @kennknowles added as fallback since no labels match configuration
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).
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "je-ik (via GitHub)" <gi...@apache.org>.
je-ik merged PR #39494:
URL: https://github.com/apache/beam/pull/39494
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "junaiddshaukat (via GitHub)" <gi...@apache.org>.
junaiddshaukat commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3656505954
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/WindowedGroupByKeyProcessor.java:
##########
@@ -0,0 +1,284 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.core.NullSideInputReader;
+import org.apache.beam.runners.core.ReduceFnRunner;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.SystemReduceFn;
+import org.apache.beam.runners.core.TimerInternals.TimerData;
+import org.apache.beam.runners.core.triggers.ExecutableTriggerStateMachine;
+import org.apache.beam.runners.core.triggers.TriggerStateMachines;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.construction.TriggerTranslation;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.WindowedValue;
+import org.apache.beam.sdk.values.WindowingStrategy;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.io.BaseEncoding;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes a windowed {@code GroupByKey} by driving Beam's {@link ReduceFnRunner} — the same
+ * windowing + triggering state machine the Flink and Spark portable runners use — with Kafka
+ * Streams state and timers behind it.
+ *
+ * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key
+ * is co-located here. For each data record this builds a {@link ReduceFnRunner} for that key over a
+ * {@link KafkaStreamsStateInternals} and {@link KafkaStreamsTimerInternals} (both backed by
+ * persistent stores) and feeds the element in; the runner assigns it to windows, updates the
+ * trigger state, and sets any timers it needs. When the aggregated input watermark advances, every
+ * event-time timer whose fire time has passed is replayed through {@code onTimers}, which is what
+ * makes windows emit their panes. The runner is stateless between records — all durable state lives
+ * in the stores — so a fresh one per record is correct, mirroring {@code
+ * GroupAlsoByWindowViaWindowSetNewDoFn}.
+ *
+ * <p>This first version supports the default trigger and non-merging windows well; richer triggers,
+ * processing-time timers and session (merging) windows build on the same machinery in a follow-up.
+ */
+class WindowedGroupByKeyProcessor<K, V, W extends BoundedWindow>
+ implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WindowedGroupByKeyProcessor.class);
+
+ private final String stateStoreName;
+ private final String timerStoreName;
+ private final String transformId;
+ private final Coder<K> keyCoder;
+ private final WindowingStrategy<?, W> windowingStrategy;
+ private final Coder<? extends BoundedWindow> windowCoder;
+ private final RunnerApi.Trigger triggerProto;
+ private final SystemReduceFn<K, V, Iterable<V>, Iterable<V>, W> reduceFn;
+ private final PipelineOptions options;
+
+ private final WatermarkAggregator watermarkAggregator;
+ private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+ private Instant inputWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+
+ private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context;
+ private @Nullable KeyValueStore<byte[], byte[]> stateStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerStore;
+
+ WindowedGroupByKeyProcessor(
+ String stateStoreName,
+ String timerStoreName,
+ String transformId,
+ Set<String> upstreamTransformIds,
+ Coder<K> keyCoder,
+ Coder<V> valueCoder,
+ WindowingStrategy<?, W> windowingStrategy,
+ PipelineOptions options) {
+ this.stateStoreName = stateStoreName;
+ this.timerStoreName = timerStoreName;
+ this.transformId = transformId;
+ this.keyCoder = keyCoder;
+ this.windowingStrategy = windowingStrategy;
+ this.windowCoder = windowingStrategy.getWindowFn().windowCoder();
+ this.triggerProto = TriggerTranslation.toProto(windowingStrategy.getTrigger());
+ this.reduceFn = SystemReduceFn.buffering(valueCoder);
+ this.options = options;
+ this.watermarkAggregator = new WatermarkAggregator(upstreamTransformIds);
+ }
+
+ @Override
+ public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) {
+ this.context = context;
+ this.stateStore = context.getStateStore(stateStoreName);
+ this.timerStore = context.getStateStore(timerStoreName);
+ }
+
+ @Override
+ public void process(Record<byte[], KStreamsPayload<?>> record) {
+ KStreamsPayload<?> payload = record.value();
+ if (payload == null) {
+ LOG.warn(
+ "GroupByKey {} dropping record with null payload (external write or tombstone)",
+ transformId);
+ return;
+ }
+ if (payload.isData()) {
+ processData(record, payload);
+ return;
+ }
+ watermarkAggregator.observe(payload.asWatermark());
+ Instant advanced = watermarkAggregator.advance();
+ if (advanced.isAfter(lastForwardedWatermark)) {
+ inputWatermark = advanced;
+ fireDueEventTimeTimers(record, advanced);
+ lastForwardedWatermark = advanced;
+ forwardWatermark(record, advanced.getMillis());
+ }
+ }
+
+ private void processData(Record<byte[], KStreamsPayload<?>> record, KStreamsPayload<?> payload) {
+ byte[] encodedKey = record.key();
+ if (encodedKey == null) {
+ throw new IllegalStateException("GroupByKey data record is missing its key");
+ }
+ @SuppressWarnings("unchecked")
+ WindowedValue<KV<K, V>> element = (WindowedValue<KV<K, V>>) payload.getData();
+ K key = decodeKey(encodedKey);
+ WindowedValue<V> valueElement = element.withValue(element.getValue().getValue());
+ runReduceFn(
+ record, encodedKey, key, Collections.singletonList(valueElement), Collections.emptyList());
+ }
+
+ /** Fires every event-time timer whose fire time is at or before the new input watermark. */
+ private void fireDueEventTimeTimers(
+ Record<byte[], KStreamsPayload<?>> record, Instant watermark) {
+ KeyValueStore<byte[], byte[]> timers = checkInitialized(timerStore);
+ // Group due timers by the Beam key they belong to; a key's timers fire together in one
+ // ReduceFnRunner turn. Whole-store scan per advance is O(timers) — see the class doc.
+ Map<String, DueTimers> dueByKey = new LinkedHashMap<>();
+ List<byte[]> firedStoreKeys = new ArrayList<>();
+ try (KeyValueIterator<byte[], byte[]> it = timers.all()) {
+ while (it.hasNext()) {
+ org.apache.kafka.streams.KeyValue<byte[], byte[]> entry = it.next();
+ TimerData timer = decodeTimer(entry.value);
+ if (timer.getDomain() != TimeDomain.EVENT_TIME || timer.getTimestamp().isAfter(watermark)) {
+ continue;
+ }
+ byte[] encodedKey = KafkaStreamsTimerInternals.encodedKeyOf(entry.key);
+ dueByKey
+ .computeIfAbsent(
+ BaseEncoding.base16().encode(encodedKey), k -> new DueTimers(encodedKey))
+ .timers
+ .add(timer);
+ firedStoreKeys.add(entry.key);
+ }
+ }
+ // Remove fired timers before replaying them; onTimers may legitimately set new ones.
+ for (byte[] storeKey : firedStoreKeys) {
+ timers.delete(storeKey);
+ }
+ for (DueTimers due : dueByKey.values()) {
+ runReduceFn(
+ record, due.encodedKey, decodeKey(due.encodedKey), Collections.emptyList(), due.timers);
+ }
+ }
+
+ private void runReduceFn(
+ Record<byte[], KStreamsPayload<?>> record,
+ byte[] encodedKey,
+ @NonNull K key,
+ List<WindowedValue<V>> elements,
+ List<TimerData> timers) {
+ StateInternals stateInternals =
+ new KafkaStreamsStateInternals<>(key, encodedKey, checkInitialized(stateStore));
+ KafkaStreamsTimerInternals timerInternals =
+ new KafkaStreamsTimerInternals(
+ encodedKey, checkInitialized(timerStore), windowCoder, inputWatermark, Instant.now());
+ ReduceFnRunner<K, V, Iterable<V>, W> runner =
+ new ReduceFnRunner<>(
+ key,
+ windowingStrategy,
+ ExecutableTriggerStateMachine.create(
+ TriggerStateMachines.stateMachineForTrigger(triggerProto)),
+ stateInternals,
+ timerInternals,
+ output -> forwardData(record, encodedKey, output),
+ NullSideInputReader.empty(),
+ reduceFn,
+ options);
+ try {
+ runner.processElements(elements);
+ runner.onTimers(timers);
+ runner.persist();
+ } catch (Exception e) {
+ throw new RuntimeException("GroupByKey " + transformId + " failed to run windowing", e);
+ }
+ }
+
+ private void forwardData(
+ Record<byte[], KStreamsPayload<?>> trigger,
+ byte[] encodedKey,
+ WindowedValue<KV<K, Iterable<V>>> output) {
+ ProcessorContext<byte[], KStreamsPayload<?>> ctx = checkInitialized(context);
+ ctx.forward(
+ new Record<byte[], KStreamsPayload<?>>(
+ encodedKey, KStreamsPayload.data(output), trigger.timestamp()));
+ }
+
+ private void forwardWatermark(Record<byte[], KStreamsPayload<?>> trigger, long watermarkMillis) {
Review Comment:
You're right, this was a real bug. ReduceFnRunner takes a hold for a buffered pane that hasn't been emitted, and we were publishing the raw input watermark, so downstream was told nothing earlier was coming while panes were still buffered those elements would then arrive late against a watermark we'd already published.
WatermarkHoldState now mirrors each hold into a hold-time-ordered index, and the GroupByKey publishes min(inputWatermark, minimum hold). Reading the minimum is the first entry of that index rather than a scan, same idea as the timer index. Holds are read after firing, since firing emits the panes and releases them.
--
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] [GSoC 2026] Kafka Streams runner: windowed GroupByKey via ReduceFnRunner [beam]
Posted by "je-ik (via GitHub)" <gi...@apache.org>.
je-ik commented on code in PR #39494:
URL: https://github.com/apache/beam/pull/39494#discussion_r3655276453
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/KafkaStreamsStateInternals.java:
##########
@@ -0,0 +1,393 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.StateNamespace;
+import org.apache.beam.runners.core.StateTag;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.coders.InstantCoder;
+import org.apache.beam.sdk.coders.ListCoder;
+import org.apache.beam.sdk.state.BagState;
+import org.apache.beam.sdk.state.CombiningState;
+import org.apache.beam.sdk.state.MapState;
+import org.apache.beam.sdk.state.MultimapState;
+import org.apache.beam.sdk.state.OrderedListState;
+import org.apache.beam.sdk.state.ReadableState;
+import org.apache.beam.sdk.state.SetState;
+import org.apache.beam.sdk.state.State;
+import org.apache.beam.sdk.state.StateBinder;
+import org.apache.beam.sdk.state.StateContext;
+import org.apache.beam.sdk.state.StateSpec;
+import org.apache.beam.sdk.state.ValueState;
+import org.apache.beam.sdk.state.WatermarkHoldState;
+import org.apache.beam.sdk.transforms.Combine.CombineFn;
+import org.apache.beam.sdk.transforms.CombineWithContext;
+import org.apache.beam.sdk.transforms.windowing.TimestampCombiner;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.CombineFnUtil;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * A {@link StateInternals} for one key, backed by a Kafka Streams {@link KeyValueStore}.
+ *
+ * <p>Beam addresses a state cell by {@code (key, StateNamespace, StateTag)}; a windowed pipeline
+ * puts each window's state in its own namespace. Every cell is stored as one entry in the shared
+ * per-transform store under a composite byte key {@code len(key)|key | len(ns)|ns | len(tag)|tag},
+ * so all cells for one Beam key share a prefix and a whole key's state can be range-scanned. The
+ * value is the cell's contents encoded with its Beam {@link Coder}. Writing straight to the store
+ * (rather than buffering and flushing) keeps this restart-safe for free: the store is changelogged
+ * and, under exactly-once, its writes commit atomically with the input offsets.
+ *
+ * <p>Modeled on the Spark runner's {@code SparkStateInternals}; the difference is that each cell
+ * reads and writes its own store entry instead of an in-memory table, so there is no separate
+ * persist step.
+ */
+class KafkaStreamsStateInternals<K> implements StateInternals {
+
+ private final @NonNull K key;
+ private final byte[] encodedKey;
+ private final KeyValueStore<byte[], byte[]> store;
+
+ KafkaStreamsStateInternals(
+ @NonNull K key, byte[] encodedKey, KeyValueStore<byte[], byte[]> store) {
+ this.key = key;
+ this.encodedKey = encodedKey;
+ this.store = store;
+ }
+
+ @Override
+ public Object getKey() {
+ return key;
+ }
+
+ @Override
+ public <T extends State> T state(
+ StateNamespace namespace, StateTag<T> address, StateContext<?> c) {
+ return address.getSpec().bind(address.getId(), new KafkaStreamsStateBinder(namespace, c));
+ }
+
+ /** The composite store key for one cell: {@code len|key len|namespace len|tagId}. */
+ private byte[] compositeKey(StateNamespace namespace, String id) {
Review Comment:
This method will be a hotspot (it is called for every state access), can we optimize it a little by avoiding length-prefixing and instead just copy bytes in memory, e.g. (pseudocode I did'nt check correctness, this is just an idea)
```java
byte[] namespaceBytes = namespae.stringKey().getBytes(UTF_8);
byte[] idBytes = id.getBytes(UTF_8);
int len = encodedKey.length + namespaceBytes.length + idBytes.length + 2 /* add a separator, e.g. / between parts to avoid any possible collision */;
byte[] res = new byte[len];
System.arraycopy(encodedKey -> res);
System.arraycopy(namespaceByes -> res + encodedKey.length + 1);
System.arraycopy(idBytes -> res + encodedKey.length + namespaceBytes.length + 2);
res[encodedKey.length] = "/";
res[encodedKey.length + namespaceBytes.length + 1] = "/';
```
This might be more efficient due to pre-allocating the whole array and then just memcpy data.
It might also be worth caching the encodedKey / namespace pair, because it will be likely called several times with identical values in sequence (e.g. use code can read state 1, state 2, timer 1, write state 2, write timer 1 - all will have same encodedKey + namespace)
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/WindowedGroupByKeyProcessor.java:
##########
@@ -0,0 +1,284 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.core.NullSideInputReader;
+import org.apache.beam.runners.core.ReduceFnRunner;
+import org.apache.beam.runners.core.StateInternals;
+import org.apache.beam.runners.core.SystemReduceFn;
+import org.apache.beam.runners.core.TimerInternals.TimerData;
+import org.apache.beam.runners.core.triggers.ExecutableTriggerStateMachine;
+import org.apache.beam.runners.core.triggers.TriggerStateMachines;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.options.PipelineOptions;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.beam.sdk.util.construction.TriggerTranslation;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.WindowedValue;
+import org.apache.beam.sdk.values.WindowingStrategy;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.io.BaseEncoding;
+import org.apache.kafka.streams.processor.api.Processor;
+import org.apache.kafka.streams.processor.api.ProcessorContext;
+import org.apache.kafka.streams.processor.api.Record;
+import org.apache.kafka.streams.state.KeyValueIterator;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes a windowed {@code GroupByKey} by driving Beam's {@link ReduceFnRunner} — the same
+ * windowing + triggering state machine the Flink and Spark portable runners use — with Kafka
+ * Streams state and timers behind it.
+ *
+ * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key
+ * is co-located here. For each data record this builds a {@link ReduceFnRunner} for that key over a
+ * {@link KafkaStreamsStateInternals} and {@link KafkaStreamsTimerInternals} (both backed by
+ * persistent stores) and feeds the element in; the runner assigns it to windows, updates the
+ * trigger state, and sets any timers it needs. When the aggregated input watermark advances, every
+ * event-time timer whose fire time has passed is replayed through {@code onTimers}, which is what
+ * makes windows emit their panes. The runner is stateless between records — all durable state lives
+ * in the stores — so a fresh one per record is correct, mirroring {@code
+ * GroupAlsoByWindowViaWindowSetNewDoFn}.
+ *
+ * <p>This first version supports the default trigger and non-merging windows well; richer triggers,
+ * processing-time timers and session (merging) windows build on the same machinery in a follow-up.
+ */
+class WindowedGroupByKeyProcessor<K, V, W extends BoundedWindow>
+ implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(WindowedGroupByKeyProcessor.class);
+
+ private final String stateStoreName;
+ private final String timerStoreName;
+ private final String transformId;
+ private final Coder<K> keyCoder;
+ private final WindowingStrategy<?, W> windowingStrategy;
+ private final Coder<? extends BoundedWindow> windowCoder;
+ private final RunnerApi.Trigger triggerProto;
+ private final SystemReduceFn<K, V, Iterable<V>, Iterable<V>, W> reduceFn;
+ private final PipelineOptions options;
+
+ private final WatermarkAggregator watermarkAggregator;
+ private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+ private Instant inputWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE;
+
+ private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context;
+ private @Nullable KeyValueStore<byte[], byte[]> stateStore;
+ private @Nullable KeyValueStore<byte[], byte[]> timerStore;
+
+ WindowedGroupByKeyProcessor(
+ String stateStoreName,
+ String timerStoreName,
+ String transformId,
+ Set<String> upstreamTransformIds,
+ Coder<K> keyCoder,
+ Coder<V> valueCoder,
+ WindowingStrategy<?, W> windowingStrategy,
+ PipelineOptions options) {
+ this.stateStoreName = stateStoreName;
+ this.timerStoreName = timerStoreName;
+ this.transformId = transformId;
+ this.keyCoder = keyCoder;
+ this.windowingStrategy = windowingStrategy;
+ this.windowCoder = windowingStrategy.getWindowFn().windowCoder();
+ this.triggerProto = TriggerTranslation.toProto(windowingStrategy.getTrigger());
+ this.reduceFn = SystemReduceFn.buffering(valueCoder);
+ this.options = options;
+ this.watermarkAggregator = new WatermarkAggregator(upstreamTransformIds);
+ }
+
+ @Override
+ public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) {
+ this.context = context;
+ this.stateStore = context.getStateStore(stateStoreName);
+ this.timerStore = context.getStateStore(timerStoreName);
+ }
+
+ @Override
+ public void process(Record<byte[], KStreamsPayload<?>> record) {
+ KStreamsPayload<?> payload = record.value();
+ if (payload == null) {
+ LOG.warn(
+ "GroupByKey {} dropping record with null payload (external write or tombstone)",
+ transformId);
+ return;
+ }
+ if (payload.isData()) {
+ processData(record, payload);
+ return;
+ }
+ watermarkAggregator.observe(payload.asWatermark());
+ Instant advanced = watermarkAggregator.advance();
+ if (advanced.isAfter(lastForwardedWatermark)) {
+ inputWatermark = advanced;
+ fireDueEventTimeTimers(record, advanced);
+ lastForwardedWatermark = advanced;
+ forwardWatermark(record, advanced.getMillis());
+ }
+ }
+
+ private void processData(Record<byte[], KStreamsPayload<?>> record, KStreamsPayload<?> payload) {
+ byte[] encodedKey = record.key();
+ if (encodedKey == null) {
+ throw new IllegalStateException("GroupByKey data record is missing its key");
+ }
+ @SuppressWarnings("unchecked")
+ WindowedValue<KV<K, V>> element = (WindowedValue<KV<K, V>>) payload.getData();
+ K key = decodeKey(encodedKey);
+ WindowedValue<V> valueElement = element.withValue(element.getValue().getValue());
+ runReduceFn(
+ record, encodedKey, key, Collections.singletonList(valueElement), Collections.emptyList());
+ }
+
+ /** Fires every event-time timer whose fire time is at or before the new input watermark. */
+ private void fireDueEventTimeTimers(
+ Record<byte[], KStreamsPayload<?>> record, Instant watermark) {
+ KeyValueStore<byte[], byte[]> timers = checkInitialized(timerStore);
+ // Group due timers by the Beam key they belong to; a key's timers fire together in one
+ // ReduceFnRunner turn. Whole-store scan per advance is O(timers) — see the class doc.
+ Map<String, DueTimers> dueByKey = new LinkedHashMap<>();
+ List<byte[]> firedStoreKeys = new ArrayList<>();
+ try (KeyValueIterator<byte[], byte[]> it = timers.all()) {
Review Comment:
This looks expensive. And we call it for each watermark move, we need a way to efficiently select only timers that should expire, not iterate all timers, because there will be a timer for each key and that cen be a long list.
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/KafkaStreamsTimerInternals.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import org.apache.beam.runners.core.StateNamespace;
+import org.apache.beam.runners.core.TimerInternals;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * A {@link TimerInternals} for one key, backed by a shared Kafka Streams timer {@link
+ * KeyValueStore} for a GroupByKey.
+ *
+ * <p>Kafka Streams has no per-key timer service, so timers are persisted like any other state. A
+ * timer is stored under a key built from its identity — {@code key | domain | timerFamily | timerId
+ * | namespace} — so setting a timer with the same identity overwrites the previous one and deleting
+ * it removes exactly that entry, matching {@link TimerInternals}' contract. The value is the {@link
+ * TimerData} encoded with {@link TimerInternals.TimerDataCoderV2}, which carries the fire time.
+ *
+ * <p>Firing is driven by {@link WindowedGroupByKeyProcessor}: on a watermark advance it scans the
+ * store for event-time timers whose fire time has passed and replays them through {@link
+ * org.apache.beam.runners.core.ReduceFnRunner#onTimers}. Scanning the whole store per advance is
+ * O(timers); acceptable for this first windowing support and replaceable with a fire-time-ordered
+ * index later, the same way the initial GroupByKey buffered eagerly.
+ *
+ * <p>This instance reports the current input-watermark and processing times it was constructed with
+ * (the caller advances them as reports arrive); it never fires timers itself.
+ */
+class KafkaStreamsTimerInternals implements TimerInternals {
+
+ private final byte[] encodedKey;
+ private final KeyValueStore<byte[], byte[]> timerStore;
+ private final TimerInternals.TimerDataCoderV2 timerCoder;
+ private final Instant inputWatermarkTime;
+ private final Instant processingTime;
+
+ KafkaStreamsTimerInternals(
+ byte[] encodedKey,
+ KeyValueStore<byte[], byte[]> timerStore,
+ Coder<? extends BoundedWindow> windowCoder,
+ Instant inputWatermarkTime,
+ Instant processingTime) {
+ this.encodedKey = encodedKey;
+ this.timerStore = timerStore;
+ this.timerCoder = TimerInternals.TimerDataCoderV2.of(windowCoder);
+ this.inputWatermarkTime = inputWatermarkTime;
+ this.processingTime = processingTime;
+ }
+
+ @Override
+ public void setTimer(
+ StateNamespace namespace,
+ String timerId,
+ String timerFamilyId,
+ Instant target,
+ Instant outputTimestamp,
+ TimeDomain timeDomain) {
+ setTimer(TimerData.of(timerId, timerFamilyId, namespace, target, outputTimestamp, timeDomain));
+ }
+
+ @Override
+ public void setTimer(TimerData timerData) {
+ timerStore.put(timerStoreKey(encodedKey, timerData), encodeTimer(timerData));
+ }
+
+ @Override
+ public void deleteTimer(
+ StateNamespace namespace, String timerId, String timerFamilyId, TimeDomain timeDomain) {
+ timerStore.delete(timerStoreKey(encodedKey, timerId, timerFamilyId, timeDomain, namespace));
+ }
+
+ @Override
+ public void deleteTimer(StateNamespace namespace, String timerId, String timerFamilyId) {
+ throw new UnsupportedOperationException(
+ "Deleting a timer without a time domain is not supported; the domain is part of a timer's"
+ + " store identity.");
+ }
+
+ @Override
+ public void deleteTimer(TimerData timerKey) {
+ timerStore.delete(timerStoreKey(encodedKey, timerKey));
+ }
+
+ @Override
+ public Instant currentProcessingTime() {
+ return processingTime;
+ }
+
+ @Override
+ public @Nullable Instant currentSynchronizedProcessingTime() {
+ return null;
+ }
+
+ @Override
+ public Instant currentInputWatermarkTime() {
+ return inputWatermarkTime;
+ }
+
+ @Override
+ public @Nullable Instant currentOutputWatermarkTime() {
+ return null;
Review Comment:
Why we return null here? Can we add comment explaining if this is going to be fixed in future and what it depends on? Same for synchronized processing time.
##########
runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/KafkaStreamsTimerInternals.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.kafka.streams.translation;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import org.apache.beam.runners.core.StateNamespace;
+import org.apache.beam.runners.core.TimerInternals;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.CoderException;
+import org.apache.beam.sdk.state.TimeDomain;
+import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
+import org.apache.beam.sdk.util.CoderUtils;
+import org.apache.kafka.streams.state.KeyValueStore;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.joda.time.Instant;
+
+/**
+ * A {@link TimerInternals} for one key, backed by a shared Kafka Streams timer {@link
+ * KeyValueStore} for a GroupByKey.
+ *
+ * <p>Kafka Streams has no per-key timer service, so timers are persisted like any other state. A
+ * timer is stored under a key built from its identity — {@code key | domain | timerFamily | timerId
+ * | namespace} — so setting a timer with the same identity overwrites the previous one and deleting
+ * it removes exactly that entry, matching {@link TimerInternals}' contract. The value is the {@link
+ * TimerData} encoded with {@link TimerInternals.TimerDataCoderV2}, which carries the fire time.
+ *
+ * <p>Firing is driven by {@link WindowedGroupByKeyProcessor}: on a watermark advance it scans the
+ * store for event-time timers whose fire time has passed and replays them through {@link
+ * org.apache.beam.runners.core.ReduceFnRunner#onTimers}. Scanning the whole store per advance is
+ * O(timers); acceptable for this first windowing support and replaceable with a fire-time-ordered
+ * index later, the same way the initial GroupByKey buffered eagerly.
+ *
+ * <p>This instance reports the current input-watermark and processing times it was constructed with
+ * (the caller advances them as reports arrive); it never fires timers itself.
+ */
+class KafkaStreamsTimerInternals implements TimerInternals {
+
+ private final byte[] encodedKey;
+ private final KeyValueStore<byte[], byte[]> timerStore;
+ private final TimerInternals.TimerDataCoderV2 timerCoder;
+ private final Instant inputWatermarkTime;
+ private final Instant processingTime;
+
+ KafkaStreamsTimerInternals(
+ byte[] encodedKey,
+ KeyValueStore<byte[], byte[]> timerStore,
+ Coder<? extends BoundedWindow> windowCoder,
+ Instant inputWatermarkTime,
+ Instant processingTime) {
+ this.encodedKey = encodedKey;
+ this.timerStore = timerStore;
+ this.timerCoder = TimerInternals.TimerDataCoderV2.of(windowCoder);
+ this.inputWatermarkTime = inputWatermarkTime;
+ this.processingTime = processingTime;
+ }
+
+ @Override
+ public void setTimer(
+ StateNamespace namespace,
+ String timerId,
+ String timerFamilyId,
+ Instant target,
+ Instant outputTimestamp,
+ TimeDomain timeDomain) {
+ setTimer(TimerData.of(timerId, timerFamilyId, namespace, target, outputTimestamp, timeDomain));
+ }
+
+ @Override
+ public void setTimer(TimerData timerData) {
+ timerStore.put(timerStoreKey(encodedKey, timerData), encodeTimer(timerData));
+ }
+
+ @Override
+ public void deleteTimer(
+ StateNamespace namespace, String timerId, String timerFamilyId, TimeDomain timeDomain) {
+ timerStore.delete(timerStoreKey(encodedKey, timerId, timerFamilyId, timeDomain, namespace));
+ }
+
+ @Override
+ public void deleteTimer(StateNamespace namespace, String timerId, String timerFamilyId) {
+ throw new UnsupportedOperationException(
+ "Deleting a timer without a time domain is not supported; the domain is part of a timer's"
+ + " store identity.");
+ }
+
+ @Override
+ public void deleteTimer(TimerData timerKey) {
+ timerStore.delete(timerStoreKey(encodedKey, timerKey));
+ }
+
+ @Override
+ public Instant currentProcessingTime() {
+ return processingTime;
+ }
+
+ @Override
+ public @Nullable Instant currentSynchronizedProcessingTime() {
+ return null;
+ }
+
+ @Override
+ public Instant currentInputWatermarkTime() {
+ return inputWatermarkTime;
+ }
+
+ @Override
+ public @Nullable Instant currentOutputWatermarkTime() {
+ return null;
+ }
+
+ private byte[] encodeTimer(TimerData timerData) {
+ try {
+ return CoderUtils.encodeToByteArray(timerCoder, timerData);
+ } catch (CoderException e) {
+ throw new RuntimeException("Failed to encode timer " + timerData, e);
+ }
+ }
+
+ /** The store key for a timer's identity. Package-visible so the processor can build/scan it. */
+ static byte[] timerStoreKey(byte[] encodedKey, TimerData timerData) {
+ return timerStoreKey(
+ encodedKey,
+ timerData.getTimerId(),
+ timerData.getTimerFamilyId(),
+ timerData.getDomain(),
+ timerData.getNamespace());
+ }
+
+ static byte[] timerStoreKey(
+ byte[] encodedKey,
+ String timerId,
+ String timerFamilyId,
+ TimeDomain domain,
+ StateNamespace namespace) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ writeSegment(out, encodedKey);
Review Comment:
Because we need to be able to efficiently parse key from the stored byte[] it seems this approach is a spot on 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