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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
