gemini-code-assist[bot] commented on code in PR #39141: URL: https://github.com/apache/beam/pull/39141#discussion_r3487678006
########## runners/kafka-streams/src/main/java/org/apache/beam/runners/kafka/streams/translation/GroupByKeyProcessor.java: ########## @@ -0,0 +1,182 @@ +/* + * 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.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<>(); + try (KeyValueIterator<byte[], byte[]> it = kvStore.all()) { + while (it.hasNext()) { + org.apache.kafka.streams.KeyValue<byte[], byte[]> entry = it.next(); + Object key = decodeKey(entry.key); + List<@Nullable Object> values = decodeBuffer(entry.value); + WindowedValue<KV<Object, Iterable<@Nullable Object>>> output = + WindowedValues.valueInGlobalWindow(KV.of(key, (Iterable<@Nullable Object>) values)); Review Comment:  Using `WindowedValues.valueInGlobalWindow` hardcodes the output timestamp to `BoundedWindow.TIMESTAMP_MIN_VALUE`. Since the watermark has already advanced to `TIMESTAMP_MAX_VALUE` when this fires, outputting elements with `TIMESTAMP_MIN_VALUE` makes them extremely late. Downstream transforms with zero allowed lateness (the default) may silently discard these elements. Instead, use `WindowedValue.timestampedValueInGlobalWindow` with `BoundedWindow.TIMESTAMP_MAX_VALUE` to ensure the output elements are on-time and not discarded. ```java WindowedValue<KV<Object, Iterable<@Nullable Object>>> output = WindowedValue.timestampedValueInGlobalWindow( KV.of(key, (Iterable<@Nullable Object>) values), BoundedWindow.TIMESTAMP_MAX_VALUE); ``` ########## runners/kafka-streams/src/test/java/org/apache/beam/runners/kafka/streams/translation/GroupByKeyTest.java: ########## @@ -0,0 +1,184 @@ +/* + * 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 static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import org.apache.beam.model.pipeline.v1.RunnerApi; +import org.apache.beam.runners.fnexecution.provisioning.JobInfo; +import org.apache.beam.runners.kafka.streams.KafkaStreamsPipelineOptions; +import org.apache.beam.sdk.Pipeline; +import org.apache.beam.sdk.coders.KvCoder; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.coders.VarIntCoder; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.options.PortablePipelineOptions; +import org.apache.beam.sdk.testing.CrashingRunner; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.GroupByKey; +import org.apache.beam.sdk.transforms.Impulse; +import org.apache.beam.sdk.transforms.ParDo; +import org.apache.beam.sdk.util.construction.Environments; +import org.apache.beam.sdk.util.construction.PTransformTranslation; +import org.apache.beam.sdk.util.construction.PipelineOptionsTranslation; +import org.apache.beam.sdk.util.construction.PipelineTranslation; +import org.apache.beam.sdk.values.KV; +import org.apache.kafka.common.serialization.ByteArrayDeserializer; +import org.apache.kafka.common.serialization.ByteArraySerializer; +import org.apache.kafka.common.serialization.Serdes; +import org.apache.kafka.streams.StreamsConfig; +import org.apache.kafka.streams.TestInputTopic; +import org.apache.kafka.streams.TestOutputTopic; +import org.apache.kafka.streams.Topology; +import org.apache.kafka.streams.TopologyTestDriver; +import org.apache.kafka.streams.test.TestRecord; +import org.junit.Test; + +/** + * End-to-end test of GroupByKey: {@code Impulse -> emit KVs -> GroupByKey -> record groups}. + * + * <p>GroupByKey shuffles through an internal repartition topic. {@link TopologyTestDriver} does not + * loop a low-level sink topic back into its source, so the test drives the upstream, drains the + * repartition topic, and pipes those records back into it — standing in for the broker round-trip. + * The downstream {@code RecordGroupFn} records each emitted group into a {@link + * SharedTestCollector}. + */ +public class GroupByKeyTest { + + private static final String JOB_ID = "ks-gbk-test"; + private static final String APPLICATION_ID = "ks-gbk-test"; + + /** Emits a few KVs from the single impulse element so there is something to group. */ + private static class EmitKvsFn extends DoFn<byte[], KV<String, Integer>> { + @ProcessElement + public void processElement(OutputReceiver<KV<String, Integer>> out) { + out.output(KV.of("a", 1)); + out.output(KV.of("a", 2)); + out.output(KV.of("b", 3)); + } + } + + /** Records each grouped result as {@code "key=[sorted values]"}. */ + private static class RecordGroupFn extends DoFn<KV<String, Iterable<Integer>>, Void> { + private final SharedTestCollector<String> collector; + + RecordGroupFn(SharedTestCollector<String> collector) { + this.collector = collector; + } + + @ProcessElement + public void processElement(@Element KV<String, Iterable<Integer>> group) { + List<Integer> values = new ArrayList<>(); + group.getValue().forEach(values::add); + Collections.sort(values); + collector.record(group.getKey() + "=" + values); + } + } + + @Test + public void groupsValuesByKeyAndFiresAtWatermark() throws Exception { + try (SharedTestCollector<String> collector = SharedTestCollector.create()) { + Pipeline pipeline = Pipeline.create(pipelineOptions()); + pipeline + .apply("impulse", Impulse.create()) + .apply("emit", ParDo.of(new EmitKvsFn())) + .setCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())) + .apply("gbk", GroupByKey.create()) + .apply("record", ParDo.of(new RecordGroupFn(collector))); + + RunnerApi.Pipeline pipelineProto = PipelineTranslation.toProto(pipeline); + KafkaStreamsPipelineOptions options = + pipeline.getOptions().as(KafkaStreamsPipelineOptions.class); + KafkaStreamsPipelineTranslator translator = new KafkaStreamsPipelineTranslator(); + JobInfo jobInfo = + JobInfo.create( + JOB_ID, options.getJobName(), "", PipelineOptionsTranslation.toProto(options)); + KafkaStreamsTranslationContext context = + translator.createTranslationContext(jobInfo, options); + + RunnerApi.Pipeline prepared = translator.prepareForTranslation(pipelineProto); + translator.translate(context, prepared); + String repartitionTopic = GroupByKeyTranslator.repartitionTopic(findGroupByKeyId(prepared)); + + Topology topology = context.getTopology(); + try (TopologyTestDriver driver = new TopologyTestDriver(topology, streamsConfig())) { + // Fire the impulse; the upstream stage emits the KVs and the terminal watermark, which the + // re-key processor sends to the repartition sink. + driver.advanceWallClockTime(Duration.ofSeconds(1)); + driver.advanceWallClockTime(Duration.ofSeconds(1)); + + // Round-trip the repartition topic: drain what the sink wrote and feed it back to the + // source so the GroupByKey processor buffers the values and fires at the watermark. + TestOutputTopic<byte[], byte[]> repartitionOut = + driver.createOutputTopic( + repartitionTopic, new ByteArrayDeserializer(), new ByteArrayDeserializer()); + TestInputTopic<byte[], byte[]> repartitionIn = + driver.createInputTopic( + repartitionTopic, new ByteArraySerializer(), new ByteArraySerializer()); + for (TestRecord<byte[], byte[]> record : repartitionOut.readRecordsToList()) { + repartitionIn.pipeInput(record.key(), record.value()); + } Review Comment:  Instead of manually extracting the key and value and piping them, you can pass the `TestRecord` directly to `pipeInput`. This is cleaner, shorter, and preserves all record metadata (such as timestamps and headers), making the test more realistic and robust. ```suggestion for (TestRecord<byte[], byte[]> record : repartitionOut.readRecordsToList()) { repartitionIn.pipeInput(record); } ``` -- 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]
