je-ik commented on code in PR #39141: URL: https://github.com/apache/beam/pull/39141#discussion_r3497204505
########## runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/GroupByKeyProcessor.java: ########## @@ -0,0 +1,189 @@ +/* + * 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.List; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.CoderException; +import org.apache.beam.sdk.coders.IterableCoder; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.util.CoderUtils; +import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.WindowedValue; +import org.apache.beam.sdk.values.WindowedValues; +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.Nullable; +import org.joda.time.Instant; + +/** + * Executes a {@code GroupByKey} (GlobalWindow, default trigger, no allowed lateness). + * + * <p>Records arrive on the repartition topic keyed by the encoded Beam key, so every value of a key + * is co-located here. Each value is appended to a per-key buffer in a Kafka Streams state store. + * Watermark reports are fed to a {@link WatermarkManager}; when the input watermark reaches {@link + * BoundedWindow#TIMESTAMP_MAX_VALUE} (the end of the global window) every buffered key is emitted + * once as {@code KV<K, Iterable<V>>} and the buffer cleared, then the watermark is forwarded + * downstream. + * + * <p>Buffering whole value lists and re-encoding on each append is O(n^2) per key; fine for this + * first GroupByKey, and replaced when this moves to runner-core {@code GroupAlsoByWindow}. + */ +class GroupByKeyProcessor + implements Processor<byte[], KStreamsPayload<?>, byte[], KStreamsPayload<?>> { + + private final String stateStoreName; + private final Coder<Object> keyCoder; + private final IterableCoder<@Nullable Object> bufferCoder; + + private final WatermarkManager watermarkManager = new WatermarkManager(); + private Instant lastForwardedWatermark = BoundedWindow.TIMESTAMP_MIN_VALUE; + // The global window fires exactly once, when the watermark first reaches its end. Later watermark + // reports (e.g. the same terminal watermark broadcast across repartition partitions) must not + // re-fire. + private boolean fired = false; + + private @Nullable ProcessorContext<byte[], KStreamsPayload<?>> context; + private @Nullable KeyValueStore<byte[], byte[]> store; + + GroupByKeyProcessor( + String stateStoreName, Coder<Object> keyCoder, Coder<@Nullable Object> valueCoder) { + this.stateStoreName = stateStoreName; + this.keyCoder = keyCoder; + this.bufferCoder = IterableCoder.of(valueCoder); + } + + @Override + public void init(ProcessorContext<byte[], KStreamsPayload<?>> context) { + this.context = context; + this.store = context.getStateStore(stateStoreName); + } + + @Override + public void process(Record<byte[], KStreamsPayload<?>> record) { + KStreamsPayload<?> payload = record.value(); + if (payload.isData()) { + byte[] encodedKey = record.key(); + Object element = payload.getData().getValue(); + if (encodedKey == null || element == null) { + throw new IllegalStateException("GroupByKey data record is missing its key or value"); + } + appendValue(encodedKey, element); + return; + } + WatermarkPayload report = payload.asWatermark(); + watermarkManager.observe( + report.getSourcePartition(), + new Instant(report.getWatermarkMillis()), + report.getTotalSourcePartitions()); + Instant advanced = watermarkManager.advance(); + if (!fired && !advanced.isBefore(BoundedWindow.TIMESTAMP_MAX_VALUE)) { + fireAll(record); + fired = true; + } + if (advanced.isAfter(lastForwardedWatermark)) { + lastForwardedWatermark = advanced; + forwardWatermark(record, advanced.getMillis()); + } + } + + private void appendValue(byte[] encodedKey, Object kvObject) { + KV<?, ?> kv = (KV<?, ?>) kvObject; + KeyValueStore<byte[], byte[]> kvStore = checkInitialized(store); + byte[] existing = kvStore.get(encodedKey); + List<@Nullable Object> values = existing == null ? new ArrayList<>() : decodeBuffer(existing); + values.add(kv.getValue()); + kvStore.put(encodedKey, encodeBuffer(values)); + } + + private void fireAll(Record<byte[], KStreamsPayload<?>> trigger) { + ProcessorContext<byte[], KStreamsPayload<?>> ctx = checkInitialized(context); + KeyValueStore<byte[], byte[]> kvStore = checkInitialized(store); + List<byte[]> firedKeys = new ArrayList<>(); Review Comment: > Checked (a) Kafka Streams' KeyValueIterator just extends java.util.Iterator and doesn't override remove(), so it inherits the default that throws UnsupportedOperationException; the RocksDB and in-memory store iterators don't implement it either. So iterator.remove() isn't available. That is likely only an issue in the Java wrapper, because I'd say it should be - technically - possible to delete records from RocksDB as you iterate it. > Worth noting the firedKeys list is actually a small part of the memory here — the buffered values in the state store and the emitted output records dominate, so dropping just the list wouldn't really move the OOM needle. Yeah, we'll currently probably go with buffering grouped elements into memory (we should definitely take care to buffer only elements per single key at a time), optimizing this can be postponed right 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
