From 1772c586d7100e6ddfbc1cc182ff31e587537ff5 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Fri, 20 Nov 2026 12:28:34 -0800 Subject: [PATCH 1/4] Add allocation-free WindowedValues fast paths and optimize OutputReceivers / FnApiDoFnRunner - WindowedValues: add ofWithCurrentContext(...) and builder(template, value) helpers, omit redundant OpenTelemetry Context.root() references, and add SingleWindowedValue fast paths in FullWindowedValueCoder encode/decode/registerByteSizeObserver. - OutputBuilderSupplier / OutputBuilderSuppliers / DoFnOutputReceivers: add direct build(value) and buildWithTimestamp(value, ts) methods avoiding intermediate Builder and lambda allocations on every emitted element. - FnApiDoFnRunner: use WindowedValues.ofWithCurrentContext(...) and builder(elem, val) in output receivers. - Add unit tests in WindowedValueTest and JMH benchmarks in OutputReceiverBenchmark. --- .../beam/runners/core/SimpleDoFnRunner.java | 548 ++++++++++-- .../runners/core/SimpleDoFnRunnerTest.java | 785 ++++++++++++++++++ .../transforms/OutputReceiverBenchmark.java | 175 ++++ .../beam/sdk/jmh/transforms/package-info.java | 20 + .../sdk/transforms/DoFnOutputReceivers.java | 37 +- .../beam/sdk/util/OutputBuilderSupplier.java | 15 + .../beam/sdk/util/OutputBuilderSuppliers.java | 13 +- .../beam/sdk/values/WindowedValues.java | 436 +++++++++- .../beam/sdk/util/WindowedValueTest.java | 194 +++++ .../beam/fn/harness/FnApiDoFnRunner.java | 65 +- 10 files changed, 2185 insertions(+), 103 deletions(-) create mode 100644 sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java create mode 100644 sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/package-info.java diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java index 09ac17d2a2f3..3ab08d1d92cf 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java @@ -23,11 +23,13 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.options.PipelineOptions; @@ -59,7 +61,9 @@ import org.apache.beam.sdk.util.SystemDoFnInternal; import org.apache.beam.sdk.util.UserCodeException; import org.apache.beam.sdk.util.WindowedValueMultiReceiver; +import org.apache.beam.sdk.util.WindowedValueReceiver; import org.apache.beam.sdk.values.CausedByDrain; +import org.apache.beam.sdk.values.OutputBuilder; import org.apache.beam.sdk.values.PCollectionView; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; @@ -68,7 +72,6 @@ import org.apache.beam.sdk.values.WindowedValues; import org.apache.beam.sdk.values.WindowingStrategy; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions; -import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.FluentIterable; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Sets; import org.checkerframework.checker.initialization.qual.Initialized; @@ -91,6 +94,10 @@ */ public class SimpleDoFnRunner implements DoFnRunner { + private static final long MIN_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); + private static final long MAX_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis(); + private static final int MAX_INLINE_EXTRA_TAGS = 8; + private final PipelineOptions options; /** The {@link DoFn} being run. */ @@ -100,12 +107,18 @@ public class SimpleDoFnRunner implements DoFnRunner invoker; private final SideInputReader sideInputReader; - private final WindowedValueMultiReceiver outputManager; + final WindowedValueMultiReceiver outputManager; - private final TupleTag mainOutputTag; + final TupleTag mainOutputTag; /** The set of known output tags. */ - private final Set> outputTags; + final Set> outputTags; + + /** + * Deduplicated non-main output tags in declaration order when {@code 1 <= count <= + * MAX_INLINE_EXTRA_TAGS}; {@code null} for single-output or large fan-out {@code DoFn}s. + */ + final TupleTag @Nullable [] extraOutputTags; private final boolean observesWindow; @@ -115,18 +128,25 @@ public class SimpleDoFnRunner implements DoFnRunner mainOutputSchemaCoder; - private final @Nullable Map, Coder> outputCoders; + final @Nullable Map, Coder> outputCoders; private final @Nullable DoFnSchemaInformation doFnSchemaInformation; private final Map> sideInputMapping; + private @Nullable DoFnProcessContext reusableProcessContext; + /** Constructor. */ + @SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected public SimpleDoFnRunner( PipelineOptions options, DoFn fn, @@ -156,8 +176,25 @@ public SimpleDoFnRunner( } this.outputManager = outputManager; this.mainOutputTag = mainOutputTag; - this.outputTags = - Sets.newHashSet(FluentIterable.>of(mainOutputTag).append(additionalOutputTags)); + if (additionalOutputTags.isEmpty()) { + this.outputTags = Collections.singleton(mainOutputTag); + this.extraOutputTags = null; + } else { + Set> tags = Sets.newHashSetWithExpectedSize(1 + additionalOutputTags.size()); + tags.add(mainOutputTag); + List> orderedExtras = new ArrayList<>(additionalOutputTags.size()); + for (TupleTag tag : additionalOutputTags) { + if (tags.add(tag)) { + orderedExtras.add(tag); + } + } + this.outputTags = tags; + if (orderedExtras.isEmpty() || orderedExtras.size() > MAX_INLINE_EXTRA_TAGS) { + this.extraOutputTags = null; + } else { + this.extraOutputTags = orderedExtras.toArray(new TupleTag[0]); + } + } this.stepContext = stepContext; // This is a cast of an _invariant_ coder. But we are assured by pipeline validation @@ -167,6 +204,9 @@ public SimpleDoFnRunner( (Coder) windowingStrategy.getWindowFn().windowCoder(); this.windowCoder = untypedCoder; this.allowedLateness = windowingStrategy.getAllowedLateness(); + Duration rawSkew = fn.getAllowedTimestampSkew(); + this.allowedTimestampSkew = rawSkew != null ? rawSkew : Duration.ZERO; + this.allowedTimestampSkewMillis = this.allowedTimestampSkew.getMillis(); this.doFnSchemaInformation = doFnSchemaInformation; this.sideInputMapping = sideInputMapping; } @@ -189,22 +229,31 @@ public void startBundle() { @Override public void processElement(WindowedValue compressedElem) { Context openTelemetryContext = compressedElem.getOpenTelemetryContext(); - if (openTelemetryContext == null) { + if (openTelemetryContext == null || openTelemetryContext == Context.current()) { processElementInternal(compressedElem); } else { - try (Scope ignore = openTelemetryContext.makeCurrent()) { - processElementInternal(compressedElem); - } + processElementWithContext(compressedElem, openTelemetryContext); + } + } + + private void processElementWithContext( + WindowedValue compressedElem, Context openTelemetryContext) { + try (Scope ignore = openTelemetryContext.makeCurrent()) { + processElementInternal(compressedElem); } } private void processElementInternal(WindowedValue compressedElem) { - if (observesWindow) { - for (WindowedValue elem : compressedElem.explodeWindows()) { - invokeProcessElement(elem); - } - } else { + if (!observesWindow || WindowedValues.singleWindowOrNull(compressedElem) != null) { invokeProcessElement(compressedElem); + } else { + explodeAndInvokeProcessElement(compressedElem); + } + } + + private void explodeAndInvokeProcessElement(WindowedValue compressedElem) { + for (WindowedValue elem : compressedElem.explodeWindows()) { + invokeProcessElement(elem); } } @@ -228,10 +277,38 @@ public void onTimer( private void invokeProcessElement(WindowedValue elem) { // This can contain user code. Wrap it in case it throws an exception. + DoFnProcessContext context = reusableProcessContext; + if (context == null) { + context = initReusableProcessContext(); + } + if (context.elem == null) { + context.setElement(elem); + try { + invoker.invokeProcessElement(context); + } catch (Exception e) { + throw wrapUserCodeException(e); + } finally { + context.clearElement(); + } + } else { + invokeProcessElementReentrant(elem); + } + } + + private DoFnProcessContext initReusableProcessContext() { + DoFnProcessContext context = new DoFnProcessContext(); + reusableProcessContext = context; + return context; + } + + private void invokeProcessElementReentrant(WindowedValue elem) { + DoFnProcessContext reentrantContext = new DoFnProcessContext(elem); try { - invoker.invokeProcessElement(new DoFnProcessContext(elem)); + invoker.invokeProcessElement(reentrantContext); } catch (Exception e) { throw wrapUserCodeException(e); + } finally { + reentrantContext.clearElement(); } } @@ -269,11 +346,39 @@ private T sideInput(PCollectionView view, BoundedWindow sideInputWindow) return sideInputReader.get(view, sideInputWindow); } - @SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected - private void checkTimestamp(Instant elemTimestamp, Instant timestamp) { + void checkSameElementTimestamp(Instant elemTimestamp) { + long skewMillis = allowedTimestampSkewMillis; + if (skewMillis == 0L) { + if (elemTimestamp.getMillis() <= MAX_TIMESTAMP_MILLIS) { + return; + } + } else if (skewMillis > 0L) { + long tsMillis = elemTimestamp.getMillis(); + if (tsMillis >= MIN_TIMESTAMP_MILLIS && tsMillis <= MAX_TIMESTAMP_MILLIS) { + return; + } + } + checkTimestampSlowPath(elemTimestamp, elemTimestamp); + } + + void checkTimestamp(Instant elemTimestamp, Instant timestamp) { + long tsMillis = timestamp.getMillis(); + long skewMillis = allowedTimestampSkewMillis; + if (skewMillis >= 0L) { + long elemMillis = elemTimestamp.getMillis(); + long lowerBoundMillis = + elemMillis < Long.MIN_VALUE + skewMillis ? MIN_TIMESTAMP_MILLIS : elemMillis - skewMillis; + if (tsMillis >= lowerBoundMillis && tsMillis <= MAX_TIMESTAMP_MILLIS) { + return; + } + } + checkTimestampSlowPath(elemTimestamp, timestamp); + } + + private void checkTimestampSlowPath(Instant elemTimestamp, Instant timestamp) { Instant lowerBound; try { - lowerBound = elemTimestamp.minus(fn.getAllowedTimestampSkew()); + lowerBound = elemTimestamp.minus(allowedTimestampSkew); } catch (ArithmeticException e) { lowerBound = BoundedWindow.TIMESTAMP_MIN_VALUE; } @@ -286,18 +391,34 @@ private void checkTimestamp(Instant elemTimestamp, Instant timestamp) { + "on changing the allowed skew.", timestamp, elemTimestamp, - fn.getAllowedTimestampSkew().getMillis() >= Integer.MAX_VALUE - ? fn.getAllowedTimestampSkew() - : PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod()), + allowedTimestampSkewMillis >= Integer.MAX_VALUE + ? allowedTimestampSkew + : PeriodFormat.getDefault().print(allowedTimestampSkew.toPeriod()), BoundedWindow.TIMESTAMP_MAX_VALUE)); } } - private void outputWindowedValue(TupleTag tag, WindowedValue windowedElem) { - checkArgument(outputTags.contains(tag), "Unknown output tag %s", tag); + @SuppressWarnings("ReferenceEquality") + void outputWindowedValue(TupleTag tag, WindowedValue windowedElem) { + if (tag != mainOutputTag) { + validateSideOutputTag(tag); + } outputManager.output(tag, windowedElem); } + @SuppressWarnings("ReferenceEquality") + private void validateSideOutputTag(TupleTag tag) { + TupleTag @Nullable [] extraTags = this.extraOutputTags; + if (extraTags != null) { + for (int i = 0; i < extraTags.length; i++) { + if (extraTags[i] == tag) { + return; + } + } + } + checkArgument(outputTags.contains(tag), "Unknown output tag %s", tag); + } + /** An {@link DoFnInvoker.ArgumentProvider} for {@link DoFn.StartBundle @StartBundle}. */ private class DoFnStartBundleArgumentProvider extends DoFnInvoker.BaseArgumentProvider { @@ -389,16 +510,45 @@ public BundleFinalizer bundleFinalizer() { /** * A concrete implementation of {@link DoFn.ProcessContext} used for running a {@link DoFn} over a - * single element. + * single element. A single instance is reused across non-reentrant {@code @ProcessElement} + * invocations via {@link #setElement(WindowedValue)} / {@link #clearElement()}; callers accessing + * a retained context or receiver after {@code @ProcessElement} returns fail fast with {@link + * IllegalStateException}. */ - private class DoFnProcessContext extends DoFn.ProcessContext - implements DoFnInvoker.ArgumentProvider { - final WindowedValue elem; + private final class DoFnProcessContext extends DoFn.ProcessContext + implements DoFnInvoker.ArgumentProvider, OutputBuilderSupplier { + @Nullable WindowedValue elem; /** Lazily initialized; should only be accessed via {@link #getNamespace()}. */ private @Nullable StateNamespace namespace; - private final OutputBuilderSupplier builderSupplier; + private @Nullable DirectOutputReceiver cachedOutputReceiver; + private @Nullable OutputReceiver cachedOutputRowReceiver; + private @Nullable CachedMultiOutputReceiver cachedMultiOutputReceiver; + + DoFnProcessContext() { + fn.super(); + } + + DoFnProcessContext(WindowedValue elem) { + fn.super(); + this.elem = elem; + } + + void setElement(WindowedValue elem) { + this.elem = elem; + } + + void clearElement() { + this.elem = null; + if (this.namespace != null) { + this.namespace = null; + } + } + + WindowedValue currentElem() { + return checkStateNotNull(elem, "DoFnProcessContext accessed outside of @ProcessElement"); + } /** * The state namespace for this context. @@ -414,10 +564,19 @@ private StateNamespace getNamespace() { return namespace; } - private DoFnProcessContext(WindowedValue elem) { - fn.super(); - this.elem = elem; - this.builderSupplier = OutputBuilderSuppliers.supplierForElement(elem); + @Override + public WindowedValues.Builder builder(T value) { + return WindowedValues.builder(currentElem(), value); + } + + @Override + public WindowedValue build(T value) { + return WindowedValues.ofWithCurrentContext(currentElem(), value); + } + + @Override + public WindowedValue buildWithTimestamp(T value, Instant timestamp) { + return WindowedValues.ofWithCurrentContext(currentElem(), value, timestamp); } @Override @@ -427,30 +586,31 @@ public PipelineOptions getPipelineOptions() { @Override public InputT element() { - return elem.getValue(); + return currentElem().getValue(); } @Override public CausedByDrain causedByDrain() { - return elem.causedByDrain(); + return currentElem().causedByDrain(); } @Override public T sideInput(PCollectionView view) { checkNotNull(view, "View passed to sideInput cannot be null"); - BoundedWindow window = Iterables.getOnlyElement(windows()); + BoundedWindow window = window(); return SimpleDoFnRunner.this.sideInput( view, view.getWindowMappingFn().getSideInputWindow(window)); } @Override public PaneInfo pane() { - return elem.getPaneInfo(); + return currentElem().getPaneInfo(); } @Override public void output(OutputT output) { - output(mainOutputTag, output); + checkNotNull(mainOutputTag, "Tag passed to output cannot be null"); + outputManager.output(mainOutputTag, currentElem().withValue(output)); } @Override @@ -470,7 +630,7 @@ public void outputWindowedValue( @Override public void output(TupleTag tag, T output) { checkNotNull(tag, "Tag passed to output cannot be null"); - SimpleDoFnRunner.this.outputWindowedValue(tag, elem.withValue(output)); + SimpleDoFnRunner.this.outputWindowedValue(tag, currentElem().withValue(output)); } @Override @@ -480,15 +640,17 @@ public void outputWindowedValue(WindowedValue windowedValue) { @Override public void outputWindowedValue(TupleTag tag, WindowedValue windowedValue) { - checkTimestamp(elem.getTimestamp(), windowedValue.getTimestamp()); + checkTimestamp(currentElem().getTimestamp(), windowedValue.getTimestamp()); SimpleDoFnRunner.this.outputWindowedValue(tag, windowedValue); } @Override public void outputWithTimestamp(TupleTag tag, T output, Instant timestamp) { checkNotNull(tag, "Tag passed to outputWithTimestamp cannot be null"); - checkTimestamp(elem.getTimestamp(), timestamp); - outputWindowedValue(tag, output, timestamp, elem.getWindows(), elem.getPaneInfo()); + WindowedValue current = currentElem(); + checkTimestamp(current.getTimestamp(), timestamp); + SimpleDoFnRunner.this.outputWindowedValue( + tag, WindowedValues.ofWithCurrentContext(current, output, timestamp)); } @Override @@ -498,46 +660,44 @@ public void outputWindowedValue( Instant timestamp, Collection windows, PaneInfo paneInfo) { - builderSupplier - .builder(output) - .setTimestamp(timestamp) - .setWindows(windows) - .setPaneInfo(paneInfo) - .setReceiver( - wv -> { - checkTimestamp(elem.getTimestamp(), wv.getTimestamp()); - SimpleDoFnRunner.this.outputWindowedValue(tag, wv); - }) - .output(); + WindowedValue current = currentElem(); + checkTimestamp(current.getTimestamp(), timestamp); + SimpleDoFnRunner.this.outputWindowedValue( + tag, WindowedValues.ofWithCurrentContext(current, output, timestamp, windows, paneInfo)); } @Override public Instant timestamp() { - return elem.getTimestamp(); + return currentElem().getTimestamp(); } @Override public @Nullable String currentRecordId() { - return elem.getRecordId(); + return currentElem().getRecordId(); } @Override public @Nullable Long currentRecordOffset() { - return elem.getRecordOffset(); + return currentElem().getRecordOffset(); } @Override public ValueKind valueKind() { - return elem.getValueKind(); + return currentElem().getValueKind(); } public Collection windows() { - return elem.getWindows(); + return currentElem().getWindows(); } @Override public BoundedWindow window() { - return Iterables.getOnlyElement(elem.getWindows()); + WindowedValue current = currentElem(); + @Nullable BoundedWindow single = WindowedValues.singleWindowOrNull(current); + if (single != null) { + return single; + } + return Iterables.getOnlyElement(current.getWindows()); } @Override @@ -619,12 +779,12 @@ public Instant fireTimestamp(DoFn doFn) { @Override public CausedByDrain causedByDrain(DoFn doFn) { - return elem.causedByDrain(); + return currentElem().causedByDrain(); } @Override public ValueKind valueKind(DoFn doFn) { - return elem.getValueKind(); + return currentElem().getValueKind(); } @Override @@ -641,19 +801,265 @@ public TimeDomain timeDomain(DoFn doFn) { @Override public OutputReceiver outputReceiver(DoFn doFn) { - return DoFnOutputReceivers.windowedReceiver(this, builderSupplier, mainOutputTag); + return getOrCreateMainOutputReceiver(); + } + + private DirectOutputReceiver getOrCreateMainOutputReceiver() { + DirectOutputReceiver receiver = cachedOutputReceiver; + if (receiver == null) { + receiver = new DirectOutputReceiver<>(mainOutputTag, outputManager); + cachedOutputReceiver = receiver; + } + return receiver; } @Override public OutputReceiver outputRowReceiver(DoFn doFn) { - checkStateNotNull(mainOutputSchemaCoder, "cannot provide row receiver without schema coder"); - return DoFnOutputReceivers.rowReceiver( - this, builderSupplier, mainOutputTag, mainOutputSchemaCoder); + OutputReceiver receiver = cachedOutputRowReceiver; + if (receiver == null) { + checkStateNotNull( + mainOutputSchemaCoder, "cannot provide row receiver without schema coder"); + receiver = + DoFnOutputReceivers.rowReceiver(this, this, mainOutputTag, mainOutputSchemaCoder); + cachedOutputRowReceiver = receiver; + } + return receiver; } @Override public MultiOutputReceiver taggedOutputReceiver(DoFn doFn) { - return DoFnOutputReceivers.windowedMultiReceiver(this, builderSupplier, outputCoders); + CachedMultiOutputReceiver receiver = cachedMultiOutputReceiver; + if (receiver == null) { + receiver = new CachedMultiOutputReceiver(mainOutputTag, getOrCreateMainOutputReceiver()); + cachedMultiOutputReceiver = receiver; + } + return receiver; + } + + private final class DirectOutputReceiver + implements OutputReceiver, WindowedValueReceiver { + private final TupleTag tag; + private final WindowedValueMultiReceiver receiverOutputManager; + + DirectOutputReceiver(TupleTag tag, WindowedValueMultiReceiver receiverOutputManager) { + this.tag = tag; + this.receiverOutputManager = receiverOutputManager; + } + + @Override + public void output(T output) { + WindowedValue current = currentElem(); + checkSameElementTimestamp(current.getTimestamp()); + receiverOutputManager.output(tag, WindowedValues.ofWithCurrentContext(current, output)); + } + + @Override + public void outputWithTimestamp(T output, Instant timestamp) { + WindowedValue current = currentElem(); + checkTimestamp(current.getTimestamp(), timestamp); + receiverOutputManager.output( + tag, WindowedValues.ofWithCurrentContext(current, output, timestamp)); + } + + @Override + public void outputWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + WindowedValue current = currentElem(); + checkTimestamp(current.getTimestamp(), timestamp); + receiverOutputManager.output( + tag, WindowedValues.ofWithCurrentContext(current, value, timestamp, windows, paneInfo)); + } + + @Override + public void outputWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + WindowedValue current = currentElem(); + checkTimestamp(current.getTimestamp(), timestamp); + receiverOutputManager.output( + tag, + WindowedValues.ofWithCurrentContext( + current, value, timestamp, windows, paneInfo, valueKind)); + } + + @Override + public OutputBuilder builder(T value) { + return WindowedValues.builder(currentElem(), value).setReceiver(this); + } + + @Override + public void output(WindowedValue windowedValue) { + checkTimestamp(currentElem().getTimestamp(), windowedValue.getTimestamp()); + receiverOutputManager.output(tag, windowedValue); + } + } + + private final class CachedMultiOutputReceiver implements MultiOutputReceiver { + private final @Nullable TupleTag mainTag; + private final DirectOutputReceiver mainReceiver; + private @Nullable TupleTag altMainTag; + private final @Nullable TupleTag singleExtraTag; + private final @Nullable DirectOutputReceiver singleExtraReceiver; + private @Nullable TupleTag altSingleExtraTag; + private final TupleTag @Nullable [] extraTags; + private final DirectOutputReceiver @Nullable [] extraReceivers; + private TupleTag @Nullable [] extraTagAliases; + private final boolean hasLargeFanOut; + private @Nullable Map, DirectOutputReceiver> lazyExtraReceivers; + private @Nullable Map, OutputReceiver> rowReceivers; + + @SuppressWarnings("unchecked") + CachedMultiOutputReceiver( + @Nullable TupleTag mainTag, DirectOutputReceiver mainReceiver) { + this.mainTag = mainTag; + this.mainReceiver = mainReceiver; + TupleTag @Nullable [] runnerExtraTags = extraOutputTags; + if (runnerExtraTags == null) { + this.singleExtraTag = null; + this.singleExtraReceiver = null; + this.extraTags = null; + this.extraReceivers = null; + this.hasLargeFanOut = outputTags.size() - 1 > MAX_INLINE_EXTRA_TAGS; + } else if (runnerExtraTags.length == 1) { + TupleTag onlyExtra = runnerExtraTags[0]; + this.singleExtraTag = onlyExtra; + this.singleExtraReceiver = + new DirectOutputReceiver<>((TupleTag) onlyExtra, outputManager); + this.extraTags = null; + this.extraReceivers = null; + this.hasLargeFanOut = false; + } else { + this.singleExtraTag = null; + this.singleExtraReceiver = null; + @SuppressWarnings("rawtypes") + DirectOutputReceiver[] receivers = new DirectOutputReceiver[runnerExtraTags.length]; + for (int i = 0; i < runnerExtraTags.length; i++) { + receivers[i] = + new DirectOutputReceiver<>((TupleTag) runnerExtraTags[i], outputManager); + } + this.extraTags = runnerExtraTags; + this.extraReceivers = receivers; + this.hasLargeFanOut = false; + } + } + + @Override + @SuppressWarnings({"unchecked", "ReferenceEquality"}) + public OutputReceiver get(TupleTag tag) { + if (tag == null || tag == mainTag || tag == altMainTag) { + return (OutputReceiver) mainReceiver; + } + DirectOutputReceiver onlyExtra = this.singleExtraReceiver; + if (onlyExtra != null && (tag == singleExtraTag || tag == altSingleExtraTag)) { + return (OutputReceiver) onlyExtra; + } + TupleTag @Nullable [] tags = this.extraTags; + DirectOutputReceiver @Nullable [] receivers = this.extraReceivers; + if (tags != null && receivers != null) { + for (int i = 0; i < tags.length; i++) { + if (tags[i] == tag) { + return (OutputReceiver) receivers[i]; + } + } + TupleTag @Nullable [] aliases = this.extraTagAliases; + if (aliases != null) { + for (int i = 0; i < aliases.length; i++) { + if (aliases[i] == tag) { + return (OutputReceiver) receivers[i]; + } + } + } + } + return getSlowPath(tag); + } + + @SuppressWarnings("unchecked") + private OutputReceiver getSlowPath(TupleTag tag) { + if (hasLargeFanOut) { + Map, DirectOutputReceiver> map = this.lazyExtraReceivers; + if (map != null) { + DirectOutputReceiver cached = map.get(tag); + if (cached != null) { + return (OutputReceiver) cached; + } + } + } + if (Objects.equals(mainTag, tag)) { + altMainTag = tag; + return (OutputReceiver) mainReceiver; + } + DirectOutputReceiver onlyExtra = this.singleExtraReceiver; + if (onlyExtra != null && Objects.equals(singleExtraTag, tag)) { + altSingleExtraTag = tag; + return (OutputReceiver) onlyExtra; + } + TupleTag @Nullable [] tags = this.extraTags; + DirectOutputReceiver @Nullable [] receivers = this.extraReceivers; + if (tags != null && receivers != null) { + for (int i = 0; i < tags.length; i++) { + if (Objects.equals(tags[i], tag)) { + TupleTag @Nullable [] aliases = this.extraTagAliases; + if (aliases == null) { + aliases = new TupleTag[tags.length]; + this.extraTagAliases = aliases; + } + aliases[i] = tag; + return (OutputReceiver) receivers[i]; + } + } + } else if (hasLargeFanOut && outputTags.contains(tag)) { + Map, DirectOutputReceiver> map = this.lazyExtraReceivers; + if (map == null) { + map = new HashMap<>(); + this.lazyExtraReceivers = map; + } + DirectOutputReceiver created = new DirectOutputReceiver<>(tag, outputManager); + map.put(tag, created); + return created; + } + return DoFnOutputReceivers.windowedReceiver( + DoFnProcessContext.this, DoFnProcessContext.this, tag); + } + + @Override + @SuppressWarnings({"unchecked", "ReferenceEquality"}) + public OutputReceiver getRowReceiver(TupleTag tag) { + Map, Coder> coders = checkNotNull(outputCoders); + if (tag == mainTag && mainOutputSchemaCoder != null) { + return outputRowReceiver(fn); + } + Map, OutputReceiver> cache = this.rowReceivers; + if (cache != null) { + OutputReceiver cached = cache.get(tag); + if (cached != null) { + return cached; + } + } + Coder outputCoder = (Coder) coders.get(tag); + checkStateNotNull(outputCoder, "No output tag for %s ", tag); + Preconditions.checkState( + outputCoder instanceof SchemaCoder, + "Output with tag %s must have a schema in order to call getRowReceiver", + tag); + OutputReceiver receiver = + DoFnOutputReceivers.rowReceiver( + DoFnProcessContext.this, + DoFnProcessContext.this, + tag, + (SchemaCoder) outputCoder); + if (cache == null) { + cache = new HashMap<>(4); + this.rowReceivers = cache; + } + cache.put(tag, receiver); + return receiver; + } } @Override @@ -1599,7 +2005,7 @@ private void setAndVerifyOutputTimestamp() { Instant timestampToValidate = outputTimestamp; Instant lowerBound; try { - lowerBound = elementInputTimestamp.minus(fn.getAllowedTimestampSkew()); + lowerBound = elementInputTimestamp.minus(allowedTimestampSkew); } catch (ArithmeticException e) { lowerBound = BoundedWindow.TIMESTAMP_MIN_VALUE; } @@ -1614,9 +2020,9 @@ private void setAndVerifyOutputTimestamp() { + "allowed skew.", timestampToValidate, elementInputTimestamp, - fn.getAllowedTimestampSkew().getMillis() >= Integer.MAX_VALUE - ? fn.getAllowedTimestampSkew() - : PeriodFormat.getDefault().print(fn.getAllowedTimestampSkew().toPeriod()), + allowedTimestampSkewMillis >= Integer.MAX_VALUE + ? allowedTimestampSkew + : PeriodFormat.getDefault().print(allowedTimestampSkew.toPeriod()), BoundedWindow.TIMESTAMP_MAX_VALUE)); } } else if (!noOutputTimestamp && TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) { diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java index 49c9277314bc..7955f0407b45 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java @@ -23,36 +23,60 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isA; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.beam.runners.core.TimerInternals.TimerData; import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.StringUtf8Coder; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.SchemaCoder; +import org.apache.beam.sdk.state.StateSpec; +import org.apache.beam.sdk.state.StateSpecs; import org.apache.beam.sdk.state.TimeDomain; import org.apache.beam.sdk.state.Timer; import org.apache.beam.sdk.state.TimerSpec; import org.apache.beam.sdk.state.TimerSpecs; +import org.apache.beam.sdk.state.ValueState; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.DoFnSchemaInformation; import org.apache.beam.sdk.transforms.reflect.DoFnSignature.TimerDeclaration; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.FixedWindows; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.GlobalWindows; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.transforms.windowing.PaneInfo.Timing; import org.apache.beam.sdk.transforms.windowing.WindowFn; import org.apache.beam.sdk.util.UserCodeException; import org.apache.beam.sdk.util.WindowedValueMultiReceiver; import org.apache.beam.sdk.values.CausedByDrain; import org.apache.beam.sdk.values.KV; +import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.ValueKind; import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; import org.apache.beam.sdk.values.WindowingStrategy; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ArrayListMultimap; +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ListMultimap; import org.joda.time.Duration; import org.joda.time.Instant; @@ -797,6 +821,767 @@ public Duration getAllowedTimestampSkew() { } } + @Test + @SuppressWarnings("unchecked") + public void testReentrantProcessElementPreservesOuterContextAndMetadata() { + TupleTag mainTag = new TupleTag<>("main"); + IntervalWindow outerWin = + new IntervalWindow(Instant.ofEpochMilli(100), Instant.ofEpochMilli(200)); + IntervalWindow innerWin = + new IntervalWindow(Instant.ofEpochMilli(500), Instant.ofEpochMilli(600)); + PaneInfo outerPane = PaneInfo.createPane(true, false, Timing.EARLY, 1, 0); + PaneInfo innerPane = PaneInfo.createPane(false, true, Timing.LATE, 2, 1); + WindowedValue outerElem = + WindowedValues.of( + "outer", + Instant.ofEpochMilli(150), + outerWin, + outerPane, + "outer-rec", + 11L, + CausedByDrain.NORMAL, + null, + ValueKind.INSERT); + WindowedValue innerElem = + WindowedValues.of( + "inner", + Instant.ofEpochMilli(550), + innerWin, + innerPane, + "inner-rec", + 22L, + CausedByDrain.CAUSED_BY_DRAIN, + null, + ValueKind.DELETE); + + List> observed = new ArrayList<>(); + List.ProcessContext> capturedContexts = new ArrayList<>(); + DoFn echoDoFn = + new DoFn() { + @ProcessElement + public void processElement( + ProcessContext c, BoundedWindow window, OutputReceiver out) { + capturedContexts.add(c); + String before = "before:" + c.element() + "@" + c.timestamp().getMillis(); + out.output(before); + // Verify ProcessContext still sees its own element/window/metadata after reentry. + assertEquals(c.element().equals("outer") ? outerWin : innerWin, window); + String after = "after:" + c.element() + "@" + c.timestamp().getMillis(); + out.output(after); + } + }; + + final DoFnRunner[] runnerRef = new DoFnRunner[1]; + WindowedValueMultiReceiver reentrantOutputManager = + new WindowedValueMultiReceiver() { + @Override + public void output(TupleTag tag, WindowedValue output) { + WindowedValue wv = (WindowedValue) output; + observed.add(wv); + if ("before:outer@150".equals(wv.getValue())) { + runnerRef[0].processElement(innerElem); + } + } + }; + + runnerRef[0] = + new SimpleDoFnRunner<>( + null, + echoDoFn, + NullSideInputReader.empty(), + reentrantOutputManager, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.of(FixedWindows.of(Duration.millis(100))), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + + runnerRef[0].startBundle(); + runnerRef[0].processElement(outerElem); + runnerRef[0].finishBundle(); + + assertEquals(4, observed.size()); + assertEquals("before:outer@150", observed.get(0).getValue()); + assertEquals(Instant.ofEpochMilli(150), observed.get(0).getTimestamp()); + assertThat(observed.get(0).getWindows(), contains(outerWin)); + assertEquals(outerPane, observed.get(0).getPaneInfo()); + assertEquals("outer-rec", observed.get(0).getRecordId()); + assertEquals(Long.valueOf(11L), observed.get(0).getRecordOffset()); + assertEquals(CausedByDrain.NORMAL, observed.get(0).causedByDrain()); + assertEquals(ValueKind.INSERT, observed.get(0).getValueKind()); + + assertEquals("before:inner@550", observed.get(1).getValue()); + assertEquals(Instant.ofEpochMilli(550), observed.get(1).getTimestamp()); + assertThat(observed.get(1).getWindows(), contains(innerWin)); + assertEquals(innerPane, observed.get(1).getPaneInfo()); + assertEquals("inner-rec", observed.get(1).getRecordId()); + assertEquals(Long.valueOf(22L), observed.get(1).getRecordOffset()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, observed.get(1).causedByDrain()); + assertEquals(ValueKind.DELETE, observed.get(1).getValueKind()); + + assertEquals("after:inner@550", observed.get(2).getValue()); + assertEquals("after:outer@150", observed.get(3).getValue()); + assertEquals(Instant.ofEpochMilli(150), observed.get(3).getTimestamp()); + assertThat(observed.get(3).getWindows(), contains(outerWin)); + assertEquals(outerPane, observed.get(3).getPaneInfo()); + assertEquals("outer-rec", observed.get(3).getRecordId()); + assertEquals(Long.valueOf(11L), observed.get(3).getRecordOffset()); + assertEquals(CausedByDrain.NORMAL, observed.get(3).causedByDrain()); + assertEquals(ValueKind.INSERT, observed.get(3).getValueKind()); + + // Both primary AND reentrant fallback contexts must fail fast once @ProcessElement exits. + assertEquals(2, capturedContexts.size()); + for (DoFn.ProcessContext ctx : capturedContexts) { + assertThrows(IllegalStateException.class, ctx::element); + } + + // Reentrant inner exception swallowed inside outputManager still leaves outer context intact. + DoFn throwOnInnerFn = + new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + if ("boom".equals(c.element())) { + throw new IllegalStateException("inner boom"); + } + c.output("pre:" + c.element()); + c.output("post:" + c.element()); + } + }; + List afterThrow = new ArrayList<>(); + final DoFnRunner[] runner2 = new DoFnRunner[1]; + runner2[0] = + new SimpleDoFnRunner<>( + null, + throwOnInnerFn, + NullSideInputReader.empty(), + new WindowedValueMultiReceiver() { + @Override + public void output(TupleTag tag, WindowedValue out) { + String v = (String) out.getValue(); + afterThrow.add(v); + if ("pre:outer".equals(v)) { + assertThrows( + UserCodeException.class, + () -> runner2[0].processElement(WindowedValues.valueInGlobalWindow("boom"))); + } + } + }, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + runner2[0].processElement(WindowedValues.valueInGlobalWindow("outer")); + assertThat(afterThrow, contains("pre:outer", "post:outer")); + // And after an outer exception, reusable context is cleanly reset for subsequent elements. + assertThrows( + UserCodeException.class, + () -> runner2[0].processElement(WindowedValues.valueInGlobalWindow("boom"))); + afterThrow.clear(); + runner2[0].processElement(WindowedValues.valueInGlobalWindow("ok")); + assertThat(afterThrow, contains("pre:ok", "post:ok")); + } + + @Test + @SuppressWarnings("unchecked") + public void testMultiOutputReceiverBoundariesDuplicatesAndNonIdenticalTag() { + TupleTag mainTag = new TupleTag<>("main"); + TupleTag mainCopy = new TupleTag<>("main"); + TupleTag unknownTag = new TupleTag<>("unknown"); + + // Verify 0, 1, 2, 8, and 9 extra tags (crossing MAX_INLINE_EXTRA_TAGS = 8 boundary), plus + // duplicate mainTag and duplicate side tag inside additionalOutputTags. + for (int extraCount : new int[] {0, 1, 2, 8, 9}) { + List> extraTags = new ArrayList<>(); + List> extraCopies = new ArrayList<>(); + for (int i = 0; i < extraCount; i++) { + extraTags.add(new TupleTag("side-" + i)); + extraCopies.add(new TupleTag<>("side-" + i)); + } + List> withDuplicates = new ArrayList<>(extraTags); + withDuplicates.add(mainTag); // duplicate main tag (like FlinkDoFnFunction) + if (!extraTags.isEmpty()) { + withDuplicates.add(extraTags.get(0)); + } + + ListOutputManager manager = new ListOutputManager(); + DoFn multiDoFn = + new DoFn() { + @ProcessElement + public void processElement(@Element String elem, MultiOutputReceiver out) { + out.get(mainTag).output(elem + ":main"); + out.get(mainCopy).output(elem + ":mainCopy"); + // Passing null routes to mainOutputTag, matching DoFnOutputReceivers / FnApi. + out.get((TupleTag) null).output(elem + ":nullToMain"); + for (int i = 0; i < extraTags.size(); i++) { + TupleTag exact = (TupleTag) extraTags.get(i); + TupleTag copy = extraCopies.get(i); + out.get(exact).output(elem + ":s" + i); + out.get(copy).output(elem + ":s" + i + "c"); + } + assertThrows(IllegalArgumentException.class, () -> out.get(unknownTag).output("bad")); + } + }; + + DoFnRunner runner = + new SimpleDoFnRunner<>( + null, + multiDoFn, + NullSideInputReader.empty(), + manager, + mainTag, + withDuplicates, + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + runner.startBundle(); + // Process two sequential elements to hit both initial alias population and cached fast path. + runner.processElement(WindowedValues.valueInGlobalWindow("e1")); + runner.processElement(WindowedValues.valueInGlobalWindow("e2")); + runner.finishBundle(); + + assertThat( + manager.outputs.get(mainTag), + contains( + WindowedValues.valueInGlobalWindow("e1:main"), + WindowedValues.valueInGlobalWindow("e1:mainCopy"), + WindowedValues.valueInGlobalWindow("e1:nullToMain"), + WindowedValues.valueInGlobalWindow("e2:main"), + WindowedValues.valueInGlobalWindow("e2:mainCopy"), + WindowedValues.valueInGlobalWindow("e2:nullToMain"))); + for (int i = 0; i < extraTags.size(); i++) { + assertThat( + manager.outputs.get(extraTags.get(i)), + contains( + WindowedValues.valueInGlobalWindow("e1:s" + i), + WindowedValues.valueInGlobalWindow("e1:s" + i + "c"), + WindowedValues.valueInGlobalWindow("e2:s" + i), + WindowedValues.valueInGlobalWindow("e2:s" + i + "c"))); + } + } + } + + @Test + public void testNullTagValidationBeforeAndAfterSideOutput() { + TupleTag mainTag = new TupleTag<>("main"); + TupleTag side1 = new TupleTag<>("side1"); + TupleTag side2 = new TupleTag<>("side2"); + ListOutputManager manager = new ListOutputManager(); + + DoFn fn = + new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + // Null tag passed to outputWindowedValue BEFORE any valid side output must throw IAE. + assertThrows( + IllegalArgumentException.class, + () -> c.outputWindowedValue(null, WindowedValues.valueInGlobalWindow("bad"))); + assertThrows( + IllegalArgumentException.class, + () -> + c.outputWindowedValue( + null, + "bad", + BoundedWindow.TIMESTAMP_MIN_VALUE, + Collections.singletonList(GlobalWindow.INSTANCE), + PaneInfo.NO_FIRING)); + // Alternating valid side outputs (both exact and equal copies). + c.output(side1, "s1"); + c.output(side2, "s2"); + c.output(new TupleTag<>("side1"), "s1copy"); + // Null tag AFTER valid side outputs must also throw IAE. + assertThrows( + IllegalArgumentException.class, + () -> c.outputWindowedValue(null, WindowedValues.valueInGlobalWindow("bad2"))); + } + + @FinishBundle + public void finishBundle(FinishBundleContext c) { + assertThrows( + IllegalArgumentException.class, + () -> + c.output( + null, "bad", BoundedWindow.TIMESTAMP_MIN_VALUE, GlobalWindow.INSTANCE)); + } + }; + + DoFnRunner runner = + new SimpleDoFnRunner<>( + null, + fn, + NullSideInputReader.empty(), + manager, + mainTag, + Arrays.asList(side1, side2), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + runner.startBundle(); + runner.processElement(WindowedValues.valueInGlobalWindow("x")); + runner.finishBundle(); + assertEquals(2, manager.outputs.get(side1).size()); + assertEquals(1, manager.outputs.get(side2).size()); + } + + @Test + @SuppressWarnings("unchecked") + public void testNullMainOutputTagAndNullAdditionalOutputTagSafety() { + TupleTag side0 = new TupleTag<>("side-0"); + TupleTag unknown = new TupleTag<>("unknown"); + + // ProcessContext.output(v) with null mainOutputTag must throw NPE (wrapped in + // UserCodeException). + DoFn mainOutFn = + new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + c.output("x"); + } + }; + DoFnRunner nullMainRunner = + new SimpleDoFnRunner<>( + null, + mainOutFn, + NullSideInputReader.empty(), + new ListOutputManager(), + null, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + UserCodeException uce = + assertThrows( + UserCodeException.class, + () -> nullMainRunner.processElement(WindowedValues.valueInGlobalWindow("in"))); + assertThat(uce.getCause(), isA(NullPointerException.class)); + + // CachedMultiOutputReceiver with mainOutputTag == null across 0, 1, 2, and 9 extra tags. + for (int extraCount : new int[] {0, 1, 2, 9}) { + List> extras = new ArrayList<>(); + for (int i = 0; i < extraCount; i++) { + extras.add(new TupleTag("side-" + i)); + } + ListOutputManager mgr = new ListOutputManager(); + DoFn multiFn = + new DoFn() { + @ProcessElement + public void processElement(MultiOutputReceiver out) { + if (extraCount > 0) { + out.get(side0).output("ok"); + } + assertThrows( + IllegalArgumentException.class, () -> out.get(unknown).output("unknown")); + } + }; + DoFnRunner r = + new SimpleDoFnRunner<>( + null, + multiFn, + NullSideInputReader.empty(), + mgr, + null, + extras, + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + r.processElement(WindowedValues.valueInGlobalWindow("in")); + if (extraCount > 0) { + assertEquals(1, mgr.outputs.get(side0).size()); + } + } + + // additionalOutputTags containing a null tag with non-null mainOutputTag must not NPE on + // slow-path lookup, and out.get(null) must still route to mainOutputTag. + TupleTag mainTag = new TupleTag<>("main"); + ListOutputManager mgr = new ListOutputManager(); + DoFn nullExtraFn = + new DoFn() { + @ProcessElement + public void processElement(MultiOutputReceiver out) { + out.get((TupleTag) null).output("routed-to-main"); + assertThrows(IllegalArgumentException.class, () -> out.get(unknown).output("bad")); + } + }; + DoFnRunner r = + new SimpleDoFnRunner<>( + null, + nullExtraFn, + NullSideInputReader.empty(), + mgr, + mainTag, + Arrays.asList(null, side0), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + r.processElement(WindowedValues.valueInGlobalWindow("in")); + assertThat( + mgr.outputs.get(mainTag), contains(WindowedValues.valueInGlobalWindow("routed-to-main"))); + } + + @Test + @SuppressWarnings("unchecked") + public void testRowReceiversAndDirectOutputReceiverOverloads() { + Schema schema = Schema.builder().addStringField("s").build(); + SchemaCoder schemaCoder = SchemaCoder.of(schema); + TupleTag mainTag = new TupleTag<>("main"); + TupleTag sideTag = new TupleTag<>("side"); + TupleTag nonSchemaTag = new TupleTag<>("plain"); + Map, Coder> coders = new HashMap<>(); + coders.put(mainTag, schemaCoder); + coders.put(sideTag, schemaCoder); + coders.put(nonSchemaTag, StringUtf8Coder.of()); + + List> mainRowRefs = new ArrayList<>(); + List> sideRowRefs = new ArrayList<>(); + DoFn rowFn = + new DoFn() { + @ProcessElement + public void processElement( + @Element String elem, OutputReceiver mainOut, MultiOutputReceiver multiOut) { + Row row = Row.withSchema(schema).addValue(elem).build(); + mainOut.output(row); + DoFn.OutputReceiver mr = multiOut.getRowReceiver(mainTag); + DoFn.OutputReceiver sr = multiOut.getRowReceiver(sideTag); + mainRowRefs.add(mr); + sideRowRefs.add(sr); + sr.output(row); + assertThrows(IllegalStateException.class, () -> multiOut.getRowReceiver(nonSchemaTag)); + assertThrows( + IllegalStateException.class, + () -> multiOut.getRowReceiver(new TupleTag("missing"))); + } + }; + ListOutputManager manager = new ListOutputManager(); + DoFnRunner runner = + new SimpleDoFnRunner<>( + null, + rowFn, + NullSideInputReader.empty(), + manager, + mainTag, + Arrays.asList(sideTag, nonSchemaTag), + mockStepContext, + null, + coders, + WindowingStrategy.of(FixedWindows.of(Duration.standardSeconds(10))), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + IntervalWindow w1 = new IntervalWindow(Instant.ofEpochMilli(0), Instant.ofEpochMilli(10_000)); + IntervalWindow w2 = + new IntervalWindow(Instant.ofEpochMilli(10_000), Instant.ofEpochMilli(20_000)); + runner.processElement( + WindowedValues.of("a", Instant.ofEpochMilli(100), w1, PaneInfo.NO_FIRING)); + runner.processElement( + WindowedValues.of("b", Instant.ofEpochMilli(10_100), w2, PaneInfo.NO_FIRING)); + assertSame(mainRowRefs.get(0), mainRowRefs.get(1)); + assertSame(sideRowRefs.get(0), sideRowRefs.get(1)); + assertEquals(2, manager.outputs.get(mainTag).size()); + assertEquals(2, manager.outputs.get(sideTag).size()); + assertEquals(Instant.ofEpochMilli(100), manager.outputs.get(sideTag).get(0).getTimestamp()); + assertEquals(Instant.ofEpochMilli(10_100), manager.outputs.get(sideTag).get(1).getTimestamp()); + + // DirectOutputReceiver outputWithTimestamp, 4-arg and 5-arg outputWindowedValue, builder(). + TupleTag strTag = new TupleTag<>("str"); + ListOutputManager strMgr = new ListOutputManager(); + PaneInfo earlyPane = PaneInfo.createPane(true, false, Timing.EARLY); + DoFn overloadFn = + new DoFn() { + @ProcessElement + public void processElement(@Element String elem, OutputReceiver out) { + out.outputWithTimestamp(elem + ":ts", Instant.ofEpochMilli(200)); + out.outputWindowedValue( + elem + ":w4", Instant.ofEpochMilli(300), Collections.singletonList(w1), earlyPane); + out.outputWindowedValue( + elem + ":w5", + Instant.ofEpochMilli(400), + Collections.singletonList(w2), + earlyPane, + ValueKind.DELETE); + out.builder(elem + ":bld").setTimestamp(Instant.ofEpochMilli(500)).output(); + } + }; + DoFnRunner strRunner = + new SimpleDoFnRunner<>( + null, + overloadFn, + NullSideInputReader.empty(), + strMgr, + strTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.of(FixedWindows.of(Duration.standardSeconds(10))), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + strRunner.processElement( + WindowedValues.of("v", Instant.ofEpochMilli(100), w1, PaneInfo.NO_FIRING)); + List> outs = strMgr.outputs.get(strTag); + assertEquals(4, outs.size()); + assertEquals("v:ts", outs.get(0).getValue()); + assertEquals(Instant.ofEpochMilli(200), outs.get(0).getTimestamp()); + assertEquals("v:w4", outs.get(1).getValue()); + assertEquals(earlyPane, outs.get(1).getPaneInfo()); + assertEquals("v:w5", outs.get(2).getValue()); + assertEquals(ValueKind.DELETE, outs.get(2).getValueKind()); + assertThat(outs.get(2).getWindows(), contains(w2)); + assertEquals("v:bld", outs.get(3).getValue()); + assertEquals(Instant.ofEpochMilli(500), outs.get(3).getTimestamp()); + } + + @Test + public void testCheckTimestampSkewBoundaryEdgeCases() { + TupleTag mainTag = new TupleTag<>("main"); + + // skew = Long.MAX_VALUE with elemMillis = -1 (no overflow) and -2 (overflow -> MIN_VALUE). + DoFn maxSkewFn = + new DoFn() { + @Override + @SuppressWarnings("deprecation") + public Duration getAllowedTimestampSkew() { + return Duration.millis(Long.MAX_VALUE); + } + + @ProcessElement + public void processElement(OutputReceiver out) { + out.outputWithTimestamp("min", BoundedWindow.TIMESTAMP_MIN_VALUE); + } + }; + ListOutputManager mgr = new ListOutputManager(); + DoFnRunner maxSkewRunner = + new SimpleDoFnRunner<>( + null, + maxSkewFn, + NullSideInputReader.empty(), + mgr, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + maxSkewRunner.processElement( + WindowedValues.timestampedValueInGlobalWindow("a", Instant.ofEpochMilli(-1))); + maxSkewRunner.processElement( + WindowedValues.timestampedValueInGlobalWindow("b", Instant.ofEpochMilli(-2))); + assertEquals(2, mgr.outputs.get(mainTag).size()); + + // Negative allowedTimestampSkew must reject same-timestamp DirectOutputReceiver.output(v). + DoFn negSkewFn = + new DoFn() { + @Override + @SuppressWarnings("deprecation") + public Duration getAllowedTimestampSkew() { + return Duration.millis(-10); + } + + @ProcessElement + public void processElement(OutputReceiver out) { + out.output("should-fail"); + } + }; + DoFnRunner negRunner = + new SimpleDoFnRunner<>( + null, + negSkewFn, + NullSideInputReader.empty(), + new ListOutputManager(), + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + UserCodeException negEx = + assertThrows( + UserCodeException.class, + () -> + negRunner.processElement( + WindowedValues.timestampedValueInGlobalWindow("x", Instant.ofEpochMilli(100)))); + assertThat(negEx.getCause(), isA(IllegalArgumentException.class)); + + // Timestamp past TIMESTAMP_MAX_VALUE rejected by output() on DirectOutputReceiver. + DoFn normalFn = + new DoFn() { + @ProcessElement + public void processElement(OutputReceiver out) { + out.output("past-max"); + } + }; + DoFnRunner normalRunner = + new SimpleDoFnRunner<>( + null, + normalFn, + NullSideInputReader.empty(), + new ListOutputManager(), + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + Instant tooLate = BoundedWindow.TIMESTAMP_MAX_VALUE.plus(Duration.millis(1)); + UserCodeException maxEx = + assertThrows( + UserCodeException.class, + () -> + normalRunner.processElement( + WindowedValues.timestampedValueInGlobalWindow("x", tooLate))); + assertThat(maxEx.getCause(), isA(IllegalArgumentException.class)); + } + + @Test + @SuppressWarnings("unchecked") + public void testExplodedWindowsResetStateNamespaceAndOpenTelemetryScope() { + TupleTag mainTag = new TupleTag<>("main"); + InMemoryStateInternals stateInternals = InMemoryStateInternals.forKey("k"); + when(mockStepContext.stateInternals()).thenReturn((StateInternals) stateInternals); + + DoFn statefulFn = + new DoFn() { + @StateId("s") + private final StateSpec> spec = StateSpecs.value(StringUtf8Coder.of()); + + @ProcessElement + public void processElement( + @Element String elem, + BoundedWindow window, + @StateId("s") ValueState state, + OutputReceiver out) { + String prev = state.read(); + String label = prev == null ? elem : prev + "+" + elem; + state.write(label); + out.output(window.maxTimestamp().getMillis() + ":" + label); + } + }; + ListOutputManager mgr = new ListOutputManager(); + DoFnRunner runner = + new SimpleDoFnRunner<>( + null, + statefulFn, + NullSideInputReader.empty(), + mgr, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + ImmutableMap.of(), + WindowingStrategy.of(FixedWindows.of(Duration.millis(10))), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + + IntervalWindow w1 = new IntervalWindow(Instant.ofEpochMilli(0), Instant.ofEpochMilli(10)); + IntervalWindow w2 = new IntervalWindow(Instant.ofEpochMilli(10), Instant.ofEpochMilli(20)); + // Multi-window element explodes across w1 and w2 with independent state namespaces. + runner.processElement( + WindowedValues.of("a", Instant.ofEpochMilli(5), Arrays.asList(w1, w2), PaneInfo.NO_FIRING)); + // Subsequent single-window element hits singleWindowOrNull fast path. + runner.processElement(WindowedValues.of("b", Instant.ofEpochMilli(6), w1, PaneInfo.NO_FIRING)); + + List> outs = mgr.outputs.get(mainTag); + assertEquals(3, outs.size()); + assertEquals("9:a", outs.get(0).getValue()); + assertEquals("19:a", outs.get(1).getValue()); + assertEquals("9:a+b", outs.get(2).getValue()); + + // OpenTelemetry context switching: null, same current context, and distinct span context. + Context ctxA = + Context.root() + .with( + Span.wrap( + SpanContext.create( + "aa000000000000000000000000000001", + "aa00000000000001", + TraceFlags.getSampled(), + TraceState.getDefault()))); + Context ctxB = + Context.root() + .with( + Span.wrap( + SpanContext.create( + "bb000000000000000000000000000002", + "bb00000000000002", + TraceFlags.getSampled(), + TraceState.getDefault()))); + List seenContexts = new ArrayList<>(); + DoFn otelFn = + new DoFn() { + @ProcessElement + public void processElement(OutputReceiver out) { + seenContexts.add(Context.current()); + out.output("ok"); + } + }; + DoFnRunner otelRunner = + new SimpleDoFnRunner<>( + null, + otelFn, + NullSideInputReader.empty(), + new ListOutputManager(), + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.globalDefault(), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + try (Scope s = ctxA.makeCurrent()) { + otelRunner.processElement( + WindowedValues.of( + "same", + BoundedWindow.TIMESTAMP_MIN_VALUE, + GlobalWindow.INSTANCE, + PaneInfo.NO_FIRING, + null, + null, + CausedByDrain.NORMAL, + ctxA, + ValueKind.INSERT)); + otelRunner.processElement( + WindowedValues.of( + "switch", + BoundedWindow.TIMESTAMP_MIN_VALUE, + GlobalWindow.INSTANCE, + PaneInfo.NO_FIRING, + null, + null, + CausedByDrain.NORMAL, + ctxB, + ValueKind.INSERT)); + assertSame(ctxA, Context.current()); + } + assertSame(ctxA, seenContexts.get(0)); + assertSame(ctxB, seenContexts.get(1)); + } + private static class ListOutputManager implements WindowedValueMultiReceiver { private final ListMultimap, WindowedValue> outputs = ArrayListMultimap.create(); diff --git a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java new file mode 100644 index 000000000000..be51ce71c6ea --- /dev/null +++ b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java @@ -0,0 +1,175 @@ +/* + * 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.sdk.jmh.transforms; + +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.transforms.DoFn.OutputReceiver; +import org.apache.beam.sdk.transforms.DoFnOutputReceivers; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.util.OutputBuilderSupplier; +import org.apache.beam.sdk.util.OutputBuilderSuppliers; +import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.WindowedValue; +import org.apache.beam.sdk.values.WindowedValues; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.infra.Blackhole; + +/** + * Microbenchmarks for {@link DoFnOutputReceivers}, {@link WindowedValues}, and {@link PaneInfo} + * per-element hot paths. + */ +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +public class OutputReceiverBenchmark { + + private static final class NoopDoFn extends DoFn {} + + @State(Scope.Thread) + public static class ReceiverState { + final PipelineOptions options = PipelineOptionsFactory.create(); + final DoFn doFn = new NoopDoFn(); + final TupleTag mainTag = new TupleTag<>("main"); + final Instant ts = new Instant(1_700_000_000_000L); + final Instant outTs = new Instant(1_700_000_001_000L); + final IntervalWindow window = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + final WindowedValue elem = + WindowedValues.of("input-element", ts, window, PaneInfo.NO_FIRING); + final OutputBuilderSupplier builderSupplier = OutputBuilderSuppliers.supplierForElement(elem); + + DoFn.WindowedContext context; + OutputReceiver cachedReceiver; + WindowedValue lastOutput; + + @Setup + public void setUp() { + context = + doFn.new WindowedContext() { + @Override + public PipelineOptions getPipelineOptions() { + return options; + } + + @Override + public void output(String output) { + lastOutput = elem.withValue(output); + } + + @Override + public void outputWithTimestamp(String output, Instant timestamp) { + lastOutput = + WindowedValues.of( + output, + timestamp, + elem.getWindows(), + elem.getPaneInfo(), + elem.getRecordId(), + elem.getRecordOffset(), + elem.causedByDrain(), + elem.getOpenTelemetryContext(), + elem.getValueKind()); + } + + @Override + public void outputWindowedValue( + String output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + lastOutput = WindowedValues.of(output, timestamp, windows, paneInfo); + } + + @Override + public void outputWindowedValue(WindowedValue windowedValue) { + lastOutput = windowedValue; + } + + @Override + public void output(TupleTag tag, T output) { + lastOutput = elem.withValue(output); + } + + @Override + public void outputWithTimestamp(TupleTag tag, T output, Instant timestamp) { + lastOutput = + WindowedValues.of( + output, + timestamp, + elem.getWindows(), + elem.getPaneInfo(), + elem.getRecordId(), + elem.getRecordOffset(), + elem.causedByDrain(), + elem.getOpenTelemetryContext(), + elem.getValueKind()); + } + + @Override + public void outputWindowedValue( + TupleTag tag, + T output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + lastOutput = WindowedValues.of(output, timestamp, windows, paneInfo); + } + + @Override + public void outputWindowedValue(TupleTag tag, WindowedValue windowedValue) { + lastOutput = windowedValue; + } + }; + cachedReceiver = DoFnOutputReceivers.windowedReceiver(context, builderSupplier, mainTag); + } + } + + @Benchmark + public void windowedReceiverOutput(ReceiverState s, Blackhole bh) { + s.cachedReceiver.output("output-element"); + bh.consume(s.lastOutput); + } + + @Benchmark + public void windowedReceiverOutputWithTimestamp(ReceiverState s, Blackhole bh) { + s.cachedReceiver.outputWithTimestamp("output-element", s.outTs); + bh.consume(s.lastOutput); + } + + @Benchmark + public Collection singleWindowGetWindows(ReceiverState s) { + return s.elem.getWindows(); + } + + @Benchmark + public PaneInfo paneInfoWithElementMetadataNoChange() { + return PaneInfo.NO_FIRING.withElementMetadata(false); + } +} diff --git a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/package-info.java b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/package-info.java new file mode 100644 index 000000000000..a5c44bdab6c5 --- /dev/null +++ b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/package-info.java @@ -0,0 +1,20 @@ +/* + * 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. + */ + +/** Benchmarks for core SDK transform classes. */ +package org.apache.beam.sdk.jmh.transforms; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java index 37850a9fcf84..c02a196b9397 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java @@ -33,8 +33,8 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.WindowedValue; -import org.apache.beam.sdk.values.WindowedValues; import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Instant; /** Common {@link OutputReceiver} and {@link MultiOutputReceiver} classes. */ @Internal @@ -57,6 +57,28 @@ private RowOutputReceiver( this.schemaCoder = schemaCoder; } + @Override + public void output(Row output) { + T converted = schemaCoder.getFromRowFunction().apply(output); + WindowedValue windowedValue = builderSupplier.build(converted); + if (tag == null) { + ((DoFn.WindowedContext) context).outputWindowedValue(windowedValue); + } else { + context.outputWindowedValue(tag, windowedValue); + } + } + + @Override + public void outputWithTimestamp(Row output, Instant timestamp) { + T converted = schemaCoder.getFromRowFunction().apply(output); + WindowedValue windowedValue = builderSupplier.buildWithTimestamp(converted, timestamp); + if (tag == null) { + ((DoFn.WindowedContext) context).outputWindowedValue(windowedValue); + } else { + context.outputWindowedValue(tag, windowedValue); + } + } + @Override public OutputBuilder builder(Row value) { // assigning to final variable allows static analysis to know it @@ -65,7 +87,6 @@ public OutputBuilder builder(Row value) { if (tag == null) { return builderSupplier .builder(value) - .setValue(value) .setReceiver( rowWithMetadata -> { ((DoFn.WindowedContext) context) @@ -108,9 +129,19 @@ public WindowedContextOutputReceiver( this.outputTag = outputTag; } + @Override + public void output(T output) { + output(builderSupplier.build(output)); + } + + @Override + public void outputWithTimestamp(T output, Instant timestamp) { + output(builderSupplier.buildWithTimestamp(output, timestamp)); + } + @Override public OutputBuilder builder(T value) { - return WindowedValues.builder(builderSupplier.builder(value)).setReceiver(this); + return builderSupplier.builder(value).setReceiver(this); } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java index cee7fc5f607d..87afa3a9006d 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java @@ -18,7 +18,9 @@ package org.apache.beam.sdk.util; import org.apache.beam.sdk.annotations.Internal; +import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; +import org.joda.time.Instant; @Internal @FunctionalInterface @@ -26,4 +28,17 @@ public interface OutputBuilderSupplier { // Returns WindowedValues.Builder so that downstream can setReceiver (when tag is specified) // but we need the value at a minimum in order to fix the type variable WindowedValues.Builder builder(OutputT value); + + /** Builds a {@link WindowedValue} for {@code value} using the supplier's template metadata. */ + default WindowedValue build(OutputT value) { + return builder(value).build(); + } + + /** + * Builds a {@link WindowedValue} for {@code value} with the given {@code timestamp} using the + * supplier's template metadata. + */ + default WindowedValue buildWithTimestamp(OutputT value, Instant timestamp) { + return builder(value).setTimestamp(timestamp).build(); + } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java index e766982e295b..c7a357aea43a 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java @@ -20,6 +20,7 @@ import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; +import org.joda.time.Instant; /** Implementations of {@link OutputBuilderSupplier}. */ @Internal @@ -30,7 +31,17 @@ public static OutputBuilderSupplier supplierForElement(WindowedValue template return new OutputBuilderSupplier() { @Override public WindowedValues.Builder builder(T value) { - return WindowedValues.builder(templateValue).withValue(value); + return WindowedValues.builder(templateValue, value); + } + + @Override + public WindowedValue build(T value) { + return WindowedValues.ofWithCurrentContext(templateValue, value); + } + + @Override + public WindowedValue buildWithTimestamp(T value, Instant timestamp) { + return WindowedValues.ofWithCurrentContext(templateValue, value, timestamp); } }; } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java index 9ac8979cae37..c7c213cb2e23 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java @@ -25,11 +25,13 @@ import io.opentelemetry.context.Context; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -49,6 +51,7 @@ import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.PaneInfo; import org.apache.beam.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; +import org.apache.beam.sdk.util.VarInt; import org.apache.beam.sdk.util.WindowedValueReceiver; import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.MoreObjects; @@ -73,17 +76,24 @@ public static Builder builder() { return new Builder<>(); } - /** Create a Builder that takes element metadata from the provideed delegate. */ + /** Create a Builder that takes element metadata from the provided delegate. */ public static Builder builder(WindowedValue template) { + return builder(template, template.getValue()); + } + + /** + * Create a Builder that takes element metadata from the provided delegate with a new element + * value. + */ + public static Builder builder(WindowedValue template, T value) { return new Builder() - .setValue(template.getValue()) + .setValue(value) .setTimestamp(template.getTimestamp()) .setWindows(template.getWindows()) .setPaneInfo(template.getPaneInfo()) .setRecordOffset(template.getRecordOffset()) .setRecordId(template.getRecordId()) .setCausedByDrain(template.causedByDrain()) - .setOpenTelemetryContext(template.getOpenTelemetryContext()) .setValueKind(template.getValueKind()); } @@ -136,7 +146,7 @@ public Builder setPaneInfo(PaneInfo paneInfo) { @Override public Builder setWindow(BoundedWindow window) { - return setWindows(Collections.singleton(window)); + return setWindows(Collections.singletonList(window)); } @Override @@ -200,7 +210,7 @@ public Instant getTimestamp() { public @Nullable Context getOpenTelemetryContext() { // builder may have different context set at the beginning of parDo // when building WindowedValue we should take current context from storage. - return Context.current(); + return currentOpenTelemetryContextOrNull(); } @Override @@ -321,10 +331,14 @@ public static WindowedValue of( checkArgument(causedByDrain != null, "WindowedValue requires CausedByDrain, but it was null"); checkArgument(valueKind != null, "WindowedValue requires ValueKind, but it was null"); if (windows.size() == 1) { + BoundedWindow window = + windows instanceof List + ? ((List) windows).get(0) + : windows.iterator().next(); return of( value, timestamp, - windows.iterator().next(), + window, paneInfo, currentRecordId, currentRecordOffset, @@ -345,6 +359,140 @@ public static WindowedValue of( } } + private static final Context ROOT_OTEL_CONTEXT = Context.root(); + private static final long MIN_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); + + @SuppressWarnings("ReferenceEquality") + private static boolean isMinTimestamp(Instant timestamp) { + return timestamp == BoundedWindow.TIMESTAMP_MIN_VALUE + || (timestamp != null && timestamp.getMillis() == MIN_TIMESTAMP_MILLIS); + } + + private static @Nullable Context currentOpenTelemetryContextOrNull() { + Context current = Context.current(); + return current == ROOT_OTEL_CONTEXT ? null : current; + } + + /** + * Returns the single {@link BoundedWindow} associated with {@code value} without allocating a + * wrapper collection, or {@code null} if {@code value} holds zero or multiple windows. + * + *

Dispatches via the {@link SimpleWindowedValue} abstract superclass on the common path + * (HotSpot primary-super check) rather than {@code instanceof SingleWindowedValue} to avoid + * {@code _secondary_super_cache} contention (JDK-8180450) across concurrent worker threads when + * interleaved with {@code WindowedValue} interface casts. + */ + @Internal + public static @Nullable BoundedWindow singleWindowOrNull(WindowedValue value) { + if (value instanceof SimpleWindowedValue) { + return ((SimpleWindowedValue) value).singleWindowOrNull(); + } + if (value instanceof SingleWindowedValue) { + return ((SingleWindowedValue) value).getWindow(); + } + return null; + } + + /** + * Returns a {@code WindowedValue} copying metadata from {@code template} with a new {@code value} + * and capturing the current OpenTelemetry {@link Context}. + */ + public static WindowedValue ofWithCurrentContext(WindowedValue template, T value) { + Context otelContext = currentOpenTelemetryContextOrNull(); + if (template instanceof SimpleWindowedValue) { + SimpleWindowedValue simple = (SimpleWindowedValue) template; + return simple.withValueAndContext(value, otelContext); + } + return ofWithCurrentContextFallback(template, value, template.getTimestamp(), otelContext); + } + + /** + * Returns a {@code WindowedValue} copying metadata from {@code template} with a new {@code value} + * and {@code timestamp}, capturing the current OpenTelemetry {@link Context}. + */ + public static WindowedValue ofWithCurrentContext( + WindowedValue template, T value, Instant timestamp) { + Context otelContext = currentOpenTelemetryContextOrNull(); + if (template instanceof SimpleWindowedValue) { + SimpleWindowedValue simple = (SimpleWindowedValue) template; + return simple.withValueAndTimestampAndContext(value, timestamp, otelContext); + } + return ofWithCurrentContextFallback(template, value, timestamp, otelContext); + } + + private static WindowedValue ofWithCurrentContextFallback( + WindowedValue template, T value, Instant timestamp, @Nullable Context otelContext) { + if (template instanceof SingleWindowedValue) { + return of( + value, + timestamp, + ((SingleWindowedValue) template).getWindow(), + template.getPaneInfo(), + template.getRecordId(), + template.getRecordOffset(), + template.causedByDrain(), + otelContext, + template.getValueKind()); + } + return of( + value, + timestamp, + template.getWindows(), + template.getPaneInfo(), + template.getRecordId(), + template.getRecordOffset(), + template.causedByDrain(), + otelContext, + template.getValueKind()); + } + + /** + * Returns a {@code WindowedValue} copying non-windowed metadata from {@code template} with the + * specified {@code value}, {@code timestamp}, {@code windows}, and {@code paneInfo}, capturing + * the current OpenTelemetry {@link Context}. + */ + public static WindowedValue ofWithCurrentContext( + WindowedValue template, + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + return of( + value, + timestamp, + windows, + paneInfo, + template.getRecordId(), + template.getRecordOffset(), + template.causedByDrain(), + currentOpenTelemetryContextOrNull(), + template.getValueKind()); + } + + /** + * Returns a {@code WindowedValue} copying non-windowed metadata from {@code template} with the + * specified {@code value}, {@code timestamp}, {@code windows}, {@code paneInfo}, and {@code + * valueKind}, capturing the current OpenTelemetry {@link Context}. + */ + public static WindowedValue ofWithCurrentContext( + WindowedValue template, + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + return of( + value, + timestamp, + windows, + paneInfo, + template.getRecordId(), + template.getRecordOffset(), + template.causedByDrain(), + currentOpenTelemetryContextOrNull(), + valueKind); + } + /** * @deprecated for use only in compatibility with old broken code */ @@ -358,10 +506,14 @@ static WindowedValue createWithoutValidation( @Nullable Context openTelemetryContext, ValueKind valueKind) { if (windows.size() == 1) { + BoundedWindow window = + windows instanceof List + ? ((List) windows).get(0) + : windows.iterator().next(); return of( value, timestamp, - windows.iterator().next(), + window, paneInfo, null, null, @@ -413,8 +565,8 @@ public static WindowedValue of( checkArgument(causedByDrain != null, "WindowedValue requires CausedByDrain, but it was null"); checkArgument(valueKind != null, "WindowedValue requires ValueKind, but it was null"); - boolean isGlobal = GlobalWindow.INSTANCE.equals(window); - if (isGlobal && BoundedWindow.TIMESTAMP_MIN_VALUE.equals(timestamp)) { + boolean isGlobal = window == GlobalWindow.INSTANCE || GlobalWindow.INSTANCE.equals(window); + if (isGlobal && isMinTimestamp(timestamp)) { return new ValueInGlobalWindow<>( value, paneInfo, @@ -645,6 +797,16 @@ public boolean equals(@Nullable Object other) { return WindowedValues.equals(this, (WindowedValue) other); } + @Nullable BoundedWindow singleWindowOrNull() { + return null; + } + + abstract WindowedValue withValueAndContext( + NewT newValue, @Nullable Context newContext); + + abstract WindowedValue withValueAndTimestampAndContext( + NewT newValue, Instant newTimestamp, @Nullable Context newContext); + @Override public int hashCode() { return WindowedValues.hashCode(this); @@ -672,7 +834,7 @@ public Instant getTimestamp() { } /** The representation of a WindowedValue where timestamp == MIN and windows == {GlobalWindow}. */ - private static class ValueInGlobalWindow extends MinTimestampWindowedValue + private static final class ValueInGlobalWindow extends MinTimestampWindowedValue implements SingleWindowedValue { public ValueInGlobalWindow( @@ -697,6 +859,11 @@ public BoundedWindow getWindow() { return GlobalWindow.INSTANCE; } + @Override + BoundedWindow singleWindowOrNull() { + return GlobalWindow.INSTANCE; + } + @Override public WindowedValue withValue(NewT newValue) { return new ValueInGlobalWindow<>( @@ -709,6 +876,42 @@ public WindowedValue withValue(NewT newValue) { getValueKind()); } + @Override + WindowedValue withValueAndContext(NewT newValue, @Nullable Context newContext) { + return new ValueInGlobalWindow<>( + newValue, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + + @Override + WindowedValue withValueAndTimestampAndContext( + NewT newValue, Instant newTimestamp, @Nullable Context newContext) { + if (isMinTimestamp(newTimestamp)) { + return new ValueInGlobalWindow<>( + newValue, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + return new TimestampedValueInGlobalWindow<>( + newValue, + newTimestamp, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + @Override public boolean equals(@Nullable Object o) { if (o instanceof ValueInGlobalWindow) { @@ -763,7 +966,7 @@ public Instant getTimestamp() { * The representation of a WindowedValue where timestamp {@code >} MIN and windows == * {GlobalWindow}. */ - private static class TimestampedValueInGlobalWindow extends TimestampedWindowedValue + private static final class TimestampedValueInGlobalWindow extends TimestampedWindowedValue implements SingleWindowedValue { public TimestampedValueInGlobalWindow( @@ -796,6 +999,11 @@ public BoundedWindow getWindow() { return GlobalWindow.INSTANCE; } + @Override + BoundedWindow singleWindowOrNull() { + return GlobalWindow.INSTANCE; + } + @Override public WindowedValue withValue(NewT newValue) { return new TimestampedValueInGlobalWindow<>( @@ -809,6 +1017,43 @@ public WindowedValue withValue(NewT newValue) { getValueKind()); } + @Override + WindowedValue withValueAndContext(NewT newValue, @Nullable Context newContext) { + return new TimestampedValueInGlobalWindow<>( + newValue, + getTimestamp(), + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + + @Override + WindowedValue withValueAndTimestampAndContext( + NewT newValue, Instant newTimestamp, @Nullable Context newContext) { + if (isMinTimestamp(newTimestamp)) { + return new ValueInGlobalWindow<>( + newValue, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + return new TimestampedValueInGlobalWindow<>( + newValue, + newTimestamp, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + @Override public boolean equals(@Nullable Object o) { if (o instanceof TimestampedValueInGlobalWindow) { @@ -845,10 +1090,11 @@ public String toString() { * The representation of a WindowedValue where timestamp is arbitrary and windows == a single * non-Global window. */ - private static class TimestampedValueInSingleWindow extends TimestampedWindowedValue + private static final class TimestampedValueInSingleWindow extends TimestampedWindowedValue implements SingleWindowedValue { private final BoundedWindow window; + private transient @MonotonicNonNull Collection windows; public TimestampedValueInSingleWindow( T value, @@ -886,9 +1132,43 @@ public WindowedValue withValue(NewT newValue) { getValueKind()); } + @Override + WindowedValue withValueAndContext(NewT newValue, @Nullable Context newContext) { + return new TimestampedValueInSingleWindow<>( + newValue, + getTimestamp(), + window, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + + @Override + WindowedValue withValueAndTimestampAndContext( + NewT newValue, Instant newTimestamp, @Nullable Context newContext) { + return new TimestampedValueInSingleWindow<>( + newValue, + newTimestamp, + window, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + @Override public Collection getWindows() { - return Collections.singletonList(window); + Collection result = windows; + if (result == null) { + result = Collections.singletonList(window); + windows = result; + } + return result; } @Override @@ -896,6 +1176,11 @@ public BoundedWindow getWindow() { return window; } + @Override + BoundedWindow singleWindowOrNull() { + return window; + } + @Override public boolean equals(@Nullable Object o) { if (o instanceof TimestampedValueInSingleWindow) { @@ -931,7 +1216,8 @@ public String toString() { } /** The representation of a WindowedValue, excluding the special cases captured above. */ - private static class TimestampedValueInMultipleWindows extends TimestampedWindowedValue { + private static final class TimestampedValueInMultipleWindows + extends TimestampedWindowedValue { private Collection windows; public TimestampedValueInMultipleWindows( @@ -975,6 +1261,38 @@ public WindowedValue withValue(NewT newValue) { getValueKind()); } + @Override + WindowedValue withValueAndContext(NewT newValue, @Nullable Context newContext) { + return withValueAndTimestampAndContext(newValue, getTimestamp(), newContext); + } + + @Override + WindowedValue withValueAndTimestampAndContext( + NewT newValue, Instant newTimestamp, @Nullable Context newContext) { + if (windows.size() > 1) { + return new TimestampedValueInMultipleWindows<>( + newValue, + newTimestamp, + windows, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + return of( + newValue, + newTimestamp, + windows, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + newContext, + getValueKind()); + } + @Override @SuppressWarnings("UndefinedEquals") public boolean equals(@Nullable Object o) { @@ -1114,6 +1432,39 @@ public WindowedValueCoder withValueCoder(Coder valueCoder) { return new FullWindowedValueCoder<>(valueCoder, windowCoder); } + private static final byte[] SINGLE_WINDOW_COUNT_BYTES = new byte[] {0, 0, 0, 1}; + + private static int readBigEndianInt(InputStream in) throws IOException { + int b1 = in.read(); + int b2 = in.read(); + int b3 = in.read(); + int b4 = in.read(); + if ((b1 | b2 | b3 | b4) < 0) { + throw new EOFException(); + } + return ((b1 & 0xFF) << 24) | ((b2 & 0xFF) << 16) | ((b3 & 0xFF) << 8) | (b4 & 0xFF); + } + + private Collection decodeUnknownSizeWindows(InputStream inStream) + throws IOException { + List elements = new ArrayList<>(); + long count = VarInt.decodeLong(inStream); + while (count > 0L) { + elements.add(windowCoder.decode(inStream)); + --count; + if (count == 0L) { + count = VarInt.decodeLong(inStream); + } + } + if (count == 0L) { + return elements; + } + throw new IllegalStateException( + String.format( + "Collection does not support non zero terminator values. Received stream with terminator %s.", + count)); + } + @Override public void encode(WindowedValue windowedElem, OutputStream outStream) throws CoderException, IOException { @@ -1124,7 +1475,15 @@ public void encode(WindowedValue windowedElem, OutputStream outStream) public void encode(WindowedValue windowedElem, OutputStream outStream, Coder.Context context) throws CoderException, IOException { InstantCoder.of().encode(windowedElem.getTimestamp(), outStream); - windowsCoder.encode(windowedElem.getWindows(), outStream); + @Nullable BoundedWindow singleWindow = singleWindowOrNull(windowedElem); + if (singleWindow != null) { + outStream.write(SINGLE_WINDOW_COUNT_BYTES, 0, 4); + @SuppressWarnings("unchecked") + Coder typedWindowCoder = (Coder) windowCoder; + typedWindowCoder.encode(singleWindow, outStream); + } else { + windowsCoder.encode(windowedElem.getWindows(), outStream); + } boolean metadataSupported = isMetadataSupported(); PaneInfoCoder.INSTANCE.encode( windowedElem.getPaneInfo().withElementMetadata(metadataSupported), outStream); @@ -1159,7 +1518,22 @@ public WindowedValue decode(InputStream inStream) throws CoderException, IOEx public WindowedValue decode(InputStream inStream, Coder.Context context) throws CoderException, IOException { Instant timestamp = InstantCoder.of().decode(inStream); - Collection windows = windowsCoder.decode(inStream); + int numWindows = readBigEndianInt(inStream); + @Nullable BoundedWindow singleWindow = null; + @Nullable Collection windows = null; + if (numWindows == 1) { + singleWindow = checkNotNull(windowCoder.decode(inStream), "WindowedValue window is null"); + } else if (numWindows == 0) { + windows = Collections.emptyList(); + } else if (numWindows > 1) { + List windowList = new ArrayList<>(numWindows); + for (int i = 0; i < numWindows; i++) { + windowList.add(windowCoder.decode(inStream)); + } + windows = windowList; + } else { + windows = decodeUnknownSizeWindows(inStream); + } PaneInfo paneInfo = PaneInfoCoder.INSTANCE.decode(inStream); CausedByDrain causedByDrain = CausedByDrain.NORMAL; io.opentelemetry.context.Context openTelemetryContext = null; @@ -1176,10 +1550,28 @@ public WindowedValue decode(InputStream inStream, Coder.Context context) } T value = valueCoder.decode(inStream, context); + if (singleWindow != null) { + return WindowedValues.of( + value, + timestamp, + singleWindow, + paneInfo, + null, + null, + causedByDrain, + openTelemetryContext, + valueKind); + } // Because there are some remaining (incorrect) uses of WindowedValue with no windows, // we call this deprecated no-validation path when decoding return WindowedValues.createWithoutValidation( - value, timestamp, windows, paneInfo, causedByDrain, openTelemetryContext, valueKind); + value, + timestamp, + checkStateNotNull(windows), + paneInfo, + causedByDrain, + openTelemetryContext, + valueKind); } @Override @@ -1194,7 +1586,15 @@ public void verifyDeterministic() throws NonDeterministicException { public void registerByteSizeObserver(WindowedValue value, ElementByteSizeObserver observer) throws Exception { InstantCoder.of().registerByteSizeObserver(value.getTimestamp(), observer); - windowsCoder.registerByteSizeObserver(value.getWindows(), observer); + @Nullable BoundedWindow singleWindow = singleWindowOrNull(value); + if (singleWindow != null) { + observer.update(4L); + @SuppressWarnings("unchecked") + Coder typedWindowCoder = (Coder) windowCoder; + typedWindowCoder.registerByteSizeObserver(singleWindow, observer); + } else { + windowsCoder.registerByteSizeObserver(value.getWindows(), observer); + } PaneInfoCoder.INSTANCE.registerByteSizeObserver(value.getPaneInfo(), observer); valueCoder.registerByteSizeObserver(value.getValue(), observer); } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java index ce603f41516d..989fb272c6be 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java @@ -28,16 +28,23 @@ import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.util.Arrays; +import java.util.Collections; 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.StringUtf8Coder; import org.apache.beam.sdk.testing.CoderProperties; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; import org.apache.beam.sdk.transforms.windowing.PaneInfo.Timing; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.sdk.values.CausedByDrain; import org.apache.beam.sdk.values.ValueKind; import org.apache.beam.sdk.values.WindowedValue; @@ -244,4 +251,191 @@ public void testSingleWindowedValueInFixedWindow() { assertThat(value, instanceOf(WindowedValues.SingleWindowedValue.class)); assertThat(((WindowedValues.SingleWindowedValue) value).getWindow(), equalTo(w)); } + + @Test + public void testFullWindowedValueCoderSingleMultiZeroAndChunkedWindows() throws Exception { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); + + // Single IntervalWindow round-trip + byte size observer check. + WindowedValue single = WindowedValues.of("hello", ts, w1, PaneInfo.NO_FIRING); + byte[] singleBytes = CoderUtils.encodeToByteArray(intervalCoder, single); + WindowedValue decodedSingle = + CoderUtils.decodeFromByteArray(intervalCoder, singleBytes); + assertThat(decodedSingle, equalTo(single)); + assertThat(decodedSingle, instanceOf(WindowedValues.SingleWindowedValue.class)); + Assert.assertEquals( + CoderUtils.encodeToByteArray(intervalCoder, single, Coder.Context.NESTED).length, + measureByteSize(intervalCoder, single)); + + // Multiple windows round-trip + byte size observer check. + WindowedValue multi = + WindowedValues.of("world", ts, Arrays.asList(w1, w2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + byte[] multiBytes = CoderUtils.encodeToByteArray(intervalCoder, multi); + WindowedValue decodedMulti = CoderUtils.decodeFromByteArray(intervalCoder, multiBytes); + assertThat(decodedMulti, equalTo(multi)); + Assert.assertEquals( + CoderUtils.encodeToByteArray(intervalCoder, multi, Coder.Context.NESTED).length, + measureByteSize(intervalCoder, multi)); + + // Single GlobalWindow round-trip + byte size observer check. + Coder> globalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE); + WindowedValue globalVal = WindowedValues.valueInGlobalWindow("g"); + byte[] globalBytes = CoderUtils.encodeToByteArray(globalCoder, globalVal); + WindowedValue decodedGlobal = CoderUtils.decodeFromByteArray(globalCoder, globalBytes); + assertThat(decodedGlobal, equalTo(globalVal)); + Assert.assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, decodedGlobal.getTimestamp()); + Assert.assertEquals( + CoderUtils.encodeToByteArray(globalCoder, globalVal, Coder.Context.NESTED).length, + measureByteSize(globalCoder, globalVal)); + + // Zero windows stream (compatibility with legacy no-window encoding). + ByteArrayOutputStream zeroWinOut = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, zeroWinOut); + zeroWinOut.write(new byte[] {0, 0, 0, 0}); // numWindows == 0 + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, zeroWinOut); + StringUtf8Coder.of().encode("empty", zeroWinOut); + WindowedValue decodedZero = + intervalCoder.decode(new ByteArrayInputStream(zeroWinOut.toByteArray())); + assertThat(decodedZero.getValue(), equalTo("empty")); + assertThat(decodedZero.getWindows(), equalTo(Collections.emptyList())); + + // Unknown-size chunked windows stream (-1 prefix, VarInt count=2, terminator=0). + ByteArrayOutputStream chunkedOut = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, chunkedOut); + chunkedOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + VarInt.encode(2L, chunkedOut); + IntervalWindow.getCoder().encode(w1, chunkedOut); + IntervalWindow.getCoder().encode(w2, chunkedOut); + VarInt.encode(0L, chunkedOut); + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, chunkedOut); + StringUtf8Coder.of().encode("chunked", chunkedOut); + WindowedValue decodedChunked = + intervalCoder.decode(new ByteArrayInputStream(chunkedOut.toByteArray())); + assertThat(decodedChunked.getValue(), equalTo("chunked")); + assertThat(decodedChunked.getWindows(), containsInAnyOrder(w1, w2)); + + // Non-zero negative terminator in unknown-size stream throws IllegalStateException. + ByteArrayOutputStream badTermOut = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, badTermOut); + badTermOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + VarInt.encode(-2L, badTermOut); + Assert.assertThrows( + IllegalStateException.class, + () -> intervalCoder.decode(new ByteArrayInputStream(badTermOut.toByteArray()))); + + // Truncated IntervalWindowCoder stream throws CoderException. + byte[] encodedInterval = CoderUtils.encodeToByteArray(IntervalWindow.getCoder(), w1); + byte[] truncated = Arrays.copyOf(encodedInterval, 8); // timestamp only, missing duration + Assert.assertThrows( + CoderException.class, + () -> CoderUtils.decodeFromByteArray(IntervalWindow.getCoder(), truncated)); + } + + @Test + public void testOfWithCurrentContextOmitsRootAndPreservesActiveContext() { + WindowedValue template = WindowedValues.valueInGlobalWindow("in"); + try (Scope rootScope = Context.root().makeCurrent()) { + WindowedValue derived = WindowedValues.ofWithCurrentContext(template, "out"); + Assert.assertNull(derived.getOpenTelemetryContext()); + WindowedValue built = + WindowedValues.builder() + .setValue("b") + .setTimestamp(BoundedWindow.TIMESTAMP_MIN_VALUE) + .setWindow(GlobalWindow.INSTANCE) + .setPaneInfo(PaneInfo.NO_FIRING) + .build(); + Assert.assertNull(built.getOpenTelemetryContext()); + } + + Context activeContext = + Context.root() + .with( + Span.wrap( + SpanContext.create( + "ff000000000000000000000000000041", + "ff00000000000041", + TraceFlags.getSampled(), + TraceState.getDefault()))); + try (Scope activeScope = activeContext.makeCurrent()) { + WindowedValue derived = WindowedValues.ofWithCurrentContext(template, "out"); + Assert.assertSame(activeContext, derived.getOpenTelemetryContext()); + } + } + + @Test + public void testSingleWindowOrNullAndOfWithCurrentContextFastPaths() { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); + PaneInfo early = PaneInfo.createPane(true, false, Timing.EARLY, 3, 1); + + // ValueInGlobalWindow + WindowedValue gMin = WindowedValues.valueInGlobalWindow("g0"); + Assert.assertEquals(GlobalWindow.INSTANCE, WindowedValues.singleWindowOrNull(gMin)); + WindowedValue gMinDerived = WindowedValues.ofWithCurrentContext(gMin, "g1", ts); + Assert.assertEquals(ts, gMinDerived.getTimestamp()); + Assert.assertEquals(GlobalWindow.INSTANCE, WindowedValues.singleWindowOrNull(gMinDerived)); + WindowedValue gMinBackToMin = + WindowedValues.ofWithCurrentContext(gMinDerived, "g2", BoundedWindow.TIMESTAMP_MIN_VALUE); + Assert.assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, gMinBackToMin.getTimestamp()); + + // TimestampedValueInSingleWindow with full metadata + WindowedValue single = + WindowedValues.of( + "s0", ts, w1, early, "rid", 42L, CausedByDrain.CAUSED_BY_DRAIN, null, ValueKind.DELETE); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(single)); + WindowedValue singleCopy = WindowedValues.ofWithCurrentContext(single, "s1"); + Assert.assertEquals("s1", singleCopy.getValue()); + Assert.assertEquals(ts, singleCopy.getTimestamp()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(singleCopy)); + Assert.assertEquals(early, singleCopy.getPaneInfo()); + Assert.assertEquals("rid", singleCopy.getRecordId()); + Assert.assertEquals(Long.valueOf(42L), singleCopy.getRecordOffset()); + Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, singleCopy.causedByDrain()); + Assert.assertEquals(ValueKind.DELETE, singleCopy.getValueKind()); + + // TimestampedValueInMultipleWindows + WindowedValue multi = WindowedValues.of("m0", ts, Arrays.asList(w1, w2), early); + Assert.assertNull(WindowedValues.singleWindowOrNull(multi)); + WindowedValue multiDerived = WindowedValues.ofWithCurrentContext(multi, "m1"); + Assert.assertEquals("m1", multiDerived.getValue()); + assertThat(multiDerived.getWindows(), containsInAnyOrder(w1, w2)); + + // 6-arg ofWithCurrentContext with ValueKind override + WindowedValue kindOverride = + WindowedValues.ofWithCurrentContext( + single, + "k", + ts.plus(Duration.millis(10)), + Collections.singletonList(w2), + early, + ValueKind.UPDATE_AFTER); + Assert.assertEquals(ValueKind.UPDATE_AFTER, kindOverride.getValueKind()); + Assert.assertEquals(w2, WindowedValues.singleWindowOrNull(kindOverride)); + Assert.assertEquals("rid", kindOverride.getRecordId()); + Assert.assertEquals(Long.valueOf(42L), kindOverride.getRecordOffset()); + } + + private static long measureByteSize(Coder coder, T value) throws Exception { + final long[] total = new long[1]; + ElementByteSizeObserver observer = + new ElementByteSizeObserver() { + @Override + protected void reportElementSize(long elementByteSize) { + total[0] += elementByteSize; + } + }; + coder.registerByteSizeObserver(value, observer); + observer.advance(); + return total[0]; + } } diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java index edc647788388..da613ac3ce51 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java @@ -1871,8 +1871,7 @@ private class NonWindowObservingProcessBundleContext @Override public OutputBuilder builder(OutputT value) { - return WindowedValues.builder(currentElement) - .withValue(value) + return WindowedValues.builder(currentElement, value) .setReceiver( windowedValue -> { checkTimestamp(windowedValue.getTimestamp()); @@ -1903,7 +1902,10 @@ public void output(TupleTag tag, T output) { @Override public void outputWithTimestamp(OutputT output, Instant timestamp) { - builder(output).setValue(output).setTimestamp(timestamp).output(); + checkTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext(currentElement, output, timestamp)); } @Override @@ -1912,7 +1914,11 @@ public void outputWindowedValue( Instant timestamp, Collection windows, PaneInfo paneInfo) { - builder(output).setTimestamp(timestamp).setWindows(windows).setPaneInfo(paneInfo).output(); + checkTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + currentElement, output, timestamp, windows, paneInfo)); } @Override @@ -2105,10 +2111,23 @@ public void output(OutputT output) { private final SerializableFunction fromRowFunction = mainOutputSchemaCoder.getFromRowFunction(); + @Override + public void output(Row value) { + ProcessBundleContextBase.this.outputWindowedValue( + WindowedValues.ofWithCurrentContext( + currentElement, fromRowFunction.apply(value))); + } + + @Override + public void outputWithTimestamp(Row value, Instant timestamp) { + ProcessBundleContextBase.this.outputWindowedValue( + WindowedValues.ofWithCurrentContext( + currentElement, fromRowFunction.apply(value), timestamp)); + } + @Override public OutputBuilder builder(Row value) { - return WindowedValues.builder(currentElement) - .withValue(value) + return WindowedValues.builder(currentElement, value) .setReceiver( windowedRow -> ProcessBundleContextBase.this.outputWindowedValue( @@ -2140,10 +2159,21 @@ private OutputReceiver createTaggedOutputReceiver(TupleTag tag) { return (OutputReceiver) ProcessBundleContextBase.this; } return new OutputReceiver() { + @Override + public void output(T value) { + ProcessBundleContextBase.this.outputWindowedValue( + tag, WindowedValues.ofWithCurrentContext(currentElement, value)); + } + + @Override + public void outputWithTimestamp(T value, Instant timestamp) { + ProcessBundleContextBase.this.outputWindowedValue( + tag, WindowedValues.ofWithCurrentContext(currentElement, value, timestamp)); + } + @Override public OutputBuilder builder(T value) { - return WindowedValues.builder(currentElement) - .withValue(value) + return WindowedValues.builder(currentElement, value) .setReceiver( windowedValue -> ProcessBundleContextBase.this.outputWindowedValue(tag, windowedValue)); @@ -2173,10 +2203,25 @@ private OutputReceiver createTaggedRowReceiver(TupleTag tag) { private SerializableFunction fromRowFunction = ((SchemaCoder) outputCoder).getFromRowFunction(); + @Override + public void output(Row value) { + ProcessBundleContextBase.this.outputWindowedValue( + tag, + WindowedValues.ofWithCurrentContext( + currentElement, fromRowFunction.apply(value))); + } + + @Override + public void outputWithTimestamp(Row value, Instant timestamp) { + ProcessBundleContextBase.this.outputWindowedValue( + tag, + WindowedValues.ofWithCurrentContext( + currentElement, fromRowFunction.apply(value), timestamp)); + } + @Override public OutputBuilder builder(Row value) { - return WindowedValues.builder(currentElement) - .withValue(value) + return WindowedValues.builder(currentElement, value) .setReceiver( windowedRow -> ProcessBundleContextBase.this.outputWindowedValue( From 003b5d4221b77fe42b2b9476cf5af49a4a01b419 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Fri, 27 Nov 2026 23:20:06 -0800 Subject: [PATCH 2/4] simplification --- .../beam/runners/core/SimpleDoFnRunner.java | 284 +++---- .../runners/core/SimpleDoFnRunnerTest.java | 408 ++++++---- .../transforms/OutputReceiverBenchmark.java | 439 +++++++++-- .../OutputReceiverBenchmarkTest.java | 81 ++ .../beam/sdk/coders/IterableLikeCoder.java | 111 ++- .../sdk/transforms/DoFnOutputReceivers.java | 117 +-- .../beam/sdk/util/OutputBuilderSupplier.java | 90 ++- .../beam/sdk/util/OutputBuilderSuppliers.java | 76 +- .../util/construction/SplittableParDo.java | 2 +- .../SplittableParDoNaiveBounded.java | 2 +- .../apache/beam/sdk/values/WindowedValue.java | 9 + .../beam/sdk/values/WindowedValues.java | 675 ++++++++++++----- .../beam/sdk/coders/CollectionCoderTest.java | 46 ++ .../transforms/DoFnOutputReceiversTest.java | 375 +++++++++ .../sdk/util/OutputBuilderSuppliersTest.java | 255 +++++++ .../beam/sdk/util/WindowedValueTest.java | 614 ++++++++++++--- .../beam/fn/harness/FnApiDoFnRunner.java | 714 +++++++++++++++--- .../beam/fn/harness/FnApiDoFnRunnerTest.java | 550 ++++++++++++++ 18 files changed, 3985 insertions(+), 863 deletions(-) create mode 100644 sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmarkTest.java create mode 100644 sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/DoFnOutputReceiversTest.java create mode 100644 sdks/java/core/src/test/java/org/apache/beam/sdk/util/OutputBuilderSuppliersTest.java diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java index 3ab08d1d92cf..b0bd3523e973 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java @@ -20,10 +20,11 @@ import static org.apache.beam.sdk.util.Preconditions.checkStateNotNull; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState; import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextStorage; import io.opentelemetry.context.Scope; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -96,7 +97,6 @@ public class SimpleDoFnRunner implements DoFnRunner implements DoFnRunner> outputTags; /** - * Deduplicated non-main output tags in declaration order when {@code 1 <= count <= - * MAX_INLINE_EXTRA_TAGS}; {@code null} for single-output or large fan-out {@code DoFn}s. + * The sole non-main output tag when there is exactly one additional output; {@code null} + * otherwise. */ - final TupleTag @Nullable [] extraOutputTags; + final @Nullable TupleTag singleExtraOutputTag; private final boolean observesWindow; @@ -178,22 +178,20 @@ public SimpleDoFnRunner( this.mainOutputTag = mainOutputTag; if (additionalOutputTags.isEmpty()) { this.outputTags = Collections.singleton(mainOutputTag); - this.extraOutputTags = null; + this.singleExtraOutputTag = null; } else { Set> tags = Sets.newHashSetWithExpectedSize(1 + additionalOutputTags.size()); tags.add(mainOutputTag); - List> orderedExtras = new ArrayList<>(additionalOutputTags.size()); + @Nullable TupleTag onlyExtra = null; + int extraCount = 0; for (TupleTag tag : additionalOutputTags) { if (tags.add(tag)) { - orderedExtras.add(tag); + onlyExtra = tag; + extraCount++; } } this.outputTags = tags; - if (orderedExtras.isEmpty() || orderedExtras.size() > MAX_INLINE_EXTRA_TAGS) { - this.extraOutputTags = null; - } else { - this.extraOutputTags = orderedExtras.toArray(new TupleTag[0]); - } + this.singleExtraOutputTag = (extraCount == 1) ? onlyExtra : null; } this.stepContext = stepContext; @@ -228,18 +226,27 @@ public void startBundle() { @Override public void processElement(WindowedValue compressedElem) { - Context openTelemetryContext = compressedElem.getOpenTelemetryContext(); - if (openTelemetryContext == null || openTelemetryContext == Context.current()) { + @Nullable Context desired = compressedElem.getOpenTelemetryContext(); + @Nullable Context current = ContextStorage.get().current(); + if (desired == current) { + // Fast path covers both (null, null) and identical active contexts with zero Scope + // allocation. processElementInternal(compressedElem); } else { - processElementWithContext(compressedElem, openTelemetryContext); + processElementWithContextChange(compressedElem, desired, current); } } - private void processElementWithContext( - WindowedValue compressedElem, Context openTelemetryContext) { - try (Scope ignore = openTelemetryContext.makeCurrent()) { + private void processElementWithContextChange( + WindowedValue compressedElem, @Nullable Context desired, @Nullable Context current) { + Context root = Context.root(); + Context target = desired != null ? desired : root; + if (current == target || (current == null && target == root)) { processElementInternal(compressedElem); + } else { + try (Scope ignore = target.makeCurrent()) { + processElementInternal(compressedElem); + } } } @@ -281,17 +288,16 @@ private void invokeProcessElement(WindowedValue elem) { if (context == null) { context = initReusableProcessContext(); } - if (context.elem == null) { - context.setElement(elem); - try { - invoker.invokeProcessElement(context); - } catch (Exception e) { - throw wrapUserCodeException(e); - } finally { - context.clearElement(); - } - } else { - invokeProcessElementReentrant(elem); + checkState( + context.elem == null, + "SimpleDoFnRunner.processElement cannot be invoked reentrantly or concurrently"); + context.setElement(elem); + try { + invoker.invokeProcessElement(context); + } catch (Exception e) { + throw wrapUserCodeException(e); + } finally { + context.clearElement(); } } @@ -301,17 +307,6 @@ private DoFnProcessContext initReusableProcessContext() { return context; } - private void invokeProcessElementReentrant(WindowedValue elem) { - DoFnProcessContext reentrantContext = new DoFnProcessContext(elem); - try { - invoker.invokeProcessElement(reentrantContext); - } catch (Exception e) { - throw wrapUserCodeException(e); - } finally { - reentrantContext.clearElement(); - } - } - @Override public void finishBundle() { // This can contain user code. Wrap it in case it throws an exception. @@ -346,21 +341,6 @@ private T sideInput(PCollectionView view, BoundedWindow sideInputWindow) return sideInputReader.get(view, sideInputWindow); } - void checkSameElementTimestamp(Instant elemTimestamp) { - long skewMillis = allowedTimestampSkewMillis; - if (skewMillis == 0L) { - if (elemTimestamp.getMillis() <= MAX_TIMESTAMP_MILLIS) { - return; - } - } else if (skewMillis > 0L) { - long tsMillis = elemTimestamp.getMillis(); - if (tsMillis >= MIN_TIMESTAMP_MILLIS && tsMillis <= MAX_TIMESTAMP_MILLIS) { - return; - } - } - checkTimestampSlowPath(elemTimestamp, elemTimestamp); - } - void checkTimestamp(Instant elemTimestamp, Instant timestamp) { long tsMillis = timestamp.getMillis(); long skewMillis = allowedTimestampSkewMillis; @@ -400,25 +380,15 @@ private void checkTimestampSlowPath(Instant elemTimestamp, Instant timestamp) { @SuppressWarnings("ReferenceEquality") void outputWindowedValue(TupleTag tag, WindowedValue windowedElem) { + // Since many callers call outputWindowedValue(mainOutputTag, value), the reference-eq check + // here + // usually shortcircuits the map lookup. if (tag != mainOutputTag) { - validateSideOutputTag(tag); + checkArgument(outputTags.contains(tag), "Unknown output tag %s", tag); } outputManager.output(tag, windowedElem); } - @SuppressWarnings("ReferenceEquality") - private void validateSideOutputTag(TupleTag tag) { - TupleTag @Nullable [] extraTags = this.extraOutputTags; - if (extraTags != null) { - for (int i = 0; i < extraTags.length; i++) { - if (extraTags[i] == tag) { - return; - } - } - } - checkArgument(outputTags.contains(tag), "Unknown output tag %s", tag); - } - /** An {@link DoFnInvoker.ArgumentProvider} for {@link DoFn.StartBundle @StartBundle}. */ private class DoFnStartBundleArgumentProvider extends DoFnInvoker.BaseArgumentProvider { @@ -510,9 +480,9 @@ public BundleFinalizer bundleFinalizer() { /** * A concrete implementation of {@link DoFn.ProcessContext} used for running a {@link DoFn} over a - * single element. A single instance is reused across non-reentrant {@code @ProcessElement} - * invocations via {@link #setElement(WindowedValue)} / {@link #clearElement()}; callers accessing - * a retained context or receiver after {@code @ProcessElement} returns fail fast with {@link + * single element. A single instance is reused across {@code @ProcessElement} invocations via + * {@link #setElement(WindowedValue)} / {@link #clearElement()}; callers accessing a retained + * context or receiver after {@code @ProcessElement} returns fail fast with {@link * IllegalStateException}. */ private final class DoFnProcessContext extends DoFn.ProcessContext @@ -530,11 +500,6 @@ private final class DoFnProcessContext extends DoFn.ProcessCont fn.super(); } - DoFnProcessContext(WindowedValue elem) { - fn.super(); - this.elem = elem; - } - void setElement(WindowedValue elem) { this.elem = elem; } @@ -564,6 +529,16 @@ private StateNamespace getNamespace() { return namespace; } + private WindowedValue outputValueWithCurrentContext( + WindowedValue template, T output) { + // Preserve ValueInEmptyWindows / legacy zero-window elements (e.g. Dataflow classic batch + // side inputs from GroupingShuffleReader) without triggering non-empty window validation. + return (WindowedValues.singleWindowOrNull(template) == null + && template.getWindows().isEmpty()) + ? template.withValue(output) + : WindowedValues.ofWithCurrentContext(template, output); + } + @Override public WindowedValues.Builder builder(T value) { return WindowedValues.builder(currentElem(), value); @@ -571,7 +546,7 @@ public WindowedValues.Builder builder(T value) { @Override public WindowedValue build(T value) { - return WindowedValues.ofWithCurrentContext(currentElem(), value); + return outputValueWithCurrentContext(currentElem(), value); } @Override @@ -579,6 +554,27 @@ public WindowedValue buildWithTimestamp(T value, Instant timestamp) { return WindowedValues.ofWithCurrentContext(currentElem(), value, timestamp); } + @Override + public WindowedValue buildWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + return WindowedValues.ofWithCurrentContext( + currentElem(), value, timestamp, windows, paneInfo); + } + + @Override + public WindowedValue buildWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + return WindowedValues.ofWithCurrentContext( + currentElem(), value, timestamp, windows, paneInfo, valueKind); + } + @Override public PipelineOptions getPipelineOptions() { return options; @@ -610,7 +606,7 @@ public PaneInfo pane() { @Override public void output(OutputT output) { checkNotNull(mainOutputTag, "Tag passed to output cannot be null"); - outputManager.output(mainOutputTag, currentElem().withValue(output)); + outputManager.output(mainOutputTag, outputValueWithCurrentContext(currentElem(), output)); } @Override @@ -630,7 +626,8 @@ public void outputWindowedValue( @Override public void output(TupleTag tag, T output) { checkNotNull(tag, "Tag passed to output cannot be null"); - SimpleDoFnRunner.this.outputWindowedValue(tag, currentElem().withValue(output)); + SimpleDoFnRunner.this.outputWindowedValue( + tag, outputValueWithCurrentContext(currentElem(), output)); } @Override @@ -849,8 +846,9 @@ private final class DirectOutputReceiver @Override public void output(T output) { WindowedValue current = currentElem(); - checkSameElementTimestamp(current.getTimestamp()); - receiverOutputManager.output(tag, WindowedValues.ofWithCurrentContext(current, output)); + Instant ts = current.getTimestamp(); + checkTimestamp(ts, ts); + receiverOutputManager.output(tag, outputValueWithCurrentContext(current, output)); } @Override @@ -901,123 +899,71 @@ public void output(WindowedValue windowedValue) { } private final class CachedMultiOutputReceiver implements MultiOutputReceiver { - private final @Nullable TupleTag mainTag; + // Note: the tags passed in by the user will probably be different object instances. The point + // of cachedMainTag + // and cachedSingleExtraTag is to cache the object reference so we can do a quick + // reference-equality lookup (for + // DoFns with 1 or 2 outputs). We always fall back to Objects.equals if this doesn't match. + private @Nullable TupleTag cachedMainTag; private final DirectOutputReceiver mainReceiver; - private @Nullable TupleTag altMainTag; - private final @Nullable TupleTag singleExtraTag; + private @Nullable TupleTag cachedSingleExtraTag; private final @Nullable DirectOutputReceiver singleExtraReceiver; - private @Nullable TupleTag altSingleExtraTag; - private final TupleTag @Nullable [] extraTags; - private final DirectOutputReceiver @Nullable [] extraReceivers; - private TupleTag @Nullable [] extraTagAliases; - private final boolean hasLargeFanOut; - private @Nullable Map, DirectOutputReceiver> lazyExtraReceivers; + private @Nullable Map, DirectOutputReceiver> extraReceivers; private @Nullable Map, OutputReceiver> rowReceivers; - @SuppressWarnings("unchecked") CachedMultiOutputReceiver( @Nullable TupleTag mainTag, DirectOutputReceiver mainReceiver) { - this.mainTag = mainTag; + this.cachedMainTag = mainTag; this.mainReceiver = mainReceiver; - TupleTag @Nullable [] runnerExtraTags = extraOutputTags; - if (runnerExtraTags == null) { - this.singleExtraTag = null; - this.singleExtraReceiver = null; - this.extraTags = null; - this.extraReceivers = null; - this.hasLargeFanOut = outputTags.size() - 1 > MAX_INLINE_EXTRA_TAGS; - } else if (runnerExtraTags.length == 1) { - TupleTag onlyExtra = runnerExtraTags[0]; - this.singleExtraTag = onlyExtra; - this.singleExtraReceiver = - new DirectOutputReceiver<>((TupleTag) onlyExtra, outputManager); - this.extraTags = null; - this.extraReceivers = null; - this.hasLargeFanOut = false; + TupleTag onlyExtra = singleExtraOutputTag; + if (onlyExtra != null) { + this.cachedSingleExtraTag = onlyExtra; + this.singleExtraReceiver = newDirectReceiver(onlyExtra); } else { - this.singleExtraTag = null; + this.cachedSingleExtraTag = null; this.singleExtraReceiver = null; - @SuppressWarnings("rawtypes") - DirectOutputReceiver[] receivers = new DirectOutputReceiver[runnerExtraTags.length]; - for (int i = 0; i < runnerExtraTags.length; i++) { - receivers[i] = - new DirectOutputReceiver<>((TupleTag) runnerExtraTags[i], outputManager); - } - this.extraTags = runnerExtraTags; - this.extraReceivers = receivers; - this.hasLargeFanOut = false; } } + private DirectOutputReceiver newDirectReceiver(TupleTag tag) { + return new DirectOutputReceiver<>(tag, outputManager); + } + @Override @SuppressWarnings({"unchecked", "ReferenceEquality"}) public OutputReceiver get(TupleTag tag) { - if (tag == null || tag == mainTag || tag == altMainTag) { + if (tag == null || tag == cachedMainTag) { return (OutputReceiver) mainReceiver; } DirectOutputReceiver onlyExtra = this.singleExtraReceiver; - if (onlyExtra != null && (tag == singleExtraTag || tag == altSingleExtraTag)) { + if (onlyExtra != null && tag == cachedSingleExtraTag) { return (OutputReceiver) onlyExtra; } - TupleTag @Nullable [] tags = this.extraTags; - DirectOutputReceiver @Nullable [] receivers = this.extraReceivers; - if (tags != null && receivers != null) { - for (int i = 0; i < tags.length; i++) { - if (tags[i] == tag) { - return (OutputReceiver) receivers[i]; - } - } - TupleTag @Nullable [] aliases = this.extraTagAliases; - if (aliases != null) { - for (int i = 0; i < aliases.length; i++) { - if (aliases[i] == tag) { - return (OutputReceiver) receivers[i]; - } - } - } - } return getSlowPath(tag); } @SuppressWarnings("unchecked") private OutputReceiver getSlowPath(TupleTag tag) { - if (hasLargeFanOut) { - Map, DirectOutputReceiver> map = this.lazyExtraReceivers; - if (map != null) { - DirectOutputReceiver cached = map.get(tag); - if (cached != null) { - return (OutputReceiver) cached; - } - } - } - if (Objects.equals(mainTag, tag)) { - altMainTag = tag; + if (Objects.equals(cachedMainTag, tag)) { + cachedMainTag = tag; return (OutputReceiver) mainReceiver; } DirectOutputReceiver onlyExtra = this.singleExtraReceiver; - if (onlyExtra != null && Objects.equals(singleExtraTag, tag)) { - altSingleExtraTag = tag; + if (onlyExtra != null && Objects.equals(cachedSingleExtraTag, tag)) { + cachedSingleExtraTag = tag; return (OutputReceiver) onlyExtra; } - TupleTag @Nullable [] tags = this.extraTags; - DirectOutputReceiver @Nullable [] receivers = this.extraReceivers; - if (tags != null && receivers != null) { - for (int i = 0; i < tags.length; i++) { - if (Objects.equals(tags[i], tag)) { - TupleTag @Nullable [] aliases = this.extraTagAliases; - if (aliases == null) { - aliases = new TupleTag[tags.length]; - this.extraTagAliases = aliases; - } - aliases[i] = tag; - return (OutputReceiver) receivers[i]; - } + Map, DirectOutputReceiver> map = this.extraReceivers; + if (map != null) { + DirectOutputReceiver cached = map.get(tag); + if (cached != null) { + return (OutputReceiver) cached; } - } else if (hasLargeFanOut && outputTags.contains(tag)) { - Map, DirectOutputReceiver> map = this.lazyExtraReceivers; + } + if (outputTags.contains(tag)) { if (map == null) { - map = new HashMap<>(); - this.lazyExtraReceivers = map; + map = new HashMap<>(4); + this.extraReceivers = map; } DirectOutputReceiver created = new DirectOutputReceiver<>(tag, outputManager); map.put(tag, created); @@ -1031,7 +977,7 @@ private OutputReceiver getSlowPath(TupleTag tag) { @SuppressWarnings({"unchecked", "ReferenceEquality"}) public OutputReceiver getRowReceiver(TupleTag tag) { Map, Coder> coders = checkNotNull(outputCoders); - if (tag == mainTag && mainOutputSchemaCoder != null) { + if (tag == cachedMainTag && mainOutputSchemaCoder != null) { return outputRowReceiver(fn); } Map, OutputReceiver> cache = this.rowReceivers; diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java index 7955f0407b45..43990b8bd502 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java @@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isA; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.verify; @@ -34,6 +35,7 @@ import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; import io.opentelemetry.context.Scope; import java.util.ArrayList; import java.util.Arrays; @@ -671,6 +673,248 @@ public void testOnTimerNoSkew() { PeriodFormat.getDefault().print(Duration.ZERO.toPeriod()))))); } + @Test + public void testProcessElementIsolatesOpenTelemetryContext() { + ContextKey testKey = ContextKey.named("beam-test-key"); + List observedValues = new ArrayList<>(); + TupleTag mainTag = new TupleTag<>("main"); + ListOutputManager outputManager = new ListOutputManager(); + DoFn recordingFn = + new DoFn() { + @ProcessElement + public void processElement(@Element String elem, OutputReceiver out) { + observedValues.add(Context.current().get(testKey)); + out.output(elem); + } + }; + + DoFnRunner runner = + new SimpleDoFnRunner<>( + null, + recordingFn, + NullSideInputReader.empty(), + outputManager, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.of(new GlobalWindows()), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + + // Build an untraced element under Context.root() -> normalized openTelemetryContext is null. + WindowedValue untraced; + try (Scope ignored = Context.root().makeCurrent()) { + untraced = + WindowedValues.ofWithCurrentContext(WindowedValues.valueInGlobalWindow("in"), "untraced"); + } + assertNull(untraced.getOpenTelemetryContext()); + + Context ambientCtx = Context.root().with(testKey, "ambient"); + Context elemCtx = Context.root().with(testKey, "element"); + WindowedValue traced = + WindowedValues.of( + "traced", + BoundedWindow.TIMESTAMP_MIN_VALUE, + GlobalWindow.INSTANCE, + PaneInfo.NO_FIRING, + null, + null, + CausedByDrain.NORMAL, + elemCtx, + ValueKind.INSERT); + WindowedValue explicitRoot = + WindowedValues.of( + "root", + BoundedWindow.TIMESTAMP_MIN_VALUE, + GlobalWindow.INSTANCE, + PaneInfo.NO_FIRING, + null, + null, + CausedByDrain.NORMAL, + Context.root(), + ValueKind.INSERT); + + // Executing an untraced element while ambientCtx is active must NOT leak ambientCtx. + try (Scope ignored = ambientCtx.makeCurrent()) { + runner.processElement(untraced); + assertSame(ambientCtx, Context.current()); + + runner.processElement(traced); + assertSame(ambientCtx, Context.current()); + + runner.processElement(explicitRoot); + assertSame(ambientCtx, Context.current()); + } + + // Running explicit Context.root() with no attached thread context should also work cleanly. + runner.processElement(explicitRoot); + assertSame(Context.root(), Context.current()); + + assertEquals(4, observedValues.size()); + assertNull(observedValues.get(0)); + assertEquals("element", observedValues.get(1)); + assertNull(observedValues.get(2)); + assertNull(observedValues.get(3)); + + List> emitted = outputManager.outputs.get(mainTag); + assertEquals(4, emitted.size()); + assertNull(emitted.get(0).getOpenTelemetryContext()); + assertSame(elemCtx, emitted.get(1).getOpenTelemetryContext()); + assertNull(emitted.get(2).getOpenTelemetryContext()); + assertNull(emitted.get(3).getOpenTelemetryContext()); + + // ProcessContext.output() must capture a span started inside @ProcessElement even when + // the input element had null openTelemetryContext (consistent with OutputReceiver.output). + Context childCtx = Context.root().with(testKey, "in-dofn-span"); + ListOutputManager legacyOut = new ListOutputManager(); + DoFn spanCreatingFn = + new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + try (Scope ignored = childCtx.makeCurrent()) { + c.output("tagged-" + c.element()); + } + } + }; + DoFnRunner legacyRunner = + new SimpleDoFnRunner<>( + null, + spanCreatingFn, + NullSideInputReader.empty(), + legacyOut, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.of(new GlobalWindows()), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + legacyRunner.processElement(untraced); + assertSame(childCtx, legacyOut.outputs.get(mainTag).get(0).getOpenTelemetryContext()); + } + + @Test + public void testProcessElementOutputPreservesEmptyWindows() throws Exception { + TupleTag mainTag = new TupleTag<>("main"); + ListOutputManager outputManager = new ListOutputManager(); + DoFn doFn = + new DoFn() { + @ProcessElement + public void processElement(ProcessContext c) { + c.output("out:" + c.element()); + } + }; + DoFnRunner runner = + new SimpleDoFnRunner<>( + null, + doFn, + NullSideInputReader.empty(), + outputManager, + mainTag, + Collections.emptyList(), + mockStepContext, + null, + Collections.emptyMap(), + WindowingStrategy.of(new GlobalWindows()), + DoFnSchemaInformation.create(), + Collections.emptyMap()); + + // 1. Custom empty-window WindowedValue (models Dataflow ValueInEmptyWindows). + WindowedValue emptyWrapper = new EmptyWindowedValue<>("v1", new Instant(1000L)); + runner.processElement(emptyWrapper); + + // 2. Legacy zero-window stream decoded via FullWindowedValueCoder. + java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + org.apache.beam.sdk.coders.InstantCoder.of().encode(new Instant(2000L), baos); + baos.write(new byte[] {0, 0, 0, 0}); // numWindows == 0 + org.apache.beam.sdk.transforms.windowing.PaneInfo.PaneInfoCoder.INSTANCE.encode( + PaneInfo.NO_FIRING, baos); + org.apache.beam.sdk.coders.StringUtf8Coder.of().encode("v2", baos); + WindowedValue decodedZero = + WindowedValues.getFullCoder( + org.apache.beam.sdk.coders.StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE) + .decode(new java.io.ByteArrayInputStream(baos.toByteArray())); + Context activeCtx = Context.root().with(ContextKey.named("k"), "active"); + try (Scope ignored = activeCtx.makeCurrent()) { + runner.processElement(decodedZero); + } + + List> emitted = outputManager.outputs.get(mainTag); + assertEquals(2, emitted.size()); + assertEquals("out:v1", emitted.get(0).getValue()); + assertEquals(0, emitted.get(0).getWindows().size()); + assertEquals("out:v2", emitted.get(1).getValue()); + assertEquals(0, emitted.get(1).getWindows().size()); + } + + private static final class EmptyWindowedValue implements WindowedValue { + private final T value; + private final Instant timestamp; + + EmptyWindowedValue(T value, Instant timestamp) { + this.value = value; + this.timestamp = timestamp; + } + + @Override + public T getValue() { + return value; + } + + @Override + public Instant getTimestamp() { + return timestamp; + } + + @Override + public java.util.Collection getWindows() { + return Collections.emptyList(); + } + + @Override + public PaneInfo getPaneInfo() { + return PaneInfo.NO_FIRING; + } + + @Override + public String getRecordId() { + return null; + } + + @Override + public Context getOpenTelemetryContext() { + return null; + } + + @Override + public Long getRecordOffset() { + return null; + } + + @Override + public CausedByDrain causedByDrain() { + return CausedByDrain.NORMAL; + } + + @Override + public ValueKind getValueKind() { + return ValueKind.INSERT; + } + + @Override + public Iterable> explodeWindows() { + return Collections.emptyList(); + } + + @Override + public WindowedValue withValue(OtherT newValue) { + return new EmptyWindowedValue<>(newValue, timestamp); + } + } + static class ThrowingDoFn extends DoFn { final Exception exceptionToThrow = new UnsupportedOperationException("Expected exception"); @@ -823,149 +1067,39 @@ public Duration getAllowedTimestampSkew() { @Test @SuppressWarnings("unchecked") - public void testReentrantProcessElementPreservesOuterContextAndMetadata() { + public void testReusableProcessContextResetAfterExceptionAndRejectsReentrancy() { TupleTag mainTag = new TupleTag<>("main"); - IntervalWindow outerWin = - new IntervalWindow(Instant.ofEpochMilli(100), Instant.ofEpochMilli(200)); - IntervalWindow innerWin = - new IntervalWindow(Instant.ofEpochMilli(500), Instant.ofEpochMilli(600)); - PaneInfo outerPane = PaneInfo.createPane(true, false, Timing.EARLY, 1, 0); - PaneInfo innerPane = PaneInfo.createPane(false, true, Timing.LATE, 2, 1); - WindowedValue outerElem = - WindowedValues.of( - "outer", - Instant.ofEpochMilli(150), - outerWin, - outerPane, - "outer-rec", - 11L, - CausedByDrain.NORMAL, - null, - ValueKind.INSERT); - WindowedValue innerElem = - WindowedValues.of( - "inner", - Instant.ofEpochMilli(550), - innerWin, - innerPane, - "inner-rec", - 22L, - CausedByDrain.CAUSED_BY_DRAIN, - null, - ValueKind.DELETE); - - List> observed = new ArrayList<>(); List.ProcessContext> capturedContexts = new ArrayList<>(); - DoFn echoDoFn = + DoFn doFn = new DoFn() { @ProcessElement - public void processElement( - ProcessContext c, BoundedWindow window, OutputReceiver out) { + public void processElement(ProcessContext c) { capturedContexts.add(c); - String before = "before:" + c.element() + "@" + c.timestamp().getMillis(); - out.output(before); - // Verify ProcessContext still sees its own element/window/metadata after reentry. - assertEquals(c.element().equals("outer") ? outerWin : innerWin, window); - String after = "after:" + c.element() + "@" + c.timestamp().getMillis(); - out.output(after); - } - }; - - final DoFnRunner[] runnerRef = new DoFnRunner[1]; - WindowedValueMultiReceiver reentrantOutputManager = - new WindowedValueMultiReceiver() { - @Override - public void output(TupleTag tag, WindowedValue output) { - WindowedValue wv = (WindowedValue) output; - observed.add(wv); - if ("before:outer@150".equals(wv.getValue())) { - runnerRef[0].processElement(innerElem); + if ("boom".equals(c.element())) { + throw new IllegalStateException("boom"); } + c.output("out:" + c.element()); } }; + List outputs = new ArrayList<>(); + final DoFnRunner[] runnerRef = new DoFnRunner[1]; runnerRef[0] = new SimpleDoFnRunner<>( null, - echoDoFn, - NullSideInputReader.empty(), - reentrantOutputManager, - mainTag, - Collections.emptyList(), - mockStepContext, - null, - Collections.emptyMap(), - WindowingStrategy.of(FixedWindows.of(Duration.millis(100))), - DoFnSchemaInformation.create(), - Collections.emptyMap()); - - runnerRef[0].startBundle(); - runnerRef[0].processElement(outerElem); - runnerRef[0].finishBundle(); - - assertEquals(4, observed.size()); - assertEquals("before:outer@150", observed.get(0).getValue()); - assertEquals(Instant.ofEpochMilli(150), observed.get(0).getTimestamp()); - assertThat(observed.get(0).getWindows(), contains(outerWin)); - assertEquals(outerPane, observed.get(0).getPaneInfo()); - assertEquals("outer-rec", observed.get(0).getRecordId()); - assertEquals(Long.valueOf(11L), observed.get(0).getRecordOffset()); - assertEquals(CausedByDrain.NORMAL, observed.get(0).causedByDrain()); - assertEquals(ValueKind.INSERT, observed.get(0).getValueKind()); - - assertEquals("before:inner@550", observed.get(1).getValue()); - assertEquals(Instant.ofEpochMilli(550), observed.get(1).getTimestamp()); - assertThat(observed.get(1).getWindows(), contains(innerWin)); - assertEquals(innerPane, observed.get(1).getPaneInfo()); - assertEquals("inner-rec", observed.get(1).getRecordId()); - assertEquals(Long.valueOf(22L), observed.get(1).getRecordOffset()); - assertEquals(CausedByDrain.CAUSED_BY_DRAIN, observed.get(1).causedByDrain()); - assertEquals(ValueKind.DELETE, observed.get(1).getValueKind()); - - assertEquals("after:inner@550", observed.get(2).getValue()); - assertEquals("after:outer@150", observed.get(3).getValue()); - assertEquals(Instant.ofEpochMilli(150), observed.get(3).getTimestamp()); - assertThat(observed.get(3).getWindows(), contains(outerWin)); - assertEquals(outerPane, observed.get(3).getPaneInfo()); - assertEquals("outer-rec", observed.get(3).getRecordId()); - assertEquals(Long.valueOf(11L), observed.get(3).getRecordOffset()); - assertEquals(CausedByDrain.NORMAL, observed.get(3).causedByDrain()); - assertEquals(ValueKind.INSERT, observed.get(3).getValueKind()); - - // Both primary AND reentrant fallback contexts must fail fast once @ProcessElement exits. - assertEquals(2, capturedContexts.size()); - for (DoFn.ProcessContext ctx : capturedContexts) { - assertThrows(IllegalStateException.class, ctx::element); - } - - // Reentrant inner exception swallowed inside outputManager still leaves outer context intact. - DoFn throwOnInnerFn = - new DoFn() { - @ProcessElement - public void processElement(ProcessContext c) { - if ("boom".equals(c.element())) { - throw new IllegalStateException("inner boom"); - } - c.output("pre:" + c.element()); - c.output("post:" + c.element()); - } - }; - List afterThrow = new ArrayList<>(); - final DoFnRunner[] runner2 = new DoFnRunner[1]; - runner2[0] = - new SimpleDoFnRunner<>( - null, - throwOnInnerFn, + doFn, NullSideInputReader.empty(), new WindowedValueMultiReceiver() { @Override public void output(TupleTag tag, WindowedValue out) { String v = (String) out.getValue(); - afterThrow.add(v); - if ("pre:outer".equals(v)) { + outputs.add(v); + if ("out:reenter".equals(v)) { assertThrows( - UserCodeException.class, - () -> runner2[0].processElement(WindowedValues.valueInGlobalWindow("boom"))); + IllegalStateException.class, + () -> + runnerRef[0].processElement( + WindowedValues.valueInGlobalWindow("nested"))); } } }, @@ -977,15 +1111,23 @@ public void output(TupleTag tag, WindowedValue out) WindowingStrategy.globalDefault(), DoFnSchemaInformation.create(), Collections.emptyMap()); - runner2[0].processElement(WindowedValues.valueInGlobalWindow("outer")); - assertThat(afterThrow, contains("pre:outer", "post:outer")); - // And after an outer exception, reusable context is cleanly reset for subsequent elements. + + runnerRef[0].startBundle(); + runnerRef[0].processElement(WindowedValues.valueInGlobalWindow("reenter")); + assertThat(outputs, contains("out:reenter")); + + // Retained context must fail fast once @ProcessElement exits. + assertEquals(1, capturedContexts.size()); + assertThrows(IllegalStateException.class, () -> capturedContexts.get(0).element()); + + // Exception inside @ProcessElement still clears the reusable context for subsequent elements. assertThrows( UserCodeException.class, - () -> runner2[0].processElement(WindowedValues.valueInGlobalWindow("boom"))); - afterThrow.clear(); - runner2[0].processElement(WindowedValues.valueInGlobalWindow("ok")); - assertThat(afterThrow, contains("pre:ok", "post:ok")); + () -> runnerRef[0].processElement(WindowedValues.valueInGlobalWindow("boom"))); + outputs.clear(); + runnerRef[0].processElement(WindowedValues.valueInGlobalWindow("ok")); + assertThat(outputs, contains("out:ok")); + runnerRef[0].finishBundle(); } @Test @@ -995,7 +1137,7 @@ public void testMultiOutputReceiverBoundariesDuplicatesAndNonIdenticalTag() { TupleTag mainCopy = new TupleTag<>("main"); TupleTag unknownTag = new TupleTag<>("unknown"); - // Verify 0, 1, 2, 8, and 9 extra tags (crossing MAX_INLINE_EXTRA_TAGS = 8 boundary), plus + // Verify 0, 1, 2, 8, and 9 extra tags (single-extra fast slot and multi-extra HashMap), plus // duplicate mainTag and duplicate side tag inside additionalOutputTags. for (int extraCount : new int[] {0, 1, 2, 8, 9}) { List> extraTags = new ArrayList<>(); diff --git a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java index be51ce71c6ea..d3050a07390e 100644 --- a/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java +++ b/sdks/java/core/jmh/src/main/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmark.java @@ -17,19 +17,31 @@ */ package org.apache.beam.sdk.jmh.transforms; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.concurrent.TimeUnit; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.DoFn.OutputReceiver; import org.apache.beam.sdk.transforms.DoFnOutputReceivers; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; import org.apache.beam.sdk.transforms.windowing.PaneInfo; -import org.apache.beam.sdk.util.OutputBuilderSupplier; import org.apache.beam.sdk.util.OutputBuilderSuppliers; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; +import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.TypeDescriptor; import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; import org.joda.time.Duration; @@ -38,39 +50,168 @@ import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; /** - * Microbenchmarks for {@link DoFnOutputReceivers}, {@link WindowedValues}, and {@link PaneInfo} - * per-element hot paths. + * Microbenchmarks for {@link DoFnOutputReceivers}, {@link OutputBuilderSuppliers}, and {@link + * WindowedValues} (including {@link WindowedValues.FullWindowedValueCoder}) per-element hot paths. + * + *

Run with {@code -prof gc} to measure per-element allocation rates and with {@code -t 4} (e.g. + * under {@code MIXED_POLYMORPHIC}) to observe multi-threaded secondary-super contention + * (JDK-8180450). */ -@BenchmarkMode(Mode.Throughput) -@OutputTimeUnit(TimeUnit.MICROSECONDS) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) public class OutputReceiverBenchmark { + private static final int RING_SIZE = 16; + private static final int RING_MASK = RING_SIZE - 1; + private static final class NoopDoFn extends DoFn {} + /** Unsynchronized resettable byte buffer avoiding monitor-lock overhead of JDK BAOS. */ + private static final class UnsyncByteArrayOutputStream extends OutputStream { + private byte[] buf; + private int count; + + UnsyncByteArrayOutputStream(int initialCapacity) { + this.buf = new byte[initialCapacity]; + } + + @Override + public void write(int b) { + ensureCapacity(count + 1); + buf[count++] = (byte) b; + } + + @Override + public void write(byte[] b, int off, int len) { + ensureCapacity(count + len); + System.arraycopy(b, off, buf, count, len); + count += len; + } + + private void ensureCapacity(int minCapacity) { + if (minCapacity > buf.length) { + buf = Arrays.copyOf(buf, Math.max(minCapacity, buf.length << 1)); + } + } + + void reset() { + count = 0; + } + + int size() { + return count; + } + + byte[] toByteArray() { + return Arrays.copyOf(buf, count); + } + + byte[] buffer() { + return buf; + } + } + + /** Unsynchronized resettable byte-array stream avoiding monitor-lock overhead of JDK BAIS. */ + private static final class UnsyncByteArrayInputStream extends InputStream { + private final byte[] buf; + private int pos; + + UnsyncByteArrayInputStream(byte[] buf) { + this.buf = buf; + } + + @Override + public int read() { + return pos < buf.length ? (buf[pos++] & 0xFF) : -1; + } + + @Override + public int read(byte[] b, int off, int len) { + if (len == 0) { + return 0; + } + if (pos >= buf.length) { + return -1; + } + int available = Math.min(len, buf.length - pos); + System.arraycopy(buf, pos, b, off, available); + pos += available; + return available; + } + + @Override + public void reset() { + pos = 0; + } + } + + private static final class RecordingByteSizeObserver extends ElementByteSizeObserver { + long lastSize; + + @Override + protected void reportElementSize(long elementByteSize) { + lastSize = elementByteSize; + } + } + + /** Thread-local benchmark state for {@link DoFnOutputReceivers} fast-path vs builder checks. */ @State(Scope.Thread) public static class ReceiverState { - final PipelineOptions options = PipelineOptionsFactory.create(); - final DoFn doFn = new NoopDoFn(); + /** Selects the template {@link WindowedValue} shape backing the {@link OutputReceiver}s. */ + @Param({ + "GLOBAL_MIN", + "GLOBAL_TIMESTAMPED", + "SINGLE_INTERVAL", + "MULTI_INTERVAL", + "MIXED_POLYMORPHIC", + "BUILDER_TEMPLATE" + }) + public String templateKind = "SINGLE_INTERVAL"; + final TupleTag mainTag = new TupleTag<>("main"); - final Instant ts = new Instant(1_700_000_000_000L); - final Instant outTs = new Instant(1_700_000_001_000L); - final IntervalWindow window = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); - final WindowedValue elem = - WindowedValues.of("input-element", ts, window, PaneInfo.NO_FIRING); - final OutputBuilderSupplier builderSupplier = OutputBuilderSuppliers.supplierForElement(elem); + final String[] values = new String[RING_SIZE]; + final Row[] rows = new Row[RING_SIZE]; + final Instant[] timestamps = new Instant[RING_SIZE]; + final WindowedValue[] templates = new WindowedValue[RING_SIZE]; + + @SuppressWarnings("unchecked") + final OutputReceiver[] taggedReceivers = + (OutputReceiver[]) new OutputReceiver[RING_SIZE]; + + @SuppressWarnings("unchecked") + final OutputReceiver[] untaggedReceivers = + (OutputReceiver[]) new OutputReceiver[RING_SIZE]; + + @SuppressWarnings("unchecked") + final OutputReceiver[] rowReceivers = + (OutputReceiver[]) new OutputReceiver[RING_SIZE]; + Collection explicitWindows; DoFn.WindowedContext context; - OutputReceiver cachedReceiver; - WindowedValue lastOutput; + int index; + /** + * Initializes receivers, contexts, and non-constant input rings to prevent constant folding. + */ @Setup - public void setUp() { + public void setUp(Blackhole bh) { + PipelineOptions options = PipelineOptionsFactory.create(); + DoFn doFn = new NoopDoFn(); + Schema schema = Schema.builder().addStringField("v").build(); + SchemaCoder schemaCoder = + SchemaCoder.of( + schema, + TypeDescriptor.of(String.class), + s -> Row.withSchema(schema).addValue(s).build(), + r -> r.getString(0)); + // Keep the DoFn stub free of io.opentelemetry.context.Context bytecode descriptors. context = doFn.new WindowedContext() { @Override @@ -80,22 +221,12 @@ public PipelineOptions getPipelineOptions() { @Override public void output(String output) { - lastOutput = elem.withValue(output); + throw new UnsupportedOperationException(); } @Override public void outputWithTimestamp(String output, Instant timestamp) { - lastOutput = - WindowedValues.of( - output, - timestamp, - elem.getWindows(), - elem.getPaneInfo(), - elem.getRecordId(), - elem.getRecordOffset(), - elem.causedByDrain(), - elem.getOpenTelemetryContext(), - elem.getValueKind()); + throw new UnsupportedOperationException(); } @Override @@ -104,32 +235,22 @@ public void outputWindowedValue( Instant timestamp, Collection windows, PaneInfo paneInfo) { - lastOutput = WindowedValues.of(output, timestamp, windows, paneInfo); + throw new UnsupportedOperationException(); } @Override public void outputWindowedValue(WindowedValue windowedValue) { - lastOutput = windowedValue; + bh.consume(windowedValue); } @Override public void output(TupleTag tag, T output) { - lastOutput = elem.withValue(output); + throw new UnsupportedOperationException(); } @Override public void outputWithTimestamp(TupleTag tag, T output, Instant timestamp) { - lastOutput = - WindowedValues.of( - output, - timestamp, - elem.getWindows(), - elem.getPaneInfo(), - elem.getRecordId(), - elem.getRecordOffset(), - elem.causedByDrain(), - elem.getOpenTelemetryContext(), - elem.getValueKind()); + throw new UnsupportedOperationException(); } @Override @@ -139,37 +260,245 @@ public void outputWindowedValue( Instant timestamp, Collection windows, PaneInfo paneInfo) { - lastOutput = WindowedValues.of(output, timestamp, windows, paneInfo); + throw new UnsupportedOperationException(); } @Override public void outputWindowedValue(TupleTag tag, WindowedValue windowedValue) { - lastOutput = windowedValue; + bh.consume(windowedValue); } }; - cachedReceiver = DoFnOutputReceivers.windowedReceiver(context, builderSupplier, mainTag); + + Instant baseTs = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(baseTs, baseTs.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + baseTs.plus(Duration.standardMinutes(1)), baseTs.plus(Duration.standardMinutes(2))); + explicitWindows = Collections.singletonList(w1); + + for (int i = 0; i < RING_SIZE; i++) { + values[i] = "output-element-" + i; + rows[i] = Row.withSchema(schema).addValue(values[i]).build(); + timestamps[i] = baseTs.plus(Duration.millis((i + 1) * 1000L)); + WindowedValue template = createTemplate(templateKind, i, baseTs, w1, w2); + templates[i] = template; + taggedReceivers[i] = + DoFnOutputReceivers.windowedReceiver( + context, OutputBuilderSuppliers.supplierForElement(template), mainTag); + untaggedReceivers[i] = + DoFnOutputReceivers.windowedReceiver( + context, OutputBuilderSuppliers.supplierForElement(template), null); + rowReceivers[i] = + DoFnOutputReceivers.rowReceiver( + context, OutputBuilderSuppliers.supplierForElement(template), mainTag, schemaCoder); + } + index = 0; } + + private static WindowedValue createTemplate( + String kind, int slot, Instant ts, IntervalWindow w1, IntervalWindow w2) { + String actualKind = kind; + if ("MIXED_POLYMORPHIC".equals(kind)) { + switch (slot & 3) { + case 0: + actualKind = "GLOBAL_MIN"; + break; + case 1: + actualKind = "GLOBAL_TIMESTAMPED"; + break; + case 2: + actualKind = "SINGLE_INTERVAL"; + break; + default: + actualKind = "MULTI_INTERVAL"; + break; + } + } + switch (actualKind) { + case "GLOBAL_MIN": + return WindowedValues.valueInGlobalWindow("in-" + slot); + case "GLOBAL_TIMESTAMPED": + return WindowedValues.timestampedValueInGlobalWindow("in-" + slot, ts); + case "SINGLE_INTERVAL": + return WindowedValues.of("in-" + slot, ts, w1, PaneInfo.NO_FIRING); + case "MULTI_INTERVAL": + return WindowedValues.of("in-" + slot, ts, Arrays.asList(w1, w2), PaneInfo.NO_FIRING); + case "BUILDER_TEMPLATE": + return WindowedValues.builder() + .setValue("in-" + slot) + .setTimestamp(ts) + .setWindow(w1) + .setPaneInfo(PaneInfo.NO_FIRING); + default: + throw new IllegalArgumentException("Unknown templateKind: " + kind); + } + } + + int nextSlot() { + return index++ & RING_MASK; + } + } + + /** Thread-local benchmark state for {@link WindowedValues.FullWindowedValueCoder}. */ + @State(Scope.Thread) + public static class CoderState { + /** Selects the encoded {@link WindowedValue} shape. */ + @Param({"GLOBAL_MIN", "SINGLE_INTERVAL", "MULTI_INTERVAL"}) + public String windowKind = "SINGLE_INTERVAL"; + + Coder> coder; + WindowedValue[] values; + UnsyncByteArrayInputStream[] inputStreams; + UnsyncByteArrayOutputStream out; + RecordingByteSizeObserver observer; + int index; + + /** Initializes coder instances, sample elements, and pre-encoded byte buffers. */ + @Setup + public void setUp() throws IOException { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); + @SuppressWarnings("unchecked") + WindowedValue[] typedValues = + (WindowedValue[]) new WindowedValue[RING_SIZE]; + values = typedValues; + inputStreams = new UnsyncByteArrayInputStream[RING_SIZE]; + out = new UnsyncByteArrayOutputStream(256); + observer = new RecordingByteSizeObserver(); + + if ("GLOBAL_MIN".equals(windowKind)) { + coder = WindowedValues.getFullCoder(StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE); + } else { + coder = WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); + } + + for (int i = 0; i < RING_SIZE; i++) { + String payload = "payload-element-" + i; + if ("GLOBAL_MIN".equals(windowKind)) { + values[i] = WindowedValues.valueInGlobalWindow(payload); + } else if ("SINGLE_INTERVAL".equals(windowKind)) { + values[i] = + WindowedValues.of(payload, ts.plus(Duration.millis(i)), w1, PaneInfo.NO_FIRING); + } else { + values[i] = + WindowedValues.of( + payload, + ts.plus(Duration.millis(i)), + Arrays.asList(w1, w2), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + } + out.reset(); + coder.encode(values[i], out); + inputStreams[i] = new UnsyncByteArrayInputStream(out.toByteArray()); + } + index = 0; + } + + int nextSlot() { + return index++ & RING_MASK; + } + } + + @Benchmark + public void windowedReceiverOutputTagged(ReceiverState s) { + int i = s.nextSlot(); + s.taggedReceivers[i].output(s.values[i]); + } + + @Benchmark + public void windowedReceiverOutputUntagged(ReceiverState s) { + int i = s.nextSlot(); + s.untaggedReceivers[i].output(s.values[i]); + } + + @Benchmark + public void windowedReceiverOutputViaBuilder(ReceiverState s) { + int i = s.nextSlot(); + s.taggedReceivers[i].builder(s.values[i]).output(); + } + + @Benchmark + public void windowedReceiverOutputWithTimestamp(ReceiverState s) { + int i = s.nextSlot(); + s.taggedReceivers[i].outputWithTimestamp(s.values[i], s.timestamps[i]); + } + + @Benchmark + public void windowedReceiverOutputWithTimestampViaBuilder(ReceiverState s) { + int i = s.nextSlot(); + s.taggedReceivers[i].builder(s.values[i]).setTimestamp(s.timestamps[i]).output(); + } + + @Benchmark + public void windowedReceiverOutputWindowedValue(ReceiverState s) { + int i = s.nextSlot(); + s.taggedReceivers[i].outputWindowedValue( + s.values[i], s.timestamps[i], s.explicitWindows, PaneInfo.NO_FIRING); + } + + @Benchmark + public void windowedReceiverOutputWindowedValueViaBuilder(ReceiverState s) { + int i = s.nextSlot(); + s.taggedReceivers[i] + .builder(s.values[i]) + .setTimestamp(s.timestamps[i]) + .setWindows(s.explicitWindows) + .setPaneInfo(PaneInfo.NO_FIRING) + .output(); + } + + @Benchmark + public void rowReceiverOutput(ReceiverState s) { + int i = s.nextSlot(); + s.rowReceivers[i].output(s.rows[i]); + } + + @Benchmark + public void rowReceiverOutputViaBuilder(ReceiverState s) { + int i = s.nextSlot(); + s.rowReceivers[i].builder(s.rows[i]).output(); + } + + @Benchmark + public void rowReceiverOutputWithTimestamp(ReceiverState s) { + int i = s.nextSlot(); + s.rowReceivers[i].outputWithTimestamp(s.rows[i], s.timestamps[i]); } @Benchmark - public void windowedReceiverOutput(ReceiverState s, Blackhole bh) { - s.cachedReceiver.output("output-element"); - bh.consume(s.lastOutput); + public void windowedReceiverPerElementConstruction(ReceiverState s) { + int i = s.nextSlot(); + OutputReceiver receiver = + DoFnOutputReceivers.windowedReceiver( + s.context, OutputBuilderSuppliers.supplierForElement(s.templates[i]), s.mainTag); + receiver.output(s.values[i]); } @Benchmark - public void windowedReceiverOutputWithTimestamp(ReceiverState s, Blackhole bh) { - s.cachedReceiver.outputWithTimestamp("output-element", s.outTs); - bh.consume(s.lastOutput); + public int fullWindowedValueCoderEncode(CoderState s) throws IOException { + int i = s.nextSlot(); + s.out.reset(); + s.coder.encode(s.values[i], s.out); + int size = s.out.size(); + byte[] buf = s.out.buffer(); + return size ^ (buf[0] & 0xFF) ^ (buf[size - 1] & 0xFF); } @Benchmark - public Collection singleWindowGetWindows(ReceiverState s) { - return s.elem.getWindows(); + public WindowedValue fullWindowedValueCoderDecode(CoderState s) throws IOException { + UnsyncByteArrayInputStream in = s.inputStreams[s.nextSlot()]; + in.reset(); + return s.coder.decode(in); } @Benchmark - public PaneInfo paneInfoWithElementMetadataNoChange() { - return PaneInfo.NO_FIRING.withElementMetadata(false); + public long fullWindowedValueCoderByteSizeObserver(CoderState s) throws Exception { + int i = s.nextSlot(); + s.coder.registerByteSizeObserver(s.values[i], s.observer); + s.observer.advance(); + return s.observer.lastSize; } } diff --git a/sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmarkTest.java b/sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmarkTest.java new file mode 100644 index 000000000000..31a015cdfb5f --- /dev/null +++ b/sdks/java/core/jmh/src/test/java/org/apache/beam/sdk/jmh/transforms/OutputReceiverBenchmarkTest.java @@ -0,0 +1,81 @@ +/* + * 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.sdk.jmh.transforms; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.apache.beam.sdk.jmh.transforms.OutputReceiverBenchmark.CoderState; +import org.apache.beam.sdk.jmh.transforms.OutputReceiverBenchmark.ReceiverState; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.openjdk.jmh.infra.Blackhole; + +/** Smoke tests for {@link OutputReceiverBenchmark}. */ +@RunWith(JUnit4.class) +public class OutputReceiverBenchmarkTest { + + private static final String[] TEMPLATE_KINDS = { + "GLOBAL_MIN", + "GLOBAL_TIMESTAMPED", + "SINGLE_INTERVAL", + "MULTI_INTERVAL", + "MIXED_POLYMORPHIC", + "BUILDER_TEMPLATE" + }; + + private static final String[] WINDOW_KINDS = {"GLOBAL_MIN", "SINGLE_INTERVAL", "MULTI_INTERVAL"}; + + @Test + public void testReceiverBenchmarks() { + Blackhole bh = + new Blackhole( + "Today's password is swordfish. I understand instantiating Blackholes directly is dangerous."); + OutputReceiverBenchmark benchmark = new OutputReceiverBenchmark(); + for (String kind : TEMPLATE_KINDS) { + ReceiverState state = new ReceiverState(); + state.templateKind = kind; + state.setUp(bh); + benchmark.windowedReceiverOutputTagged(state); + benchmark.windowedReceiverOutputUntagged(state); + benchmark.windowedReceiverOutputViaBuilder(state); + benchmark.windowedReceiverOutputWithTimestamp(state); + benchmark.windowedReceiverOutputWithTimestampViaBuilder(state); + benchmark.windowedReceiverOutputWindowedValue(state); + benchmark.windowedReceiverOutputWindowedValueViaBuilder(state); + benchmark.rowReceiverOutput(state); + benchmark.rowReceiverOutputViaBuilder(state); + benchmark.rowReceiverOutputWithTimestamp(state); + benchmark.windowedReceiverPerElementConstruction(state); + } + } + + @Test + public void testCoderBenchmarks() throws Exception { + OutputReceiverBenchmark benchmark = new OutputReceiverBenchmark(); + for (String kind : WINDOW_KINDS) { + CoderState state = new CoderState(); + state.windowKind = kind; + state.setUp(); + assertTrue(benchmark.fullWindowedValueCoderEncode(state) >= 0); + assertNotNull(benchmark.fullWindowedValueCoderDecode(state)); + assertTrue(benchmark.fullWindowedValueCoderByteSizeObserver(state) > 0); + } + } +} diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/IterableLikeCoder.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/IterableLikeCoder.java index 95a12bb3788d..43f46baa4b18 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/IterableLikeCoder.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/coders/IterableLikeCoder.java @@ -27,6 +27,7 @@ import java.util.Collection; import java.util.List; import java.util.Observable; +import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.util.BufferedElementCountingOutputStream; import org.apache.beam.sdk.util.VarInt; import org.apache.beam.sdk.util.common.ElementByteSizeObservableIterable; @@ -58,6 +59,13 @@ */ public abstract class IterableLikeCoder> extends StructuredCoder { + // Explicitly preserve the historical computed default serialVersionUID so internal framing + // helpers and static constants do not break Java serialization across worker/pipeline updates. + private static final long serialVersionUID = 6727373035450264331L; + + /** Pre-encoded big-endian 4-byte {@code 1} size header for single-element collections. */ + private static final byte[] SINGLE_ELEMENT_SIZE_BYTES = new byte[] {0, 0, 0, 1}; + public Coder getElemCoder() { return elementCoder; } @@ -97,6 +105,77 @@ protected IterableLikeCoder(Coder elementCoder, String iterableName) { this.iterableName = iterableName; } + /** + * Encodes a single-element collection containing {@code element} using the exact {@link + * IterableLikeCoder} known-size wire format (4-byte big-endian int {@code 1} followed by {@code + * element}), without allocating a wrapper {@link Collection}. + */ + @Internal + public static void encodeSingleElement( + Coder elementCoder, T element, OutputStream outStream) throws IOException, CoderException { + outStream.write(SINGLE_ELEMENT_SIZE_BYTES, 0, 4); + elementCoder.encode(element, outStream); + } + + /** + * Registers the byte size of a single-element collection containing {@code element} with {@code + * observer}, matching {@link #registerByteSizeObserver} for a 1-element {@link Collection} + * without allocating a wrapper collection. + */ + @Internal + public static void registerSingleElementByteSize( + Coder elementCoder, T element, ElementByteSizeObserver observer) throws Exception { + observer.update(4L); + elementCoder.registerByteSizeObserver(element, observer); + } + + /** + * Reads the leading 4-byte big-endian element-count header written by {@link #encode}. Returns a + * non-negative count for known-size collections, or a negative value (typically {@code -1}) for + * unknown-size chunked streams. + */ + @Internal + public static int readSizeHeader(InputStream inStream) throws IOException { + return BitConverters.readBigEndianInt(inStream); + } + + /** + * Decodes the remaining elements after {@link #readSizeHeader(InputStream)} has consumed the + * leading 4-byte size header {@code size}, handling both known-size ({@code size >= 0}) and + * chunked unknown-size ({@code size < 0}) streams. + */ + @Internal + public IterableT decodeAfterSizeHeader(int size, InputStream inStream) + throws IOException, CoderException { + if (size >= 0) { + List elements = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + elements.add(elementCoder.decode(inStream)); + } + return decodeToIterable(elements); + } + return decodeUnknownSize(inStream); + } + + private IterableT decodeUnknownSize(InputStream inStream) throws IOException, CoderException { + List elements = new ArrayList<>(); + // We don't know the size a priori. Check if we're done with + // each block of elements. + long count = VarInt.decodeLong(inStream); + while (count > 0L) { + elements.add(elementCoder.decode(inStream)); + --count; + if (count == 0L) { + count = VarInt.decodeLong(inStream); + } + } + if (count == 0L) { + return decodeToIterable(elements); + } else { + return decodeToIterable(elements, count, inStream); + } + } + @Override public void encode(IterableT iterable, OutputStream outStream) throws IOException, CoderException { @@ -107,7 +186,12 @@ public void encode(IterableT iterable, OutputStream outStream) // We can know the size of the Iterable. Use an encoding with a // leading size field, followed by that many elements. Collection collection = (Collection) iterable; - BitConverters.writeBigEndianInt(collection.size(), outStream); + int size = collection.size(); + if (size == 1) { + outStream.write(SINGLE_ELEMENT_SIZE_BYTES, 0, 4); + } else { + BitConverters.writeBigEndianInt(size, outStream); + } for (T elem : collection) { elementCoder.encode(elem, outStream); } @@ -128,30 +212,7 @@ public void encode(IterableT iterable, OutputStream outStream) @Override public IterableT decode(InputStream inStream) throws IOException, CoderException { - int size = BitConverters.readBigEndianInt(inStream); - if (size >= 0) { - List elements = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - elements.add(elementCoder.decode(inStream)); - } - return decodeToIterable(elements); - } - List elements = new ArrayList<>(); - // We don't know the size a priori. Check if we're done with - // each block of elements. - long count = VarInt.decodeLong(inStream); - while (count > 0L) { - elements.add(elementCoder.decode(inStream)); - --count; - if (count == 0L) { - count = VarInt.decodeLong(inStream); - } - } - if (count == 0) { - return decodeToIterable(elements); - } else { - return decodeToIterable(elements, count, inStream); - } + return decodeAfterSizeHeader(readSizeHeader(inStream), inStream); } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java index c02a196b9397..5bb47fc1f34e 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java @@ -21,17 +21,21 @@ import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState; +import java.util.Collection; import java.util.Map; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.transforms.DoFn.MultiOutputReceiver; import org.apache.beam.sdk.transforms.DoFn.OutputReceiver; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; import org.apache.beam.sdk.util.OutputBuilderSupplier; import org.apache.beam.sdk.util.WindowedValueReceiver; import org.apache.beam.sdk.values.OutputBuilder; import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.ValueKind; import org.apache.beam.sdk.values.WindowedValue; import org.checkerframework.checker.nullness.qual.Nullable; import org.joda.time.Instant; @@ -40,11 +44,11 @@ @Internal public class DoFnOutputReceivers { - private static class RowOutputReceiver implements OutputReceiver { + private static final class RowOutputReceiver implements OutputReceiver { private final @Nullable TupleTag tag; private final DoFn.WindowedContext context; private final OutputBuilderSupplier builderSupplier; - SchemaCoder schemaCoder; + private final SerializableFunction fromRowFunction; private RowOutputReceiver( DoFn.WindowedContext context, @@ -54,13 +58,10 @@ private RowOutputReceiver( this.context = context; this.builderSupplier = builderSupplier; this.tag = outputTag; - this.schemaCoder = schemaCoder; + this.fromRowFunction = schemaCoder.getFromRowFunction(); } - @Override - public void output(Row output) { - T converted = schemaCoder.getFromRowFunction().apply(output); - WindowedValue windowedValue = builderSupplier.build(converted); + private void emitWindowedValue(WindowedValue windowedValue) { if (tag == null) { ((DoFn.WindowedContext) context).outputWindowedValue(windowedValue); } else { @@ -68,45 +69,49 @@ public void output(Row output) { } } + @Override + public void output(Row output) { + emitWindowedValue(builderSupplier.build(fromRowFunction.apply(output))); + } + @Override public void outputWithTimestamp(Row output, Instant timestamp) { - T converted = schemaCoder.getFromRowFunction().apply(output); - WindowedValue windowedValue = builderSupplier.buildWithTimestamp(converted, timestamp); - if (tag == null) { - ((DoFn.WindowedContext) context).outputWindowedValue(windowedValue); - } else { - context.outputWindowedValue(tag, windowedValue); - } + emitWindowedValue( + builderSupplier.buildWithTimestamp(fromRowFunction.apply(output), timestamp)); } @Override - public OutputBuilder builder(Row value) { - // assigning to final variable allows static analysis to know it - // will not change between now and when receiver is invoked - final TupleTag tag = this.tag; - if (tag == null) { - return builderSupplier - .builder(value) - .setReceiver( - rowWithMetadata -> { - ((DoFn.WindowedContext) context) - .outputWindowedValue( - rowWithMetadata.withValue( - schemaCoder.getFromRowFunction().apply(rowWithMetadata.getValue()))); - }); + public void outputWindowedValue( + Row output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + emitWindowedValue( + builderSupplier.buildWindowedValue( + fromRowFunction.apply(output), timestamp, windows, paneInfo)); + } - } else { - checkStateNotNull(tag); - return builderSupplier - .builder(value) - .setReceiver( - rowWithMetadata -> { - context.outputWindowedValue( - tag, + @Override + public void outputWindowedValue( + Row output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + emitWindowedValue( + builderSupplier.buildWindowedValue( + fromRowFunction.apply(output), timestamp, windows, paneInfo, valueKind)); + } + + @Override + public OutputBuilder builder(Row value) { + return builderSupplier + .builder(value) + .setReceiver( + rowWithMetadata -> + emitWindowedValue( rowWithMetadata.withValue( - schemaCoder.getFromRowFunction().apply(rowWithMetadata.getValue()))); - }); - } + fromRowFunction.apply(rowWithMetadata.getValue())))); } } @@ -114,11 +119,11 @@ public OutputBuilder builder(Row value) { * OutputReceiver that delegates all its core functionality to DoFn.WindowedContext which predates * OutputReceiver and has most of the same methods. */ - private static class WindowedContextOutputReceiver + private static final class WindowedContextOutputReceiver implements OutputReceiver, WindowedValueReceiver { private final OutputBuilderSupplier builderSupplier; - DoFn.WindowedContext context; - @Nullable TupleTag outputTag; + private final DoFn.WindowedContext context; + private final @Nullable TupleTag outputTag; public WindowedContextOutputReceiver( DoFn.WindowedContext context, @@ -131,14 +136,35 @@ public WindowedContextOutputReceiver( @Override public void output(T output) { + // Delegates to WindowedValueReceiver#output(WindowedValue), not recursively to output(T). output(builderSupplier.build(output)); } @Override public void outputWithTimestamp(T output, Instant timestamp) { + // Delegates to WindowedValueReceiver#output(WindowedValue). output(builderSupplier.buildWithTimestamp(output, timestamp)); } + @Override + public void outputWindowedValue( + T output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + output(builderSupplier.buildWindowedValue(output, timestamp, windows, paneInfo)); + } + + @Override + public void outputWindowedValue( + T output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + output(builderSupplier.buildWindowedValue(output, timestamp, windows, paneInfo, valueKind)); + } + @Override public OutputBuilder builder(T value) { return builderSupplier.builder(value).setReceiver(this); @@ -154,10 +180,10 @@ public void output(WindowedValue windowedValue) { } } - private static class WindowedContextMultiOutputReceiver implements MultiOutputReceiver { + private static final class WindowedContextMultiOutputReceiver implements MultiOutputReceiver { private final OutputBuilderSupplier builderSupplier; private final DoFn.WindowedContext context; - @Nullable Map, Coder> outputCoders; + private final @Nullable Map, Coder> outputCoders; public WindowedContextMultiOutputReceiver( DoFn.WindowedContext context, @@ -171,8 +197,7 @@ public WindowedContextMultiOutputReceiver( // This exists for backwards compatibility with the Dataflow runner, and will be removed. public WindowedContextMultiOutputReceiver( DoFn.WindowedContext context, OutputBuilderSupplier builderSupplier) { - this.context = context; - this.builderSupplier = builderSupplier; + this(context, builderSupplier, null); } @Override diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java index 87afa3a9006d..db5c9a354e2d 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSupplier.java @@ -17,28 +17,108 @@ */ package org.apache.beam.sdk.util; +import java.util.Collection; import org.apache.beam.sdk.annotations.Internal; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.values.ValueKind; import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; import org.joda.time.Instant; +/** + * Supplies {@link WindowedValues.Builder} instances and derived {@link WindowedValue}s populated + * with template metadata for an emitted element. + */ @Internal @FunctionalInterface public interface OutputBuilderSupplier { - // Returns WindowedValues.Builder so that downstream can setReceiver (when tag is specified) - // but we need the value at a minimum in order to fix the type variable + /** + * Returns a fresh, independently mutable {@link WindowedValues.Builder} pre-populated with {@code + * value} and the supplier's template metadata (so downstream callers may mutate it in place, + * e.g., via {@link WindowedValues.Builder#setReceiver}). + * + *

The parameter {@code value} is required to fix the {@code OutputT} type variable. + * + * @param value the element value to initialize the returned builder with + * @return a fresh {@link WindowedValues.Builder} containing {@code value} + */ WindowedValues.Builder builder(OutputT value); - /** Builds a {@link WindowedValue} for {@code value} using the supplier's template metadata. */ + /** + * Builds a {@link WindowedValue} for {@code value} using the supplier's template metadata and + * capturing the current thread's OpenTelemetry {@code Context} (with {@code Context.root()} + * normalized to {@code null}). + * + *

Note: overrides should match the behavior of {@code builder(value).build()} for valid + * inputs, though exception types thrown on invalid {@code null} metadata may differ from the + * default implementation. + * + * @param value the element value + * @return a {@link WindowedValue} populated with {@code value} and template metadata + */ default WindowedValue build(OutputT value) { return builder(value).build(); } /** - * Builds a {@link WindowedValue} for {@code value} with the given {@code timestamp} using the - * supplier's template metadata. + * Builds a {@link WindowedValue} for {@code value} with the given non-null {@code timestamp} + * using the supplier's template metadata and capturing the current thread's OpenTelemetry {@code + * Context} (with {@code Context.root()} normalized to {@code null}). + * + * @param value the element value + * @param timestamp the non-null event timestamp + * @return a {@link WindowedValue} populated with {@code value}, {@code timestamp}, and template + * metadata */ default WindowedValue buildWithTimestamp(OutputT value, Instant timestamp) { return builder(value).setTimestamp(timestamp).build(); } + + /** + * Builds a {@link WindowedValue} for {@code value} with explicit {@code timestamp}, {@code + * windows}, and {@code paneInfo}, retaining the supplier's remaining template metadata (e.g., + * record id, record offset, drain status, {@link ValueKind}) and capturing the current thread's + * OpenTelemetry {@code Context} (with {@code Context.root()} normalized to {@code null}). + * + * @param value the element value + * @param timestamp the non-null event timestamp + * @param windows the non-empty collection of windows + * @param paneInfo the non-null {@link PaneInfo} + * @return a {@link WindowedValue} with the specified windowing attributes and template metadata + */ + default WindowedValue buildWindowedValue( + OutputT value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + return builder(value).setTimestamp(timestamp).setWindows(windows).setPaneInfo(paneInfo).build(); + } + + /** + * Builds a {@link WindowedValue} for {@code value} with explicit {@code timestamp}, {@code + * windows}, {@code paneInfo}, and {@code valueKind}, retaining the supplier's remaining template + * metadata (e.g., record id, record offset, drain status) and capturing the current thread's + * OpenTelemetry {@code Context} (with {@code Context.root()} normalized to {@code null}). + * + * @param value the element value + * @param timestamp the non-null event timestamp + * @param windows the non-empty collection of windows + * @param paneInfo the non-null {@link PaneInfo} + * @param valueKind the non-null {@link ValueKind} + * @return a {@link WindowedValue} with the specified attributes and template metadata + */ + default WindowedValue buildWindowedValue( + OutputT value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + return builder(value) + .setTimestamp(timestamp) + .setWindows(windows) + .setPaneInfo(paneInfo) + .setValueKind(valueKind) + .build(); + } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java index c7a357aea43a..d79060514545 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/OutputBuilderSuppliers.java @@ -17,7 +17,13 @@ */ package org.apache.beam.sdk.util; +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkNotNull; + +import java.util.Collection; import org.apache.beam.sdk.annotations.Internal; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.values.ValueKind; import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; import org.joda.time.Instant; @@ -27,22 +33,60 @@ public class OutputBuilderSuppliers { private OutputBuilderSuppliers() {} + /** + * Returns an {@link OutputBuilderSupplier} that copies metadata from {@code templateValue} + * without retaining its OpenTelemetry {@code Context}, avoiding intermediate {@link + * WindowedValues.Builder} allocations by delegating directly to {@link + * WindowedValues#ofWithCurrentContext(WindowedValue, Object)} and its sibling overloads. + * + * @param templateValue the non-null template {@link WindowedValue} + * @return an {@link OutputBuilderSupplier} backed by {@code templateValue} + */ public static OutputBuilderSupplier supplierForElement(WindowedValue templateValue) { - return new OutputBuilderSupplier() { - @Override - public WindowedValues.Builder builder(T value) { - return WindowedValues.builder(templateValue, value); - } - - @Override - public WindowedValue build(T value) { - return WindowedValues.ofWithCurrentContext(templateValue, value); - } - - @Override - public WindowedValue buildWithTimestamp(T value, Instant timestamp) { - return WindowedValues.ofWithCurrentContext(templateValue, value, timestamp); - } - }; + return new ElementOutputBuilderSupplier(templateValue); + } + + private static final class ElementOutputBuilderSupplier implements OutputBuilderSupplier { + private final WindowedValue templateValue; + + private ElementOutputBuilderSupplier(WindowedValue templateValue) { + this.templateValue = checkNotNull(templateValue, "templateValue must not be null"); + } + + @Override + public WindowedValues.Builder builder(T value) { + return WindowedValues.builder(templateValue, value); + } + + @Override + public WindowedValue build(T value) { + return WindowedValues.ofWithCurrentContext(templateValue, value); + } + + @Override + public WindowedValue buildWithTimestamp(T value, Instant timestamp) { + return WindowedValues.ofWithCurrentContext(templateValue, value, timestamp); + } + + @Override + public WindowedValue buildWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + return WindowedValues.ofWithCurrentContext( + templateValue, value, timestamp, windows, paneInfo); + } + + @Override + public WindowedValue buildWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + return WindowedValues.ofWithCurrentContext( + templateValue, value, timestamp, windows, paneInfo, valueKind); + } } } diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDo.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDo.java index e99f1c908941..adc001c80ba0 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDo.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDo.java @@ -621,7 +621,7 @@ public void processElement( new OutputBuilderSupplier() { @Override public WindowedValues.Builder builder(OutputT value) { - return WindowedValues.builder(outputReceiver.builder(null)).withValue(value); + return WindowedValues.builder(outputReceiver.builder(null), value); } }; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDoNaiveBounded.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDoNaiveBounded.java index 52b1174e3a03..e721875514a8 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDoNaiveBounded.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/util/construction/SplittableParDoNaiveBounded.java @@ -367,7 +367,7 @@ public String getErrorContext() { new OutputBuilderSupplier() { @Override public WindowedValues.Builder builder(X value) { - return WindowedValues.builder(outputReceiver.builder(null)).withValue(value); + return WindowedValues.builder(outputReceiver.builder(null), value); } }; diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValue.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValue.java index adc37b18ebf9..301e904835d0 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValue.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValue.java @@ -49,6 +49,15 @@ public interface WindowedValue { @Nullable String getRecordId(); + /** + * Returns the OpenTelemetry {@link Context} associated with this element, or {@code null} if no + * active non-root context is attached. + * + *

A {@code null} return value is semantically equivalent to {@link Context#root()} (no active + * trace context): factories and coders may normalize {@link Context#root()} to {@code null} to + * avoid carrying and attaching empty contexts on untraced pipelines, and runners may isolate + * thread-local state to {@link Context#root()} when dispatching a {@code null}-context element. + */ @Nullable Context getOpenTelemetryContext(); @Nullable Long getRecordOffset(); diff --git a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java index c7c213cb2e23..95c9cfbec1c9 100644 --- a/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java +++ b/sdks/java/core/src/main/java/org/apache/beam/sdk/values/WindowedValues.java @@ -23,15 +23,15 @@ import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkState; import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextStorage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; -import java.util.ArrayList; +import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -46,12 +46,12 @@ import org.apache.beam.sdk.coders.CoderException; import org.apache.beam.sdk.coders.CollectionCoder; import org.apache.beam.sdk.coders.InstantCoder; +import org.apache.beam.sdk.coders.IterableLikeCoder; import org.apache.beam.sdk.coders.StructuredCoder; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.PaneInfo; import org.apache.beam.sdk.transforms.windowing.PaneInfo.PaneInfoCoder; -import org.apache.beam.sdk.util.VarInt; import org.apache.beam.sdk.util.WindowedValueReceiver; import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.MoreObjects; @@ -76,20 +76,57 @@ public static Builder builder() { return new Builder<>(); } - /** Create a Builder that takes element metadata from the provided delegate. */ + /** + * Creates a {@link Builder} that copies element metadata (excluding OpenTelemetry {@link + * Context}) from the provided {@code template}. + * + *

The template's OpenTelemetry {@link Context} is intentionally not copied; {@link + * Builder#getOpenTelemetryContext()} captures the current thread's OpenTelemetry {@link Context} + * when built, normalizing {@link Context#root()} to {@code null}. + */ public static Builder builder(WindowedValue template) { return builder(template, template.getValue()); } /** - * Create a Builder that takes element metadata from the provided delegate with a new element - * value. + * Creates a {@link Builder} that copies element metadata (excluding OpenTelemetry {@link + * Context}) from the provided {@code template} with a new element {@code value}, without invoking + * {@link WindowedValue#getValue()} on {@code template}. + * + *

The template's OpenTelemetry {@link Context} is intentionally not copied; {@link + * Builder#getOpenTelemetryContext()} captures the current thread's OpenTelemetry {@link Context} + * when built, normalizing {@link Context#root()} to {@code null}. + * + * @param template the template {@link WindowedValue} supplying metadata + * @param value the value to set on the returned builder + * @return a fresh mutable {@link Builder} containing {@code value} and metadata from {@code + * template} */ public static Builder builder(WindowedValue template, T value) { - return new Builder() - .setValue(value) - .setTimestamp(template.getTimestamp()) - .setWindows(template.getWindows()) + Builder builder = new Builder().setValue(value).setTimestamp(template.getTimestamp()); + if (template instanceof SimpleWindowedValue) { + @Nullable BoundedWindow singleWindow = + ((SimpleWindowedValue) template).singleWindowOrNull(); + if (singleWindow != null) { + builder.setWindow(singleWindow); + } else { + builder.setWindows(template.getWindows()); + } + } else if (template instanceof Builder) { + Builder templateBuilder = (Builder) template; + if (templateBuilder.singleWindow != null) { + builder.setWindow(templateBuilder.singleWindow); + } else if (templateBuilder.windows != null) { + builder.setWindows(templateBuilder.windows); + } else { + throw new IllegalStateException("Windows not set"); + } + } else if (template instanceof SingleWindowedValue) { + builder.setWindow(((SingleWindowedValue) template).getWindow()); + } else { + builder.setWindows(template.getWindows()); + } + return builder .setPaneInfo(template.getPaneInfo()) .setRecordOffset(template.getRecordOffset()) .setRecordId(template.getRecordId()) @@ -113,7 +150,8 @@ public static class Builder implements OutputBuilder { private @MonotonicNonNull WindowedValueReceiver receiver; private @MonotonicNonNull PaneInfo paneInfo; private @MonotonicNonNull Instant timestamp; - private @MonotonicNonNull Collection windows; + private @Nullable Collection windows; + private @Nullable BoundedWindow singleWindow; private @Nullable String recordId; private @Nullable Long recordOffset; private CausedByDrain causedByDrain = CausedByDrain.NORMAL; @@ -135,6 +173,7 @@ public Builder setTimestamp(Instant timestamp) { @Override public Builder setWindows(Collection windows) { this.windows = windows; + this.singleWindow = null; return this; } @@ -146,7 +185,9 @@ public Builder setPaneInfo(PaneInfo paneInfo) { @Override public Builder setWindow(BoundedWindow window) { - return setWindows(Collections.singletonList(window)); + this.singleWindow = window; + this.windows = null; + return this; } @Override @@ -206,17 +247,28 @@ public Instant getTimestamp() { return timestamp; } + /** + * Returns the current thread's OpenTelemetry {@link Context}, or {@code null} when no non-root + * context is active (normalizing {@link Context#root()} to {@code null} by identity + * comparison). + */ @Override public @Nullable Context getOpenTelemetryContext() { - // builder may have different context set at the beginning of parDo - // when building WindowedValue we should take current context from storage. + // Builder may have been created under a different context at the beginning of a ParDo; + // when building a WindowedValue we take the current context from storage and omit root. return currentOpenTelemetryContextOrNull(); } @Override public Collection getWindows() { - checkStateNotNull(windows, "Windows not set"); - return windows; + Collection result = windows; + if (result != null) { + return result; + } + BoundedWindow sw = checkStateNotNull(singleWindow, "Windows not set"); + result = sw == GlobalWindow.INSTANCE ? GLOBAL_WINDOWS : Collections.singletonList(sw); + this.windows = result; + return result; } @Override @@ -256,8 +308,7 @@ public Collection> explodeWindows() { @Override @Pure public Builder withValue(OtherT newValue) { - // because of erasure, this type system lie is safe - return ((Builder) builder(this)).setValue(newValue); + return WindowedValues.builder(this, newValue); } @Override @@ -275,9 +326,24 @@ public void output() { } public WindowedValue build() { + T val = getValue(); + Instant ts = getTimestamp(); + BoundedWindow sw = singleWindow; + if (sw != null) { + return WindowedValues.of( + val, + ts, + sw, + getPaneInfo(), + getRecordId(), + getRecordOffset(), + causedByDrain(), + getOpenTelemetryContext(), + getValueKind()); + } return WindowedValues.of( - getValue(), - getTimestamp(), + val, + ts, getWindows(), getPaneInfo(), getRecordId(), @@ -315,6 +381,75 @@ public static WindowedValue of( ValueKind.INSERT); } + private static final long MIN_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); + + @SuppressWarnings("ReferenceEquality") + private static boolean isMinTimestamp(@Nullable Instant timestamp) { + return timestamp == BoundedWindow.TIMESTAMP_MIN_VALUE + || (timestamp != null && timestamp.getMillis() == MIN_TIMESTAMP_MILLIS); + } + + @SuppressWarnings("ReferenceEquality") + private static boolean isGlobalWindow(@Nullable BoundedWindow window) { + return window == GlobalWindow.INSTANCE || GlobalWindow.INSTANCE.equals(window); + } + + private static BoundedWindow extractSingleWindow(Collection windows) { + if (windows instanceof AbstractList) { + // Primary-super class check avoids JDK-8180450 _secondary_super_cache contention for + // SingletonList, ArrayList, Arrays$ArrayList, etc. + return ((AbstractList) windows).get(0); + } + if (windows instanceof List) { + return ((List) windows).get(0); + } + return windows.iterator().next(); + } + + private static WindowedValue ofValidated( + T value, + Instant timestamp, + BoundedWindow window, + PaneInfo paneInfo, + @Nullable String currentRecordId, + @Nullable Long currentRecordOffset, + CausedByDrain causedByDrain, + @Nullable Context openTelemetryContext, + ValueKind valueKind) { + boolean isGlobal = isGlobalWindow(window); + if (isGlobal && isMinTimestamp(timestamp)) { + return new ValueInGlobalWindow<>( + value, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + openTelemetryContext, + valueKind); + } else if (isGlobal) { + return new TimestampedValueInGlobalWindow<>( + value, + timestamp, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + openTelemetryContext, + valueKind); + } else { + return new TimestampedValueInSingleWindow<>( + value, + timestamp, + window, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + openTelemetryContext, + valueKind); + } + } + /** Returns a {@code WindowedValue} with the given value, timestamp, and windows. */ public static WindowedValue of( T value, @@ -327,18 +462,28 @@ public static WindowedValue of( @Nullable Context openTelemetryContext, ValueKind valueKind) { checkArgument(paneInfo != null, "WindowedValue requires PaneInfo, but it was null"); - checkArgument(windows.size() > 0, "WindowedValue requires windows, but there were none"); + checkArgument(windows != null, "WindowedValue requires windows, but it was null"); checkArgument(causedByDrain != null, "WindowedValue requires CausedByDrain, but it was null"); checkArgument(valueKind != null, "WindowedValue requires ValueKind, but it was null"); - if (windows.size() == 1) { - BoundedWindow window = - windows instanceof List - ? ((List) windows).get(0) - : windows.iterator().next(); - return of( + if (windows == GLOBAL_WINDOWS) { + return ofValidated( value, timestamp, - window, + GlobalWindow.INSTANCE, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + openTelemetryContext, + valueKind); + } + int size = windows.size(); + checkArgument(size > 0, "WindowedValue requires windows, but there were none"); + if (size == 1) { + return ofValidated( + value, + timestamp, + extractSingleWindow(windows), paneInfo, currentRecordId, currentRecordOffset, @@ -359,34 +504,38 @@ public static WindowedValue of( } } - private static final Context ROOT_OTEL_CONTEXT = Context.root(); - private static final long MIN_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); - - @SuppressWarnings("ReferenceEquality") - private static boolean isMinTimestamp(Instant timestamp) { - return timestamp == BoundedWindow.TIMESTAMP_MIN_VALUE - || (timestamp != null && timestamp.getMillis() == MIN_TIMESTAMP_MILLIS); - } - private static @Nullable Context currentOpenTelemetryContextOrNull() { - Context current = Context.current(); - return current == ROOT_OTEL_CONTEXT ? null : current; + @Nullable Context current = ContextStorage.get().current(); + return (current == null || current == Context.root()) ? null : current; } /** - * Returns the single {@link BoundedWindow} associated with {@code value} without allocating a - * wrapper collection, or {@code null} if {@code value} holds zero or multiple windows. + * Returns the single {@link BoundedWindow} associated with {@code value} if {@code value} uses a + * known single-window representation without allocating a wrapper collection, or {@code null} + * otherwise. + * + *

A {@code null} return indicates only that the fast single-window lookup did not apply (for + * example, a multi-window or empty element, an unset {@link Builder}, a {@link Builder} populated + * via {@link Builder#setWindows(Collection)}, or a custom {@link WindowedValue} that does not + * implement {@link SingleWindowedValue}); callers should fall back to {@link + * WindowedValue#getWindows()}. * - *

Dispatches via the {@link SimpleWindowedValue} abstract superclass on the common path + *

Dispatches via the {@code SimpleWindowedValue} / {@link Builder} class hierarchy first * (HotSpot primary-super check) rather than {@code instanceof SingleWindowedValue} to avoid * {@code _secondary_super_cache} contention (JDK-8180450) across concurrent worker threads when - * interleaved with {@code WindowedValue} interface casts. + * interleaved with {@link WindowedValue} interface casts. + * + * @param value the {@link WindowedValue} to inspect + * @return the single window, or {@code null} if {@code value} is not a known single-window + * representation */ - @Internal public static @Nullable BoundedWindow singleWindowOrNull(WindowedValue value) { if (value instanceof SimpleWindowedValue) { return ((SimpleWindowedValue) value).singleWindowOrNull(); } + if (value instanceof Builder) { + return ((Builder) value).singleWindow; + } if (value instanceof SingleWindowedValue) { return ((SingleWindowedValue) value).getWindow(); } @@ -394,39 +543,62 @@ private static boolean isMinTimestamp(Instant timestamp) { } /** - * Returns a {@code WindowedValue} copying metadata from {@code template} with a new {@code value} - * and capturing the current OpenTelemetry {@link Context}. + * Returns a {@link WindowedValue} copying {@code timestamp}, {@code windows}, {@code paneInfo}, + * {@code recordId}, {@code recordOffset}, {@code causedByDrain}, and {@code valueKind} from + * {@code template} with a new {@code value}, and replacing the OpenTelemetry {@link Context} with + * the current thread's OpenTelemetry {@link Context} (normalizing {@link Context#root()} to + * {@code null} by identity comparison). + * + *

Unlike {@link #withValue(WindowedValue, Object)}, which preserves {@code template}'s own + * OpenTelemetry {@link Context}, this method intentionally ignores {@code + * template.getOpenTelemetryContext()} and captures the current thread's active context. + * + * @param template the template {@link WindowedValue} supplying metadata + * @param value the element value for the returned {@link WindowedValue} + * @return a new {@link WindowedValue} containing {@code value} and metadata from {@code template} */ public static WindowedValue ofWithCurrentContext(WindowedValue template, T value) { - Context otelContext = currentOpenTelemetryContextOrNull(); + @Nullable Context otelContext = currentOpenTelemetryContextOrNull(); if (template instanceof SimpleWindowedValue) { - SimpleWindowedValue simple = (SimpleWindowedValue) template; - return simple.withValueAndContext(value, otelContext); + return ((SimpleWindowedValue) template).withValueAndContext(value, otelContext); } return ofWithCurrentContextFallback(template, value, template.getTimestamp(), otelContext); } /** - * Returns a {@code WindowedValue} copying metadata from {@code template} with a new {@code value} - * and {@code timestamp}, capturing the current OpenTelemetry {@link Context}. + * Returns a {@link WindowedValue} copying {@code windows}, {@code paneInfo}, {@code recordId}, + * {@code recordOffset}, {@code causedByDrain}, and {@code valueKind} from {@code template} with a + * new {@code value} and {@code timestamp}, and replacing the OpenTelemetry {@link Context} with + * the current thread's OpenTelemetry {@link Context} (normalizing {@link Context#root()} to + * {@code null} by identity comparison). + * + *

Unlike {@link #withValue(WindowedValue, Object)}, this method intentionally ignores {@code + * template.getOpenTelemetryContext()} and captures the current thread's active context. + * + * @param template the template {@link WindowedValue} supplying metadata + * @param value the element value for the returned {@link WindowedValue} + * @param timestamp the non-null event timestamp for the returned {@link WindowedValue} + * @return a new {@link WindowedValue} containing {@code value}, {@code timestamp}, and metadata + * from {@code template} */ public static WindowedValue ofWithCurrentContext( WindowedValue template, T value, Instant timestamp) { - Context otelContext = currentOpenTelemetryContextOrNull(); + @Nullable Context otelContext = currentOpenTelemetryContextOrNull(); if (template instanceof SimpleWindowedValue) { - SimpleWindowedValue simple = (SimpleWindowedValue) template; - return simple.withValueAndTimestampAndContext(value, timestamp, otelContext); + return ((SimpleWindowedValue) template) + .withValueAndTimestampAndContext(value, timestamp, otelContext); } return ofWithCurrentContextFallback(template, value, timestamp, otelContext); } private static WindowedValue ofWithCurrentContextFallback( WindowedValue template, T value, Instant timestamp, @Nullable Context otelContext) { - if (template instanceof SingleWindowedValue) { + @Nullable BoundedWindow singleWindow = singleWindowOrNull(template); + if (singleWindow != null) { return of( value, timestamp, - ((SingleWindowedValue) template).getWindow(), + singleWindow, template.getPaneInfo(), template.getRecordId(), template.getRecordOffset(), @@ -447,9 +619,20 @@ private static WindowedValue ofWithCurrentContextFallback( } /** - * Returns a {@code WindowedValue} copying non-windowed metadata from {@code template} with the - * specified {@code value}, {@code timestamp}, {@code windows}, and {@code paneInfo}, capturing - * the current OpenTelemetry {@link Context}. + * Returns a {@link WindowedValue} copying {@code recordId}, {@code recordOffset}, {@code + * causedByDrain}, and {@code valueKind} from {@code template} with the specified {@code value}, + * {@code timestamp}, {@code windows}, and {@code paneInfo}, and replacing the OpenTelemetry + * {@link Context} with the current thread's OpenTelemetry {@link Context} (normalizing {@link + * Context#root()} to {@code null} by identity comparison). + * + * @param template the template {@link WindowedValue} supplying record metadata, drain status, and + * {@link ValueKind} + * @param value the element value + * @param timestamp the non-null event timestamp + * @param windows the non-empty collection of windows + * @param paneInfo the non-null {@link PaneInfo} + * @return a new {@link WindowedValue} with the specified attributes and metadata from {@code + * template} */ public static WindowedValue ofWithCurrentContext( WindowedValue template, @@ -470,9 +653,20 @@ public static WindowedValue ofWithCurrentContext( } /** - * Returns a {@code WindowedValue} copying non-windowed metadata from {@code template} with the - * specified {@code value}, {@code timestamp}, {@code windows}, {@code paneInfo}, and {@code - * valueKind}, capturing the current OpenTelemetry {@link Context}. + * Returns a {@link WindowedValue} copying {@code recordId}, {@code recordOffset}, and {@code + * causedByDrain} from {@code template} with the specified {@code value}, {@code timestamp}, + * {@code windows}, {@code paneInfo}, and {@code valueKind}, and replacing the OpenTelemetry + * {@link Context} with the current thread's OpenTelemetry {@link Context} (normalizing {@link + * Context#root()} to {@code null} by identity comparison). + * + * @param template the template {@link WindowedValue} supplying record metadata and drain status + * @param value the element value + * @param timestamp the non-null event timestamp + * @param windows the non-empty collection of windows + * @param paneInfo the non-null {@link PaneInfo} + * @param valueKind the non-null {@link ValueKind} + * @return a new {@link WindowedValue} with the specified attributes and metadata from {@code + * template} */ public static WindowedValue ofWithCurrentContext( WindowedValue template, @@ -493,6 +687,78 @@ public static WindowedValue ofWithCurrentContext( valueKind); } + /** + * Returns a {@link WindowedValue} in a single {@code window} using the current thread's + * OpenTelemetry {@link Context} (normalizing {@link Context#root()} to {@code null} by identity + * comparison). + * + * @param value the element value + * @param timestamp the non-null event timestamp + * @param window the non-null {@link BoundedWindow} + * @param paneInfo the non-null {@link PaneInfo} + * @param currentRecordId the optional record id + * @param currentRecordOffset the optional record offset + * @param causedByDrain the non-null {@link CausedByDrain} + * @param valueKind the non-null {@link ValueKind} + * @return a new single-window {@link WindowedValue} + */ + public static WindowedValue ofWithCurrentContext( + T value, + Instant timestamp, + BoundedWindow window, + PaneInfo paneInfo, + @Nullable String currentRecordId, + @Nullable Long currentRecordOffset, + CausedByDrain causedByDrain, + ValueKind valueKind) { + return of( + value, + timestamp, + window, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + currentOpenTelemetryContextOrNull(), + valueKind); + } + + /** + * Returns a {@link WindowedValue} with the given {@code windows} using the current thread's + * OpenTelemetry {@link Context} (normalizing {@link Context#root()} to {@code null} by identity + * comparison). + * + * @param value the element value + * @param timestamp the non-null event timestamp + * @param windows the non-empty collection of windows + * @param paneInfo the non-null {@link PaneInfo} + * @param currentRecordId the optional record id + * @param currentRecordOffset the optional record offset + * @param causedByDrain the non-null {@link CausedByDrain} + * @param valueKind the non-null {@link ValueKind} + * @return a new {@link WindowedValue} + */ + public static WindowedValue ofWithCurrentContext( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + @Nullable String currentRecordId, + @Nullable Long currentRecordOffset, + CausedByDrain causedByDrain, + ValueKind valueKind) { + return of( + value, + timestamp, + windows, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + currentOpenTelemetryContextOrNull(), + valueKind); + } + /** * @deprecated for use only in compatibility with old broken code */ @@ -505,15 +771,23 @@ static WindowedValue createWithoutValidation( CausedByDrain causedByDrain, @Nullable Context openTelemetryContext, ValueKind valueKind) { + if (windows == GLOBAL_WINDOWS) { + return of( + value, + timestamp, + GlobalWindow.INSTANCE, + paneInfo, + null, + null, + causedByDrain, + openTelemetryContext, + valueKind); + } if (windows.size() == 1) { - BoundedWindow window = - windows instanceof List - ? ((List) windows).get(0) - : windows.iterator().next(); return of( value, timestamp, - window, + extractSingleWindow(windows), paneInfo, null, null, @@ -537,8 +811,6 @@ static WindowedValue createWithoutValidation( /** Returns a {@code WindowedValue} with the given value, timestamp, and window. */ public static WindowedValue of( T value, Instant timestamp, BoundedWindow window, PaneInfo paneInfo) { - checkArgument(paneInfo != null, "WindowedValue requires PaneInfo, but it was null"); - return of( value, timestamp, @@ -564,39 +836,16 @@ public static WindowedValue of( checkArgument(paneInfo != null, "WindowedValue requires PaneInfo, but it was null"); checkArgument(causedByDrain != null, "WindowedValue requires CausedByDrain, but it was null"); checkArgument(valueKind != null, "WindowedValue requires ValueKind, but it was null"); - - boolean isGlobal = window == GlobalWindow.INSTANCE || GlobalWindow.INSTANCE.equals(window); - if (isGlobal && isMinTimestamp(timestamp)) { - return new ValueInGlobalWindow<>( - value, - paneInfo, - currentRecordId, - currentRecordOffset, - causedByDrain, - openTelemetryContext, - valueKind); - } else if (isGlobal) { - return new TimestampedValueInGlobalWindow<>( - value, - timestamp, - paneInfo, - currentRecordId, - currentRecordOffset, - causedByDrain, - openTelemetryContext, - valueKind); - } else { - return new TimestampedValueInSingleWindow<>( - value, - timestamp, - window, - paneInfo, - currentRecordId, - currentRecordOffset, - causedByDrain, - openTelemetryContext, - valueKind); - } + return ofValidated( + value, + timestamp, + window, + paneInfo, + currentRecordId, + currentRecordOffset, + causedByDrain, + openTelemetryContext, + valueKind); } /** @@ -622,7 +871,7 @@ public static WindowedValue valueInGlobalWindow(T value, PaneInfo paneInf * default pane. */ public static WindowedValue timestampedValueInGlobalWindow(T value, Instant timestamp) { - if (BoundedWindow.TIMESTAMP_MIN_VALUE.equals(timestamp)) { + if (isMinTimestamp(timestamp)) { return valueInGlobalWindow(value); } else { return new TimestampedValueInGlobalWindow<>( @@ -653,10 +902,27 @@ public static WindowedValue timestampedValueInGlobalWindow( /** * Returns a new {@code WindowedValue} that is a copy of this one, but with a different value, - * which may have a new type {@code NewT}. + * which may have a new type {@code NewT}. Unlike {@link #ofWithCurrentContext(WindowedValue, + * Object)}, this preserves {@code windowedValue}'s existing OpenTelemetry {@link Context}. */ public static WindowedValue withValue( WindowedValue windowedValue, NewT newValue) { + if (windowedValue instanceof SimpleWindowedValue) { + return ((SimpleWindowedValue) windowedValue).withValue(newValue); + } + @Nullable BoundedWindow singleWindow = singleWindowOrNull(windowedValue); + if (singleWindow != null) { + return WindowedValues.of( + newValue, + windowedValue.getTimestamp(), + singleWindow, + windowedValue.getPaneInfo(), + windowedValue.getRecordId(), + windowedValue.getRecordOffset(), + windowedValue.causedByDrain(), + windowedValue.getOpenTelemetryContext(), + windowedValue.getValueKind()); + } return WindowedValues.of( newValue, windowedValue.getTimestamp(), @@ -864,6 +1130,11 @@ BoundedWindow singleWindowOrNull() { return GlobalWindow.INSTANCE; } + @Override + public Iterable> explodeWindows() { + return Collections.singletonList(this); + } + @Override public WindowedValue withValue(NewT newValue) { return new ValueInGlobalWindow<>( @@ -1004,6 +1275,11 @@ BoundedWindow singleWindowOrNull() { return GlobalWindow.INSTANCE; } + @Override + public Iterable> explodeWindows() { + return Collections.singletonList(this); + } + @Override public WindowedValue withValue(NewT newValue) { return new TimestampedValueInGlobalWindow<>( @@ -1094,7 +1370,6 @@ private static final class TimestampedValueInSingleWindow extends Timestamped implements SingleWindowedValue { private final BoundedWindow window; - private transient @MonotonicNonNull Collection windows; public TimestampedValueInSingleWindow( T value, @@ -1163,12 +1438,7 @@ WindowedValue withValueAndTimestampAndContext( @Override public Collection getWindows() { - Collection result = windows; - if (result == null) { - result = Collections.singletonList(window); - windows = result; - } - return result; + return Collections.singletonList(window); } @Override @@ -1181,6 +1451,11 @@ BoundedWindow singleWindowOrNull() { return window; } + @Override + public Iterable> explodeWindows() { + return Collections.singletonList(this); + } + @Override public boolean equals(@Nullable Object o) { if (o instanceof TimestampedValueInSingleWindow) { @@ -1432,37 +1707,79 @@ public WindowedValueCoder withValueCoder(Coder valueCoder) { return new FullWindowedValueCoder<>(valueCoder, windowCoder); } - private static final byte[] SINGLE_WINDOW_COUNT_BYTES = new byte[] {0, 0, 0, 1}; - - private static int readBigEndianInt(InputStream in) throws IOException { - int b1 = in.read(); - int b2 = in.read(); - int b3 = in.read(); - int b4 = in.read(); - if ((b1 | b2 | b3 | b4) < 0) { - throw new EOFException(); - } - return ((b1 & 0xFF) << 24) | ((b2 & 0xFF) << 16) | ((b3 & 0xFF) << 8) | (b4 & 0xFF); + private static Collection decodeMultipleWindows( + Coder windowCoder, int numWindows, InputStream inStream) throws IOException { + return CollectionCoder.of(windowCoder).decodeAfterSizeHeader(numWindows, inStream); } - private Collection decodeUnknownSizeWindows(InputStream inStream) + private static void encodeElementMetadata( + WindowedValue windowedElem, OutputStream outStream) throws IOException { + BeamFnApi.Elements.ElementMetadata.Builder builder = + BeamFnApi.Elements.ElementMetadata.newBuilder(); + io.opentelemetry.context.@Nullable Context openTelemetryContext = + windowedElem.getOpenTelemetryContext(); + if (openTelemetryContext != null + && openTelemetryContext != io.opentelemetry.context.Context.root()) { + OpenTelemetryContextPropagator.set(openTelemetryContext, builder); + } + BeamFnApi.Elements.ElementMetadata em = + builder + .setDrain( + windowedElem.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN + ? BeamFnApi.Elements.DrainMode.Enum.DRAINING + : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING) + .setValueKind(ValueKindUtil.toProto(windowedElem.getValueKind())) + .build(); + ByteArrayCoder.of().encode(em.toByteArray(), outStream); + } + + private WindowedValue decodeWithMetadata( + InputStream inStream, + Coder.Context context, + Instant timestamp, + int numWindows, + @Nullable BoundedWindow singleWindow, + @Nullable Collection windows, + PaneInfo paneInfo) throws IOException { - List elements = new ArrayList<>(); - long count = VarInt.decodeLong(inStream); - while (count > 0L) { - elements.add(windowCoder.decode(inStream)); - --count; - if (count == 0L) { - count = VarInt.decodeLong(inStream); - } + BeamFnApi.Elements.ElementMetadata elementMetadata = + BeamFnApi.Elements.ElementMetadata.parseFrom(ByteArrayCoder.of().decode(inStream)); + CausedByDrain causedByDrain = + elementMetadata.getDrain().equals(BeamFnApi.Elements.DrainMode.Enum.DRAINING) + ? CausedByDrain.CAUSED_BY_DRAIN + : CausedByDrain.NORMAL; + io.opentelemetry.context.@Nullable Context openTelemetryContext = null; + if (!elementMetadata.getTraceparent().isEmpty() + || !elementMetadata.getTracestate().isEmpty()) { + io.opentelemetry.context.Context extracted = + OpenTelemetryContextPropagator.read(elementMetadata); + openTelemetryContext = + extracted == io.opentelemetry.context.Context.root() ? null : extracted; } - if (count == 0L) { - return elements; + ValueKind valueKind = ValueKindUtil.fromProto(elementMetadata.getValueKind()); + T value = valueCoder.decode(inStream, context); + if (numWindows == 1) { + return WindowedValues.of( + value, + timestamp, + checkStateNotNull(singleWindow), + paneInfo, + null, + null, + causedByDrain, + openTelemetryContext, + valueKind); } - throw new IllegalStateException( - String.format( - "Collection does not support non zero terminator values. Received stream with terminator %s.", - count)); + // Because there are some remaining (incorrect) uses of WindowedValue with no windows, + // we call this deprecated no-validation path when decoding + return WindowedValues.createWithoutValidation( + value, + timestamp, + checkStateNotNull(windows), + paneInfo, + causedByDrain, + openTelemetryContext, + valueKind); } @Override @@ -1477,34 +1794,21 @@ public void encode(WindowedValue windowedElem, OutputStream outStream, Coder. InstantCoder.of().encode(windowedElem.getTimestamp(), outStream); @Nullable BoundedWindow singleWindow = singleWindowOrNull(windowedElem); if (singleWindow != null) { - outStream.write(SINGLE_WINDOW_COUNT_BYTES, 0, 4); + // Same invariant as constructor: callers must ensure windows match windowCoder. @SuppressWarnings("unchecked") Coder typedWindowCoder = (Coder) windowCoder; - typedWindowCoder.encode(singleWindow, outStream); + IterableLikeCoder.encodeSingleElement(typedWindowCoder, singleWindow, outStream); } else { windowsCoder.encode(windowedElem.getWindows(), outStream); } boolean metadataSupported = isMetadataSupported(); - PaneInfoCoder.INSTANCE.encode( - windowedElem.getPaneInfo().withElementMetadata(metadataSupported), outStream); + PaneInfo paneInfo = windowedElem.getPaneInfo(); + if (paneInfo.isElementMetadata() != metadataSupported) { + paneInfo = paneInfo.withElementMetadata(metadataSupported); + } + PaneInfoCoder.INSTANCE.encode(paneInfo, outStream); if (metadataSupported) { - BeamFnApi.Elements.ElementMetadata.Builder builder = - BeamFnApi.Elements.ElementMetadata.newBuilder(); - io.opentelemetry.context.Context openTelemetryContext = - windowedElem.getOpenTelemetryContext(); - if (openTelemetryContext != null) { - OpenTelemetryContextPropagator.set(openTelemetryContext, builder); - } - BeamFnApi.Elements.ElementMetadata em = - builder - .setDrain( - windowedElem.causedByDrain() == CausedByDrain.CAUSED_BY_DRAIN - ? BeamFnApi.Elements.DrainMode.Enum.DRAINING - : BeamFnApi.Elements.DrainMode.Enum.NOT_DRAINING) - .setValueKind(ValueKindUtil.toProto(windowedElem.getValueKind())) - .build(); - - ByteArrayCoder.of().encode(em.toByteArray(), outStream); + encodeElementMetadata(windowedElem, outStream); } valueCoder.encode(windowedElem.getValue(), outStream, context); } @@ -1518,49 +1822,24 @@ public WindowedValue decode(InputStream inStream) throws CoderException, IOEx public WindowedValue decode(InputStream inStream, Coder.Context context) throws CoderException, IOException { Instant timestamp = InstantCoder.of().decode(inStream); - int numWindows = readBigEndianInt(inStream); + int numWindows = IterableLikeCoder.readSizeHeader(inStream); @Nullable BoundedWindow singleWindow = null; @Nullable Collection windows = null; if (numWindows == 1) { - singleWindow = checkNotNull(windowCoder.decode(inStream), "WindowedValue window is null"); - } else if (numWindows == 0) { - windows = Collections.emptyList(); - } else if (numWindows > 1) { - List windowList = new ArrayList<>(numWindows); - for (int i = 0; i < numWindows; i++) { - windowList.add(windowCoder.decode(inStream)); - } - windows = windowList; + singleWindow = + checkNotNull(windowCoder.decode(inStream), "Decoded single window must not be null"); } else { - windows = decodeUnknownSizeWindows(inStream); + windows = decodeMultipleWindows(windowCoder, numWindows, inStream); } PaneInfo paneInfo = PaneInfoCoder.INSTANCE.decode(inStream); - CausedByDrain causedByDrain = CausedByDrain.NORMAL; - io.opentelemetry.context.Context openTelemetryContext = null; - ValueKind valueKind = ValueKind.INSERT; - if (isMetadataSupported() && paneInfo.isElementMetadata()) { - BeamFnApi.Elements.ElementMetadata elementMetadata = - BeamFnApi.Elements.ElementMetadata.parseFrom(ByteArrayCoder.of().decode(inStream)); - causedByDrain = - elementMetadata.getDrain().equals(BeamFnApi.Elements.DrainMode.Enum.DRAINING) - ? CausedByDrain.CAUSED_BY_DRAIN - : CausedByDrain.NORMAL; - openTelemetryContext = OpenTelemetryContextPropagator.read(elementMetadata); - valueKind = ValueKindUtil.fromProto(elementMetadata.getValueKind()); + // Check plain paneInfo field before volatile metadataSupported load-acquire. + if (paneInfo.isElementMetadata() && isMetadataSupported()) { + return decodeWithMetadata( + inStream, context, timestamp, numWindows, singleWindow, windows, paneInfo); } T value = valueCoder.decode(inStream, context); - - if (singleWindow != null) { - return WindowedValues.of( - value, - timestamp, - singleWindow, - paneInfo, - null, - null, - causedByDrain, - openTelemetryContext, - valueKind); + if (numWindows == 1) { + return WindowedValues.of(value, timestamp, checkStateNotNull(singleWindow), paneInfo); } // Because there are some remaining (incorrect) uses of WindowedValue with no windows, // we call this deprecated no-validation path when decoding @@ -1569,9 +1848,9 @@ public WindowedValue decode(InputStream inStream, Coder.Context context) timestamp, checkStateNotNull(windows), paneInfo, - causedByDrain, - openTelemetryContext, - valueKind); + CausedByDrain.NORMAL, + null, + ValueKind.INSERT); } @Override @@ -1588,10 +1867,10 @@ public void registerByteSizeObserver(WindowedValue value, ElementByteSizeObse InstantCoder.of().registerByteSizeObserver(value.getTimestamp(), observer); @Nullable BoundedWindow singleWindow = singleWindowOrNull(value); if (singleWindow != null) { - observer.update(4L); + // Same invariant as constructor: callers must ensure windows match windowCoder. @SuppressWarnings("unchecked") Coder typedWindowCoder = (Coder) windowCoder; - typedWindowCoder.registerByteSizeObserver(singleWindow, observer); + IterableLikeCoder.registerSingleElementByteSize(typedWindowCoder, singleWindow, observer); } else { windowsCoder.registerByteSizeObserver(value.getWindows(), observer); } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/coders/CollectionCoderTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/coders/CollectionCoderTest.java index bf507a02e2c5..eeede626291f 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/coders/CollectionCoderTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/coders/CollectionCoderTest.java @@ -20,6 +20,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -29,6 +31,7 @@ import org.apache.beam.sdk.testing.CoderProperties; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.util.CoderUtils; +import org.apache.beam.sdk.util.common.ElementByteSizeObserver; import org.apache.beam.sdk.values.TypeDescriptor; import org.junit.Rule; import org.junit.Test; @@ -91,4 +94,47 @@ public void testEncodedTypeDescriptor() throws Exception { new TypeDescriptor>() {}; assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(expectedTypeDescriptor)); } + + @Test + public void testSingleElementAndHeaderHelpersMatchWireFormat() throws Exception { + CollectionCoder coder = CollectionCoder.of(VarIntCoder.of()); + ByteArrayOutputStream helperOut = new ByteArrayOutputStream(); + IterableLikeCoder.encodeSingleElement(VarIntCoder.of(), 13, helperOut); + ByteArrayOutputStream fullOut = new ByteArrayOutputStream(); + coder.encode(Collections.singletonList(13), fullOut); + assertThat(helperOut.toByteArray(), equalTo(fullOut.toByteArray())); + + ByteArrayInputStream singleIn = new ByteArrayInputStream(fullOut.toByteArray()); + assertThat(IterableLikeCoder.readSizeHeader(singleIn), equalTo(1)); + assertThat(VarIntCoder.of().decode(singleIn), equalTo(13)); + + ByteArrayOutputStream multiOut = new ByteArrayOutputStream(); + coder.encode(Arrays.asList(1, 2, 3, 4), multiOut); + ByteArrayInputStream multiIn = new ByteArrayInputStream(multiOut.toByteArray()); + int size = IterableLikeCoder.readSizeHeader(multiIn); + assertThat(size, equalTo(4)); + assertThat(coder.decodeAfterSizeHeader(size, multiIn), equalTo(Arrays.asList(1, 2, 3, 4))); + + long[] helperSize = new long[1]; + long[] fullSize = new long[1]; + ElementByteSizeObserver helperObs = + new ElementByteSizeObserver() { + @Override + protected void reportElementSize(long elementByteSize) { + helperSize[0] += elementByteSize; + } + }; + ElementByteSizeObserver fullObs = + new ElementByteSizeObserver() { + @Override + protected void reportElementSize(long elementByteSize) { + fullSize[0] += elementByteSize; + } + }; + IterableLikeCoder.registerSingleElementByteSize(VarIntCoder.of(), 13, helperObs); + helperObs.advance(); + coder.registerByteSizeObserver(Collections.singletonList(13), fullObs); + fullObs.advance(); + assertThat(helperSize[0], equalTo(fullSize[0])); + } } diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/DoFnOutputReceiversTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/DoFnOutputReceiversTest.java new file mode 100644 index 000000000000..9fd59058a74f --- /dev/null +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/DoFnOutputReceiversTest.java @@ -0,0 +1,375 @@ +/* + * 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.sdk.transforms; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.apache.beam.sdk.coders.Coder; +import org.apache.beam.sdk.options.PipelineOptions; +import org.apache.beam.sdk.options.PipelineOptionsFactory; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.SchemaCoder; +import org.apache.beam.sdk.transforms.DoFn.MultiOutputReceiver; +import org.apache.beam.sdk.transforms.DoFn.OutputReceiver; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.transforms.windowing.PaneInfo.Timing; +import org.apache.beam.sdk.util.OutputBuilderSupplier; +import org.apache.beam.sdk.util.OutputBuilderSuppliers; +import org.apache.beam.sdk.values.CausedByDrain; +import org.apache.beam.sdk.values.Row; +import org.apache.beam.sdk.values.TupleTag; +import org.apache.beam.sdk.values.TypeDescriptor; +import org.apache.beam.sdk.values.ValueKind; +import org.apache.beam.sdk.values.WindowedValue; +import org.apache.beam.sdk.values.WindowedValues; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link DoFnOutputReceivers}. */ +@RunWith(JUnit4.class) +public class DoFnOutputReceiversTest { + + private static final Instant TS = new Instant(1_700_000_000_000L); + private static final Instant TS2 = TS.plus(Duration.standardSeconds(5)); + private static final IntervalWindow W1 = + new IntervalWindow(TS, TS.plus(Duration.standardMinutes(1))); + private static final IntervalWindow W2 = + new IntervalWindow( + TS.plus(Duration.standardMinutes(1)), TS.plus(Duration.standardMinutes(2))); + private static final PaneInfo PANE = PaneInfo.createPane(false, false, Timing.EARLY, 1, 0); + private static final Schema ROW_SCHEMA = Schema.builder().addStringField("val").build(); + + private static final class DummyDoFn extends DoFn {} + + private static final class RecordingHarness { + final List> mainOutputs = new ArrayList<>(); + final List taggedOutputs = new ArrayList<>(); + final DoFn.WindowedContext context; + + RecordingHarness() { + PipelineOptions options = PipelineOptionsFactory.create(); + DoFn doFn = new DummyDoFn<>(); + this.context = + doFn.new WindowedContext() { + @Override + public PipelineOptions getPipelineOptions() { + return options; + } + + @Override + public void output(T output) { + throw new UnsupportedOperationException(); + } + + @Override + public void outputWithTimestamp(T output, Instant timestamp) { + throw new UnsupportedOperationException(); + } + + @Override + public void outputWindowedValue( + T output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + throw new UnsupportedOperationException(); + } + + @Override + public void outputWindowedValue(WindowedValue windowedValue) { + mainOutputs.add(windowedValue); + } + + @Override + public void output(TupleTag tag, OutputT output) { + throw new UnsupportedOperationException(); + } + + @Override + public void outputWithTimestamp( + TupleTag tag, OutputT output, Instant timestamp) { + throw new UnsupportedOperationException(); + } + + @Override + public void outputWindowedValue( + TupleTag tag, + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + throw new UnsupportedOperationException(); + } + + @Override + public void outputWindowedValue( + TupleTag tag, WindowedValue windowedValue) { + taggedOutputs.add(new TaggedOutput(tag, windowedValue)); + } + }; + } + } + + private static final class TaggedOutput { + final TupleTag tag; + final WindowedValue value; + + TaggedOutput(TupleTag tag, WindowedValue value) { + this.tag = tag; + this.value = value; + } + } + + private static WindowedValue metadataTemplate(Context templateCtx) { + return WindowedValues.of( + "template", + TS, + W1, + PANE, + "rid-42", + 99L, + CausedByDrain.CAUSED_BY_DRAIN, + templateCtx, + ValueKind.UPDATE_BEFORE); + } + + private static Context activeSpan(String traceId) { + return Context.root() + .with( + Span.wrap( + SpanContext.create( + traceId, + "ff00000000000041", + TraceFlags.getSampled(), + TraceState.getDefault()))); + } + + @Test + public void testWindowedReceiverUntaggedAndTaggedFastPaths() { + Context templateCtx = activeSpan("aa000000000000000000000000000001"); + Context activeCtx = activeSpan("ff000000000000000000000000000041"); + OutputBuilderSupplier supplier = + OutputBuilderSuppliers.supplierForElement(metadataTemplate(templateCtx)); + RecordingHarness<@Nullable String> harness = new RecordingHarness<>(); + + OutputReceiver<@Nullable String> main = + DoFnOutputReceivers.windowedReceiver(harness.context, supplier, null); + TupleTag<@Nullable String> sideTag = new TupleTag<>("side"); + OutputReceiver<@Nullable String> side = + DoFnOutputReceivers.windowedReceiver(harness.context, supplier, sideTag); + + try (Scope ignored = Context.root().makeCurrent()) { + main.output("m1"); + main.output(null); + side.output("s1"); + } + assertEquals(2, harness.mainOutputs.size()); + assertMetadataPreserved( + harness.mainOutputs.get(0), "m1", TS, W1, PANE, ValueKind.UPDATE_BEFORE); + assertNull(harness.mainOutputs.get(0).getOpenTelemetryContext()); + assertNull(harness.mainOutputs.get(1).getValue()); + assertEquals(1, harness.taggedOutputs.size()); + assertSame(sideTag, harness.taggedOutputs.get(0).tag); + assertMetadataPreserved( + harness.taggedOutputs.get(0).value, "s1", TS, W1, PANE, ValueKind.UPDATE_BEFORE); + assertNull(harness.taggedOutputs.get(0).value.getOpenTelemetryContext()); + + try (Scope ignored = activeCtx.makeCurrent()) { + main.outputWithTimestamp("m2", TS2); + main.outputWindowedValue( + "m3", TS2, Collections.singletonList(W2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + main.outputWindowedValue( + "m4", TS2, Arrays.asList(W1, W2), PaneInfo.NO_FIRING, ValueKind.DELETE); + main.builder("m5").setRecordId("override-id").output(); + + side.outputWithTimestamp("s2", TS2); + side.outputWindowedValue( + "s3", TS2, Collections.singletonList(W2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + side.outputWindowedValue( + "s4", TS2, Arrays.asList(W1, W2), PaneInfo.NO_FIRING, ValueKind.DELETE); + side.builder("s5").setRecordOffset(123L).output(); + } + + assertEquals(6, harness.mainOutputs.size()); + assertMetadataPreserved( + harness.mainOutputs.get(2), "m2", TS2, W1, PANE, ValueKind.UPDATE_BEFORE); + assertSame(activeCtx, harness.mainOutputs.get(2).getOpenTelemetryContext()); + assertMetadataPreserved( + harness.mainOutputs.get(3), + "m3", + TS2, + W2, + PaneInfo.ON_TIME_AND_ONLY_FIRING, + ValueKind.UPDATE_BEFORE); + assertSame(activeCtx, harness.mainOutputs.get(3).getOpenTelemetryContext()); + assertEquals(ValueKind.DELETE, harness.mainOutputs.get(4).getValueKind()); + assertThat(harness.mainOutputs.get(4).getWindows(), containsInAnyOrder(W1, W2)); + assertEquals("override-id", harness.mainOutputs.get(5).getRecordId()); + assertSame(activeCtx, harness.mainOutputs.get(5).getOpenTelemetryContext()); + + assertEquals(5, harness.taggedOutputs.size()); + assertMetadataPreserved( + harness.taggedOutputs.get(1).value, "s2", TS2, W1, PANE, ValueKind.UPDATE_BEFORE); + assertMetadataPreserved( + harness.taggedOutputs.get(2).value, + "s3", + TS2, + W2, + PaneInfo.ON_TIME_AND_ONLY_FIRING, + ValueKind.UPDATE_BEFORE); + assertEquals(ValueKind.DELETE, harness.taggedOutputs.get(3).value.getValueKind()); + assertEquals(Long.valueOf(123L), harness.taggedOutputs.get(4).value.getRecordOffset()); + } + + @Test + public void testWindowedReceiverAcceptsWindowedValueAsPayloadWithoutRecursion() { + OutputBuilderSupplier supplier = + OutputBuilderSuppliers.supplierForElement(metadataTemplate(Context.root())); + RecordingHarness harness = new RecordingHarness<>(); + OutputReceiver receiver = + DoFnOutputReceivers.windowedReceiver(harness.context, supplier, null); + + WindowedValue payload = WindowedValues.valueInGlobalWindow("inner"); + receiver.output(payload); + assertEquals(1, harness.mainOutputs.size()); + assertSame(payload, harness.mainOutputs.get(0).getValue()); + } + + @Test + public void testRowReceiverUntaggedAndTaggedAndMultiReceiver() { + Context templateCtx = activeSpan("aa000000000000000000000000000001"); + Context activeCtx = activeSpan("dd000000000000000000000000000004"); + SchemaCoder schemaCoder = + SchemaCoder.of( + ROW_SCHEMA, + TypeDescriptor.of(String.class), + s -> Row.withSchema(ROW_SCHEMA).addValue(s).build(), + r -> "converted:" + r.getString(0)); + OutputBuilderSupplier supplier = + OutputBuilderSuppliers.supplierForElement(metadataTemplate(templateCtx)); + RecordingHarness harness = new RecordingHarness<>(); + TupleTag sideTag = new TupleTag<>("rows"); + + OutputReceiver mainRow = + DoFnOutputReceivers.rowReceiver(harness.context, supplier, null, schemaCoder); + Map, Coder> coders = Collections.singletonMap(sideTag, schemaCoder); + MultiOutputReceiver multi = + DoFnOutputReceivers.windowedMultiReceiver(harness.context, supplier, coders); + OutputReceiver sideRow = multi.getRowReceiver(sideTag); + OutputReceiver sideTyped = multi.get(sideTag); + + try (Scope ignored = activeCtx.makeCurrent()) { + mainRow.output(row("a")); + mainRow.outputWithTimestamp(row("b"), TS2); + mainRow.outputWindowedValue( + row("c"), TS2, Collections.singletonList(W2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + mainRow.outputWindowedValue( + row("d"), TS2, Arrays.asList(W1, W2), PaneInfo.NO_FIRING, ValueKind.DELETE); + mainRow.builder(row("e")).setRecordId("custom-row-id").output(); + + sideRow.output(row("sa")); + sideRow.outputWithTimestamp(row("sb"), TS2); + sideRow.outputWindowedValue( + row("sc"), TS2, Collections.singletonList(W2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + sideRow.outputWindowedValue( + row("sd"), TS2, Arrays.asList(W1, W2), PaneInfo.NO_FIRING, ValueKind.DELETE); + sideRow.builder(row("se")).setRecordOffset(777L).output(); + + sideTyped.output("typed-side"); + } + + assertEquals(5, harness.mainOutputs.size()); + assertMetadataPreserved( + harness.mainOutputs.get(0), "converted:a", TS, W1, PANE, ValueKind.UPDATE_BEFORE); + assertSame(activeCtx, harness.mainOutputs.get(0).getOpenTelemetryContext()); + assertMetadataPreserved( + harness.mainOutputs.get(1), "converted:b", TS2, W1, PANE, ValueKind.UPDATE_BEFORE); + assertMetadataPreserved( + harness.mainOutputs.get(2), + "converted:c", + TS2, + W2, + PaneInfo.ON_TIME_AND_ONLY_FIRING, + ValueKind.UPDATE_BEFORE); + assertEquals("converted:d", harness.mainOutputs.get(3).getValue()); + assertEquals(ValueKind.DELETE, harness.mainOutputs.get(3).getValueKind()); + assertEquals("converted:e", harness.mainOutputs.get(4).getValue()); + assertEquals("custom-row-id", harness.mainOutputs.get(4).getRecordId()); + + assertEquals(6, harness.taggedOutputs.size()); + assertMetadataPreserved( + harness.taggedOutputs.get(0).value, "converted:sa", TS, W1, PANE, ValueKind.UPDATE_BEFORE); + assertMetadataPreserved( + harness.taggedOutputs.get(1).value, "converted:sb", TS2, W1, PANE, ValueKind.UPDATE_BEFORE); + assertMetadataPreserved( + harness.taggedOutputs.get(2).value, + "converted:sc", + TS2, + W2, + PaneInfo.ON_TIME_AND_ONLY_FIRING, + ValueKind.UPDATE_BEFORE); + assertEquals("converted:sd", harness.taggedOutputs.get(3).value.getValue()); + assertEquals(ValueKind.DELETE, harness.taggedOutputs.get(3).value.getValueKind()); + assertEquals("converted:se", harness.taggedOutputs.get(4).value.getValue()); + assertEquals(Long.valueOf(777L), harness.taggedOutputs.get(4).value.getRecordOffset()); + assertEquals("typed-side", harness.taggedOutputs.get(5).value.getValue()); + } + + private static Row row(String s) { + return Row.withSchema(ROW_SCHEMA).addValue(s).build(); + } + + private static void assertMetadataPreserved( + WindowedValue actual, + Object expectedValue, + Instant expectedTs, + BoundedWindow expectedWindow, + PaneInfo expectedPane, + ValueKind expectedKind) { + assertEquals(expectedValue, actual.getValue()); + assertEquals(expectedTs, actual.getTimestamp()); + assertEquals(expectedWindow, WindowedValues.singleWindowOrNull(actual)); + assertEquals(expectedPane, actual.getPaneInfo()); + assertEquals("rid-42", actual.getRecordId()); + assertEquals(Long.valueOf(99L), actual.getRecordOffset()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, actual.causedByDrain()); + assertEquals(expectedKind, actual.getValueKind()); + } +} diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/OutputBuilderSuppliersTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/OutputBuilderSuppliersTest.java new file mode 100644 index 000000000000..8e299934d195 --- /dev/null +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/OutputBuilderSuppliersTest.java @@ -0,0 +1,255 @@ +/* + * 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.sdk.util; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import java.util.Arrays; +import java.util.Collections; +import org.apache.beam.sdk.transforms.windowing.BoundedWindow; +import org.apache.beam.sdk.transforms.windowing.GlobalWindow; +import org.apache.beam.sdk.transforms.windowing.IntervalWindow; +import org.apache.beam.sdk.transforms.windowing.PaneInfo; +import org.apache.beam.sdk.transforms.windowing.PaneInfo.Timing; +import org.apache.beam.sdk.values.CausedByDrain; +import org.apache.beam.sdk.values.ValueKind; +import org.apache.beam.sdk.values.WindowedValue; +import org.apache.beam.sdk.values.WindowedValues; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.joda.time.Duration; +import org.joda.time.Instant; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Unit tests for {@link OutputBuilderSupplier} default methods and {@link OutputBuilderSuppliers}. + */ +@RunWith(JUnit4.class) +public class OutputBuilderSuppliersTest { + + private static final Instant TS = new Instant(1_700_000_000_000L); + private static final Instant TS2 = TS.plus(Duration.standardSeconds(10)); + private static final IntervalWindow W1 = + new IntervalWindow(TS, TS.plus(Duration.standardMinutes(1))); + private static final IntervalWindow W2 = + new IntervalWindow( + TS.plus(Duration.standardMinutes(1)), TS.plus(Duration.standardMinutes(2))); + private static final PaneInfo EARLY_PANE = PaneInfo.createPane(false, false, Timing.EARLY, 2, 1); + + private static Context activeSpan(String traceId) { + return Context.root() + .with( + Span.wrap( + SpanContext.create( + traceId, + "ff00000000000041", + TraceFlags.getSampled(), + TraceState.getDefault()))); + } + + @Test + public void testDefaultInterfaceMethodsOnMinimalSupplier() { + WindowedValue template = + WindowedValues.of( + "in", + TS, + W1, + EARLY_PANE, + "rec-1", + 12L, + CausedByDrain.CAUSED_BY_DRAIN, + activeSpan("aa000000000000000000000000000001"), + ValueKind.UPDATE_BEFORE); + + // Override ONLY builder(value) to exercise the default + // build/buildWithTimestamp/buildWindowedValue. + OutputBuilderSupplier minimal = + new OutputBuilderSupplier() { + @Override + public WindowedValues.Builder builder(OutputT value) { + return WindowedValues.builder(template, value); + } + }; + + Context active = activeSpan("bb000000000000000000000000000002"); + try (Scope ignored = Context.root().makeCurrent()) { + WindowedValue built = minimal.build(42); + assertEquals(Integer.valueOf(42), built.getValue()); + assertEquals(TS, built.getTimestamp()); + assertEquals(W1, WindowedValues.singleWindowOrNull(built)); + assertEquals(EARLY_PANE, built.getPaneInfo()); + assertEquals("rec-1", built.getRecordId()); + assertEquals(Long.valueOf(12L), built.getRecordOffset()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, built.causedByDrain()); + assertEquals(ValueKind.UPDATE_BEFORE, built.getValueKind()); + assertNull(built.getOpenTelemetryContext()); + } + + try (Scope ignored = active.makeCurrent()) { + WindowedValue withTs = minimal.buildWithTimestamp("ts-out", TS2); + assertEquals("ts-out", withTs.getValue()); + assertEquals(TS2, withTs.getTimestamp()); + assertSame(active, withTs.getOpenTelemetryContext()); + + WindowedValue win4 = + minimal.buildWindowedValue( + "win4", TS2, Collections.singletonList(W2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + assertEquals("win4", win4.getValue()); + assertEquals(W2, WindowedValues.singleWindowOrNull(win4)); + assertEquals(PaneInfo.ON_TIME_AND_ONLY_FIRING, win4.getPaneInfo()); + assertEquals(ValueKind.UPDATE_BEFORE, win4.getValueKind()); + assertSame(active, win4.getOpenTelemetryContext()); + + WindowedValue win5 = + minimal.buildWindowedValue( + "win5", TS2, Arrays.asList(W1, W2), PaneInfo.NO_FIRING, ValueKind.DELETE); + assertEquals(ValueKind.DELETE, win5.getValueKind()); + assertThat(win5.getWindows(), containsInAnyOrder(W1, W2)); + assertSame(active, win5.getOpenTelemetryContext()); + } + } + + @Test + public void testSupplierForElementAcrossWindowedValueShapes() { + Context templateCtx = activeSpan("aa000000000000000000000000000001"); + Context activeCtx = activeSpan("cc000000000000000000000000000003"); + + WindowedValue[] templates = { + WindowedValues.of( + "gmin", + BoundedWindow.TIMESTAMP_MIN_VALUE, + GlobalWindow.INSTANCE, + EARLY_PANE, + "id-gmin", + 1L, + CausedByDrain.CAUSED_BY_DRAIN, + templateCtx, + ValueKind.DELETE), + WindowedValues.of( + "gts", + TS, + GlobalWindow.INSTANCE, + EARLY_PANE, + "id-gts", + 2L, + CausedByDrain.CAUSED_BY_DRAIN, + templateCtx, + ValueKind.UPDATE_AFTER), + WindowedValues.of( + "single", + TS, + W1, + EARLY_PANE, + "id-s", + 3L, + CausedByDrain.CAUSED_BY_DRAIN, + templateCtx, + ValueKind.UPDATE_BEFORE), + WindowedValues.of( + "multi", + TS, + Arrays.asList(W1, W2), + EARLY_PANE, + "id-m", + 4L, + CausedByDrain.CAUSED_BY_DRAIN, + templateCtx, + ValueKind.DELETE), + WindowedValues.builder() + .setValue("b") + .setTimestamp(TS) + .setWindow(W1) + .setPaneInfo(EARLY_PANE) + .setRecordId("id-b") + .setRecordOffset(5L) + .setCausedByDrain(CausedByDrain.CAUSED_BY_DRAIN) + .setValueKind(ValueKind.UPDATE_BEFORE) + }; + + for (WindowedValue template : templates) { + OutputBuilderSupplier supplier = OutputBuilderSuppliers.supplierForElement(template); + try (Scope ignored = Context.root().makeCurrent()) { + WindowedValue built = supplier.build("out"); + assertEquals("out", built.getValue()); + assertEquals(template.getTimestamp(), built.getTimestamp()); + assertEquals(template.getPaneInfo(), built.getPaneInfo()); + assertEquals(template.getRecordId(), built.getRecordId()); + assertEquals(template.getRecordOffset(), built.getRecordOffset()); + assertEquals(template.causedByDrain(), built.causedByDrain()); + assertEquals(template.getValueKind(), built.getValueKind()); + assertEquals(template.getWindows().size(), built.getWindows().size()); + assertNull(built.getOpenTelemetryContext()); + + WindowedValue<@Nullable String> builtNull = supplier.build(null); + assertNull(builtNull.getValue()); + } + + try (Scope ignored = activeCtx.makeCurrent()) { + WindowedValue withTs = supplier.buildWithTimestamp("ts", TS2); + assertEquals(TS2, withTs.getTimestamp()); + assertEquals(template.getRecordId(), withTs.getRecordId()); + assertSame(activeCtx, withTs.getOpenTelemetryContext()); + + WindowedValue fromBuilder = supplier.builder("via-builder").build(); + assertEquals("via-builder", fromBuilder.getValue()); + assertEquals(template.getRecordId(), fromBuilder.getRecordId()); + assertSame(activeCtx, fromBuilder.getOpenTelemetryContext()); + + WindowedValue explicit4 = + supplier.buildWindowedValue( + "exp4", TS2, Collections.singletonList(W2), PaneInfo.ON_TIME_AND_ONLY_FIRING); + assertEquals(W2, WindowedValues.singleWindowOrNull(explicit4)); + assertEquals(PaneInfo.ON_TIME_AND_ONLY_FIRING, explicit4.getPaneInfo()); + assertEquals(template.getValueKind(), explicit4.getValueKind()); + assertEquals(template.getRecordId(), explicit4.getRecordId()); + assertSame(activeCtx, explicit4.getOpenTelemetryContext()); + + WindowedValue explicit = + supplier.buildWindowedValue( + "exp", TS2, Collections.singletonList(W2), PaneInfo.NO_FIRING, ValueKind.INSERT); + assertEquals(W2, WindowedValues.singleWindowOrNull(explicit)); + assertEquals(ValueKind.INSERT, explicit.getValueKind()); + assertEquals(template.getRecordId(), explicit.getRecordId()); + assertSame(activeCtx, explicit.getOpenTelemetryContext()); + } + } + } + + @Test + public void testSupplierForElementRejectsNullTemplate() { + assertThrows( + NullPointerException.class, () -> OutputBuilderSuppliers.supplierForElement(castNull())); + } + + @SuppressWarnings("nullness") + private static WindowedValue castNull() { + return null; + } +} diff --git a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java index 989fb272c6be..ecdbc9e17b58 100644 --- a/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java +++ b/sdks/java/core/src/test/java/org/apache/beam/sdk/util/WindowedValueTest.java @@ -31,10 +31,17 @@ import io.opentelemetry.context.Scope; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.InputStream; +import java.io.OutputStream; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CoderException; +import org.apache.beam.sdk.coders.CollectionCoder; +import org.apache.beam.sdk.coders.CustomCoder; import org.apache.beam.sdk.coders.InstantCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.CoderProperties; @@ -51,6 +58,7 @@ import org.apache.beam.sdk.values.WindowedValues; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.Iterables; +import org.checkerframework.checker.nullness.qual.Nullable; import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.After; @@ -138,9 +146,9 @@ public void testWindowedValueWithElementMetadataCoder() throws CoderException { Assert.assertEquals(value.getValue(), decodedValue.getValue()); Assert.assertEquals(value.getTimestamp(), decodedValue.getTimestamp()); Assert.assertArrayEquals(value.getWindows().toArray(), decodedValue.getWindows().toArray()); - Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, value.causedByDrain()); - Assert.assertNotNull(value.getOpenTelemetryContext()); - Assert.assertEquals(ValueKind.DELETE, value.getValueKind()); + Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, decodedValue.causedByDrain()); + Assert.assertNotNull(decodedValue.getOpenTelemetryContext()); + Assert.assertEquals(ValueKind.DELETE, decodedValue.getValueKind()); } @Test @@ -253,27 +261,42 @@ public void testSingleWindowedValueInFixedWindow() { } @Test - public void testFullWindowedValueCoderSingleMultiZeroAndChunkedWindows() throws Exception { + public void testFullWindowedValueCoderSingleIntervalWindowAndParity() throws Exception { Instant ts = new Instant(1_700_000_000_000L); IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); - IntervalWindow w2 = - new IntervalWindow( - ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); Coder> intervalCoder = WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); - // Single IntervalWindow round-trip + byte size observer check. WindowedValue single = WindowedValues.of("hello", ts, w1, PaneInfo.NO_FIRING); byte[] singleBytes = CoderUtils.encodeToByteArray(intervalCoder, single); + byte[] singleNestedBytes = + CoderUtils.encodeToByteArray(intervalCoder, single, Coder.Context.NESTED); + + // Byte-for-byte wire parity with legacy InstantCoder + CollectionCoder + PaneInfoCoder + value. + ByteArrayOutputStream expected = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, expected); + CollectionCoder.of(IntervalWindow.getCoder()).encode(Collections.singletonList(w1), expected); + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, expected); + StringUtf8Coder.of().encode("hello", expected); + Assert.assertArrayEquals(expected.toByteArray(), singleNestedBytes); + WindowedValue decodedSingle = CoderUtils.decodeFromByteArray(intervalCoder, singleBytes); assertThat(decodedSingle, equalTo(single)); assertThat(decodedSingle, instanceOf(WindowedValues.SingleWindowedValue.class)); - Assert.assertEquals( - CoderUtils.encodeToByteArray(intervalCoder, single, Coder.Context.NESTED).length, - measureByteSize(intervalCoder, single)); + Assert.assertEquals(singleNestedBytes.length, measureByteSize(intervalCoder, single)); + } + + @Test + public void testFullWindowedValueCoderMultipleWindows() throws Exception { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); - // Multiple windows round-trip + byte size observer check. WindowedValue multi = WindowedValues.of("world", ts, Arrays.asList(w1, w2), PaneInfo.ON_TIME_AND_ONLY_FIRING); byte[] multiBytes = CoderUtils.encodeToByteArray(intervalCoder, multi); @@ -282,20 +305,111 @@ public void testFullWindowedValueCoderSingleMultiZeroAndChunkedWindows() throws Assert.assertEquals( CoderUtils.encodeToByteArray(intervalCoder, multi, Coder.Context.NESTED).length, measureByteSize(intervalCoder, multi)); + } - // Single GlobalWindow round-trip + byte size observer check. + @Test + public void testFullWindowedValueCoderSingleGlobalWindowAndParity() throws Exception { Coder> globalCoder = WindowedValues.getFullCoder(StringUtf8Coder.of(), GlobalWindow.Coder.INSTANCE); WindowedValue globalVal = WindowedValues.valueInGlobalWindow("g"); byte[] globalBytes = CoderUtils.encodeToByteArray(globalCoder, globalVal); + byte[] globalNestedBytes = + CoderUtils.encodeToByteArray(globalCoder, globalVal, Coder.Context.NESTED); + + ByteArrayOutputStream expected = new ByteArrayOutputStream(); + InstantCoder.of().encode(BoundedWindow.TIMESTAMP_MIN_VALUE, expected); + CollectionCoder.of(GlobalWindow.Coder.INSTANCE) + .encode(Collections.singletonList(GlobalWindow.INSTANCE), expected); + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, expected); + StringUtf8Coder.of().encode("g", expected); + Assert.assertArrayEquals(expected.toByteArray(), globalNestedBytes); + WindowedValue decodedGlobal = CoderUtils.decodeFromByteArray(globalCoder, globalBytes); assertThat(decodedGlobal, equalTo(globalVal)); Assert.assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, decodedGlobal.getTimestamp()); + Assert.assertEquals(globalNestedBytes.length, measureByteSize(globalCoder, globalVal)); + } + + @Test + public void testFullWindowedValueCoderCustomNonSingleWindowedValueFallback() throws Exception { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); + + WindowedValue delegate = WindowedValues.of("custom", ts, w1, PaneInfo.NO_FIRING); + WindowedValue nonSingleWrapper = new CustomWindowedValue<>(delegate); + + Assert.assertNull(WindowedValues.singleWindowOrNull(nonSingleWrapper)); + byte[] wrappedBytes = CoderUtils.encodeToByteArray(intervalCoder, nonSingleWrapper); + byte[] directBytes = CoderUtils.encodeToByteArray(intervalCoder, delegate); + Assert.assertArrayEquals(directBytes, wrappedBytes); Assert.assertEquals( - CoderUtils.encodeToByteArray(globalCoder, globalVal, Coder.Context.NESTED).length, - measureByteSize(globalCoder, globalVal)); + measureByteSize(intervalCoder, delegate), measureByteSize(intervalCoder, nonSingleWrapper)); + } + + @Test + public void testFullWindowedValueCoderSingleWindowWithMetadataSupported() throws Exception { + WindowedValues.WindowedValueCoder.setMetadataSupported(); + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); + + // Round-trip with active OpenTelemetry span context. + Context activeContext = newActiveSpanContext("ff000000000000000000000000000041"); + WindowedValue withMeta = + WindowedValues.of( + "traced", + ts, + w1, + PaneInfo.ON_TIME_AND_ONLY_FIRING, + null, + null, + CausedByDrain.CAUSED_BY_DRAIN, + activeContext, + ValueKind.UPDATE_BEFORE); + WindowedValue decodedWithMeta = + CoderUtils.decodeFromByteArray( + intervalCoder, CoderUtils.encodeToByteArray(intervalCoder, withMeta)); + assertThat(decodedWithMeta, instanceOf(WindowedValues.SingleWindowedValue.class)); + Assert.assertEquals("traced", decodedWithMeta.getValue()); + Assert.assertEquals(ts, decodedWithMeta.getTimestamp()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(decodedWithMeta)); + Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, decodedWithMeta.causedByDrain()); + Assert.assertEquals(ValueKind.UPDATE_BEFORE, decodedWithMeta.getValueKind()); + Assert.assertNotNull(decodedWithMeta.getOpenTelemetryContext()); + Assert.assertEquals( + "ff000000000000000000000000000041", + Span.fromContext(decodedWithMeta.getOpenTelemetryContext()).getSpanContext().getTraceId()); + + // Round-trip without active context keeps getOpenTelemetryContext() normalized to null. + WindowedValue noTrace = + WindowedValues.of( + "plain", + ts, + w1, + PaneInfo.NO_FIRING, + null, + null, + CausedByDrain.NORMAL, + null, + ValueKind.DELETE); + WindowedValue decodedNoTrace = + CoderUtils.decodeFromByteArray( + intervalCoder, CoderUtils.encodeToByteArray(intervalCoder, noTrace)); + Assert.assertEquals("plain", decodedNoTrace.getValue()); + Assert.assertEquals(CausedByDrain.NORMAL, decodedNoTrace.causedByDrain()); + Assert.assertEquals(ValueKind.DELETE, decodedNoTrace.getValueKind()); + Assert.assertNull(decodedNoTrace.getOpenTelemetryContext()); + } + + @Test + public void testFullWindowedValueCoderZeroWindowsLegacyStream() throws Exception { + Instant ts = new Instant(1_700_000_000_000L); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); - // Zero windows stream (compatibility with legacy no-window encoding). ByteArrayOutputStream zeroWinOut = new ByteArrayOutputStream(); InstantCoder.of().encode(ts, zeroWinOut); zeroWinOut.write(new byte[] {0, 0, 0, 0}); // numWindows == 0 @@ -305,23 +419,62 @@ public void testFullWindowedValueCoderSingleMultiZeroAndChunkedWindows() throws intervalCoder.decode(new ByteArrayInputStream(zeroWinOut.toByteArray())); assertThat(decodedZero.getValue(), equalTo("empty")); assertThat(decodedZero.getWindows(), equalTo(Collections.emptyList())); + } + + @Test + public void testFullWindowedValueCoderUnknownSizeChunkedWindows() throws Exception { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); - // Unknown-size chunked windows stream (-1 prefix, VarInt count=2, terminator=0). - ByteArrayOutputStream chunkedOut = new ByteArrayOutputStream(); - InstantCoder.of().encode(ts, chunkedOut); - chunkedOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); - VarInt.encode(2L, chunkedOut); - IntervalWindow.getCoder().encode(w1, chunkedOut); - IntervalWindow.getCoder().encode(w2, chunkedOut); - VarInt.encode(0L, chunkedOut); - PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, chunkedOut); - StringUtf8Coder.of().encode("chunked", chunkedOut); - WindowedValue decodedChunked = - intervalCoder.decode(new ByteArrayInputStream(chunkedOut.toByteArray())); - assertThat(decodedChunked.getValue(), equalTo("chunked")); - assertThat(decodedChunked.getWindows(), containsInAnyOrder(w1, w2)); - - // Non-zero negative terminator in unknown-size stream throws IllegalStateException. + // Multi-chunk unknown-size stream (-1, chunk 1: w1, chunk 2: w2, terminator: 0). + ByteArrayOutputStream multiChunkOut = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, multiChunkOut); + multiChunkOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + VarInt.encode(1L, multiChunkOut); + IntervalWindow.getCoder().encode(w1, multiChunkOut); + VarInt.encode(1L, multiChunkOut); + IntervalWindow.getCoder().encode(w2, multiChunkOut); + VarInt.encode(0L, multiChunkOut); + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, multiChunkOut); + StringUtf8Coder.of().encode("multi-chunk", multiChunkOut); + WindowedValue decodedMulti = + intervalCoder.decode(new ByteArrayInputStream(multiChunkOut.toByteArray())); + assertThat(decodedMulti.getValue(), equalTo("multi-chunk")); + assertThat(decodedMulti.getWindows(), containsInAnyOrder(w1, w2)); + + // Single-window unknown-size stream (-1, count=1, w1, terminator=0) -> SingleWindowedValue. + ByteArrayOutputStream singleChunkOut = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, singleChunkOut); + singleChunkOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + VarInt.encode(1L, singleChunkOut); + IntervalWindow.getCoder().encode(w1, singleChunkOut); + VarInt.encode(0L, singleChunkOut); + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, singleChunkOut); + StringUtf8Coder.of().encode("single-chunk", singleChunkOut); + WindowedValue decodedSingle = + intervalCoder.decode(new ByteArrayInputStream(singleChunkOut.toByteArray())); + assertThat(decodedSingle, instanceOf(WindowedValues.SingleWindowedValue.class)); + assertThat(decodedSingle.getValue(), equalTo("single-chunk")); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(decodedSingle)); + + // Empty unknown-size stream (-1, terminator=0). + ByteArrayOutputStream emptyChunkOut = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, emptyChunkOut); + emptyChunkOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + VarInt.encode(0L, emptyChunkOut); + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, emptyChunkOut); + StringUtf8Coder.of().encode("empty-chunk", emptyChunkOut); + WindowedValue decodedEmpty = + intervalCoder.decode(new ByteArrayInputStream(emptyChunkOut.toByteArray())); + assertThat(decodedEmpty.getValue(), equalTo("empty-chunk")); + assertThat(decodedEmpty.getWindows(), equalTo(Collections.emptyList())); + + // Non-zero negative terminator throws IllegalStateException. ByteArrayOutputStream badTermOut = new ByteArrayOutputStream(); InstantCoder.of().encode(ts, badTermOut); badTermOut.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); @@ -329,21 +482,107 @@ public void testFullWindowedValueCoderSingleMultiZeroAndChunkedWindows() throws Assert.assertThrows( IllegalStateException.class, () -> intervalCoder.decode(new ByteArrayInputStream(badTermOut.toByteArray()))); + } + + @Test + public void testFullWindowedValueCoderTruncatedStreamsThrowEof() throws Exception { + Instant ts = new Instant(1_700_000_000_000L); + Coder> intervalCoder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), IntervalWindow.getCoder()); - // Truncated IntervalWindowCoder stream throws CoderException. - byte[] encodedInterval = CoderUtils.encodeToByteArray(IntervalWindow.getCoder(), w1); - byte[] truncated = Arrays.copyOf(encodedInterval, 8); // timestamp only, missing duration + byte[] encodedTs = CoderUtils.encodeToByteArray(InstantCoder.of(), ts); + for (int extraBytes = 0; extraBytes <= 3; extraBytes++) { + byte[] truncated = new byte[encodedTs.length + extraBytes]; + System.arraycopy(encodedTs, 0, truncated, 0, encodedTs.length); + Assert.assertThrows( + EOFException.class, () -> intervalCoder.decode(new ByteArrayInputStream(truncated))); + IllegalArgumentException wrapped = + Assert.assertThrows( + IllegalArgumentException.class, + () -> CoderUtils.decodeFromByteArray(intervalCoder, truncated)); + assertThat(wrapped.getCause(), instanceOf(EOFException.class)); + } + + // Truncated unknown-size chunk stream (missing VarInt chunk count after -1 header). + ByteArrayOutputStream truncatedChunk = new ByteArrayOutputStream(); + InstantCoder.of().encode(ts, truncatedChunk); + truncatedChunk.write(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + byte[] truncatedChunkBytes = truncatedChunk.toByteArray(); Assert.assertThrows( - CoderException.class, - () -> CoderUtils.decodeFromByteArray(IntervalWindow.getCoder(), truncated)); + EOFException.class, + () -> intervalCoder.decode(new ByteArrayInputStream(truncatedChunkBytes))); + } + + @Test + public void testFullWindowedValueCoderNullDecodedSingleWindowThrowsNpe() throws Exception { + Coder nullWindowCoder = + new CustomCoder() { + @Override + public void encode(BoundedWindow value, OutputStream outStream) {} + + @Override + @SuppressWarnings("nullness") + public BoundedWindow decode(InputStream inStream) { + return null; + } + }; + Coder> coder = + WindowedValues.getFullCoder(StringUtf8Coder.of(), nullWindowCoder); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + InstantCoder.of().encode(new Instant(1_700_000_000_000L), out); + out.write(new byte[] {0, 0, 0, 1}); // numWindows == 1 + PaneInfoCoder.INSTANCE.encode(PaneInfo.NO_FIRING, out); + StringUtf8Coder.of().encode("x", out); + NullPointerException ex = + Assert.assertThrows( + NullPointerException.class, + () -> coder.decode(new ByteArrayInputStream(out.toByteArray()))); + assertThat(ex.getMessage(), equalTo("Decoded single window must not be null")); } @Test - public void testOfWithCurrentContextOmitsRootAndPreservesActiveContext() { - WindowedValue template = WindowedValues.valueInGlobalWindow("in"); + public void testOfWithCurrentContextOmitsRootAndReplacesTemplateContext() { + Context templateContext = newActiveSpanContext("aa000000000000000000000000000001"); + Context activeContext = newActiveSpanContext("ff000000000000000000000000000041"); + Instant ts = new Instant(1_700_000_000_000L); + Instant ts2 = ts.plus(Duration.standardSeconds(5)); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + IntervalWindow w2 = + new IntervalWindow( + ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); + PaneInfo early = PaneInfo.createPane(false, false, Timing.EARLY, 3, 1); + + WindowedValue singleTemplate = + WindowedValues.of( + "in", + ts, + w1, + early, + "rid-1", + 42L, + CausedByDrain.CAUSED_BY_DRAIN, + templateContext, + ValueKind.DELETE); + try (Scope rootScope = Context.root().makeCurrent()) { - WindowedValue derived = WindowedValues.ofWithCurrentContext(template, "out"); + WindowedValue derived = WindowedValues.ofWithCurrentContext(singleTemplate, "out"); + Assert.assertEquals("out", derived.getValue()); + Assert.assertEquals(ts, derived.getTimestamp()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(derived)); + Assert.assertEquals(early, derived.getPaneInfo()); + Assert.assertEquals("rid-1", derived.getRecordId()); + Assert.assertEquals(Long.valueOf(42L), derived.getRecordOffset()); + Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, derived.causedByDrain()); + Assert.assertEquals(ValueKind.DELETE, derived.getValueKind()); + // Template's active OTel context must NOT leak when Context.root() is current. Assert.assertNull(derived.getOpenTelemetryContext()); + + WindowedValue<@Nullable String> withNullValue = + WindowedValues.ofWithCurrentContext(singleTemplate, null, ts2); + Assert.assertNull(withNullValue.getValue()); + Assert.assertEquals(ts2, withNullValue.getTimestamp()); + Assert.assertNull(withNullValue.getOpenTelemetryContext()); + WindowedValue built = WindowedValues.builder() .setValue("b") @@ -354,75 +593,264 @@ public void testOfWithCurrentContextOmitsRootAndPreservesActiveContext() { Assert.assertNull(built.getOpenTelemetryContext()); } - Context activeContext = - Context.root() - .with( - Span.wrap( - SpanContext.create( - "ff000000000000000000000000000041", - "ff00000000000041", - TraceFlags.getSampled(), - TraceState.getDefault()))); try (Scope activeScope = activeContext.makeCurrent()) { - WindowedValue derived = WindowedValues.ofWithCurrentContext(template, "out"); + WindowedValue derived = WindowedValues.ofWithCurrentContext(singleTemplate, "out"); Assert.assertSame(activeContext, derived.getOpenTelemetryContext()); + + WindowedValue derivedWithTs = + WindowedValues.ofWithCurrentContext(singleTemplate, "out2", ts2); + Assert.assertSame(activeContext, derivedWithTs.getOpenTelemetryContext()); + Assert.assertEquals(ts2, derivedWithTs.getTimestamp()); + + WindowedValue explicit5Arg = + WindowedValues.ofWithCurrentContext( + singleTemplate, "out5", ts2, Collections.singletonList(w2), PaneInfo.NO_FIRING); + Assert.assertSame(activeContext, explicit5Arg.getOpenTelemetryContext()); + Assert.assertEquals(w2, WindowedValues.singleWindowOrNull(explicit5Arg)); + Assert.assertEquals("rid-1", explicit5Arg.getRecordId()); + Assert.assertEquals(Long.valueOf(42L), explicit5Arg.getRecordOffset()); + Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, explicit5Arg.causedByDrain()); + Assert.assertEquals(ValueKind.DELETE, explicit5Arg.getValueKind()); + + WindowedValue explicit6Arg = + WindowedValues.ofWithCurrentContext( + singleTemplate, + "out6", + ts2, + Arrays.asList(w1, w2), + PaneInfo.ON_TIME_AND_ONLY_FIRING, + ValueKind.UPDATE_AFTER); + Assert.assertSame(activeContext, explicit6Arg.getOpenTelemetryContext()); + Assert.assertEquals(ValueKind.UPDATE_AFTER, explicit6Arg.getValueKind()); + Assert.assertEquals("rid-1", explicit6Arg.getRecordId()); + assertThat(explicit6Arg.getWindows(), containsInAnyOrder(w1, w2)); + + WindowedValue direct8ArgSingle = + WindowedValues.ofWithCurrentContext( + "d1", + ts2, + w1, + early, + "rid-8", + 7L, + CausedByDrain.CAUSED_BY_DRAIN, + ValueKind.UPDATE_BEFORE); + Assert.assertSame(activeContext, direct8ArgSingle.getOpenTelemetryContext()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(direct8ArgSingle)); + Assert.assertEquals(ValueKind.UPDATE_BEFORE, direct8ArgSingle.getValueKind()); + + WindowedValue direct8ArgMulti = + WindowedValues.ofWithCurrentContext( + "d2", + ts2, + Arrays.asList(w1, w2), + early, + null, + null, + CausedByDrain.NORMAL, + ValueKind.INSERT); + Assert.assertSame(activeContext, direct8ArgMulti.getOpenTelemetryContext()); + assertThat(direct8ArgMulti.getWindows(), containsInAnyOrder(w1, w2)); + } + + // WindowedValues.withValue preserves template's own context (contrast with + // ofWithCurrentContext). + try (Scope rootScope = Context.root().makeCurrent()) { + WindowedValue preserved = WindowedValues.withValue(singleTemplate, 99); + Assert.assertSame(templateContext, preserved.getOpenTelemetryContext()); + Assert.assertEquals(Integer.valueOf(99), preserved.getValue()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(preserved)); + + WindowedValue customWrapper = new CustomWindowedValue<>(singleTemplate); + WindowedValue customPreserved = WindowedValues.withValue(customWrapper, 100); + Assert.assertSame(templateContext, customPreserved.getOpenTelemetryContext()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(customPreserved)); } } @Test - public void testSingleWindowOrNullAndOfWithCurrentContextFastPaths() { + public void testSingleWindowOrNullAndGlobalTimestampTransitions() { Instant ts = new Instant(1_700_000_000_000L); IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); IntervalWindow w2 = new IntervalWindow( ts.plus(Duration.standardMinutes(1)), ts.plus(Duration.standardMinutes(2))); - PaneInfo early = PaneInfo.createPane(true, false, Timing.EARLY, 3, 1); - // ValueInGlobalWindow WindowedValue gMin = WindowedValues.valueInGlobalWindow("g0"); Assert.assertEquals(GlobalWindow.INSTANCE, WindowedValues.singleWindowOrNull(gMin)); - WindowedValue gMinDerived = WindowedValues.ofWithCurrentContext(gMin, "g1", ts); - Assert.assertEquals(ts, gMinDerived.getTimestamp()); - Assert.assertEquals(GlobalWindow.INSTANCE, WindowedValues.singleWindowOrNull(gMinDerived)); - WindowedValue gMinBackToMin = - WindowedValues.ofWithCurrentContext(gMinDerived, "g2", BoundedWindow.TIMESTAMP_MIN_VALUE); - Assert.assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, gMinBackToMin.getTimestamp()); - - // TimestampedValueInSingleWindow with full metadata - WindowedValue single = - WindowedValues.of( - "s0", ts, w1, early, "rid", 42L, CausedByDrain.CAUSED_BY_DRAIN, null, ValueKind.DELETE); - Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(single)); - WindowedValue singleCopy = WindowedValues.ofWithCurrentContext(single, "s1"); - Assert.assertEquals("s1", singleCopy.getValue()); - Assert.assertEquals(ts, singleCopy.getTimestamp()); - Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(singleCopy)); - Assert.assertEquals(early, singleCopy.getPaneInfo()); - Assert.assertEquals("rid", singleCopy.getRecordId()); - Assert.assertEquals(Long.valueOf(42L), singleCopy.getRecordOffset()); - Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, singleCopy.causedByDrain()); - Assert.assertEquals(ValueKind.DELETE, singleCopy.getValueKind()); - - // TimestampedValueInMultipleWindows - WindowedValue multi = WindowedValues.of("m0", ts, Arrays.asList(w1, w2), early); + WindowedValue gTs = WindowedValues.ofWithCurrentContext(gMin, "g1", ts); + Assert.assertEquals(ts, gTs.getTimestamp()); + Assert.assertEquals(GlobalWindow.INSTANCE, WindowedValues.singleWindowOrNull(gTs)); + // Timestamp with equal millis but distinct Instant object transitions back to MIN + // representation. + WindowedValue gBackToMin = + WindowedValues.ofWithCurrentContext( + gTs, "g2", new Instant(BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis())); + Assert.assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, gBackToMin.getTimestamp()); + Assert.assertEquals(GlobalWindow.INSTANCE, WindowedValues.singleWindowOrNull(gBackToMin)); + + WindowedValue multi = + WindowedValues.of("m0", ts, Arrays.asList(w1, w2), PaneInfo.NO_FIRING); Assert.assertNull(WindowedValues.singleWindowOrNull(multi)); - WindowedValue multiDerived = WindowedValues.ofWithCurrentContext(multi, "m1"); - Assert.assertEquals("m1", multiDerived.getValue()); - assertThat(multiDerived.getWindows(), containsInAnyOrder(w1, w2)); + WindowedValue multiCopy = WindowedValues.ofWithCurrentContext(multi, "m1"); + assertThat(multiCopy.getWindows(), containsInAnyOrder(w1, w2)); - // 6-arg ofWithCurrentContext with ValueKind override - WindowedValue kindOverride = - WindowedValues.ofWithCurrentContext( - single, - "k", - ts.plus(Duration.millis(10)), - Collections.singletonList(w2), - early, - ValueKind.UPDATE_AFTER); - Assert.assertEquals(ValueKind.UPDATE_AFTER, kindOverride.getValueKind()); - Assert.assertEquals(w2, WindowedValues.singleWindowOrNull(kindOverride)); - Assert.assertEquals("rid", kindOverride.getRecordId()); - Assert.assertEquals(Long.valueOf(42L), kindOverride.getRecordOffset()); + // Builder template (single-window vs unset vs multi-window). + WindowedValues.Builder singleBuilder = + WindowedValues.builder() + .setValue("b") + .setTimestamp(ts) + .setWindow(w1) + .setPaneInfo(PaneInfo.NO_FIRING); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(singleBuilder)); + WindowedValue fromBuilder = WindowedValues.ofWithCurrentContext(singleBuilder, 123); + Assert.assertEquals(Integer.valueOf(123), fromBuilder.getValue()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(fromBuilder)); + assertThat(singleBuilder.getWindows(), containsInAnyOrder(w1)); + Assert.assertThrows( + UnsupportedOperationException.class, + () -> ((Collection) singleBuilder.getWindows()).add(w2)); + + WindowedValues.Builder emptyBuilder = WindowedValues.builder(); + Assert.assertNull(WindowedValues.singleWindowOrNull(emptyBuilder)); + + // Non-List singleton collection (Set) fallback in WindowedValues.of(). + WindowedValue fromSet = + WindowedValues.of("set", ts, Collections.singleton(w1), PaneInfo.NO_FIRING); + assertThat(fromSet, instanceOf(WindowedValues.SingleWindowedValue.class)); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(fromSet)); + + // Null windows throws IllegalArgumentException. + Assert.assertThrows( + IllegalArgumentException.class, + () -> WindowedValues.of("x", ts, (Collection) null, PaneInfo.NO_FIRING)); + + // Empty-window template decoded via zero-window stream throws IllegalArgumentException. + WindowedValue emptyTemplate = + new CustomWindowedValue(gMin) { + @Override + public Collection getWindows() { + return Collections.emptyList(); + } + }; + Assert.assertThrows( + IllegalArgumentException.class, + () -> WindowedValues.ofWithCurrentContext(emptyTemplate, "out")); + } + + @Test + public void testBuilderWithTemplateDoesNotReadTemplateValue() { + Instant ts = new Instant(1_700_000_000_000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.standardMinutes(1))); + WindowedValue base = + WindowedValues.of( + "secret", + ts, + w1, + PaneInfo.ON_TIME_AND_ONLY_FIRING, + "rid", + 9L, + CausedByDrain.CAUSED_BY_DRAIN, + null, + ValueKind.UPDATE_BEFORE); + AtomicBoolean valueRead = new AtomicBoolean(false); + WindowedValue guardingTemplate = + new CustomWindowedValue(base) { + @Override + public String getValue() { + valueRead.set(true); + throw new AssertionError("template.getValue() must not be called"); + } + }; + + WindowedValue built = WindowedValues.builder(guardingTemplate, 77).build(); + Assert.assertFalse(valueRead.get()); + Assert.assertEquals(Integer.valueOf(77), built.getValue()); + Assert.assertEquals(ts, built.getTimestamp()); + Assert.assertEquals(w1, WindowedValues.singleWindowOrNull(built)); + Assert.assertEquals("rid", built.getRecordId()); + Assert.assertEquals(Long.valueOf(9L), built.getRecordOffset()); + Assert.assertEquals(CausedByDrain.CAUSED_BY_DRAIN, built.causedByDrain()); + Assert.assertEquals(ValueKind.UPDATE_BEFORE, built.getValueKind()); + + // Null new value on Builder. + WindowedValue<@Nullable Integer> builtNull = + WindowedValues.builder(guardingTemplate, (Integer) null).build(); + Assert.assertNull(builtNull.getValue()); + } + + private static Context newActiveSpanContext(String traceId) { + return Context.root() + .with( + Span.wrap( + SpanContext.create( + traceId, + "ff00000000000041", + TraceFlags.getSampled(), + TraceState.getDefault()))); + } + + private static class CustomWindowedValue implements WindowedValue { + private final WindowedValue delegate; + + CustomWindowedValue(WindowedValue delegate) { + this.delegate = delegate; + } + + @Override + public T getValue() { + return delegate.getValue(); + } + + @Override + public Instant getTimestamp() { + return delegate.getTimestamp(); + } + + @Override + public Collection getWindows() { + return delegate.getWindows(); + } + + @Override + public PaneInfo getPaneInfo() { + return delegate.getPaneInfo(); + } + + @Override + public @Nullable String getRecordId() { + return delegate.getRecordId(); + } + + @Override + public @Nullable Context getOpenTelemetryContext() { + return delegate.getOpenTelemetryContext(); + } + + @Override + public @Nullable Long getRecordOffset() { + return delegate.getRecordOffset(); + } + + @Override + public CausedByDrain causedByDrain() { + return delegate.causedByDrain(); + } + + @Override + public ValueKind getValueKind() { + return delegate.getValueKind(); + } + + @Override + public Iterable> explodeWindows() { + return delegate.explodeWindows(); + } + + @Override + public WindowedValue withValue(OtherT value) { + return delegate.withValue(value); + } } private static long measureByteSize(Coder coder, T value) throws Exception { diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java index da613ac3ce51..23d4a73639a9 100644 --- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java +++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java @@ -607,11 +607,17 @@ private void processElementForWindowObservingParDo(WindowedValue elem) { currentElement = elem; causedByDrain = currentElement.causedByDrain(); try { - Iterator windowIterator = - (Iterator) elem.getWindows().iterator(); - while (windowIterator.hasNext()) { - currentWindow = windowIterator.next(); + @Nullable BoundedWindow singleWindow = WindowedValues.singleWindowOrNull(elem); + if (singleWindow != null) { + currentWindow = singleWindow; doFnInvoker.invokeProcessElement(processContext); + } else { + Iterator windowIterator = + (Iterator) elem.getWindows().iterator(); + while (windowIterator.hasNext()) { + currentWindow = windowIterator.next(); + doFnInvoker.invokeProcessElement(processContext); + } } } finally { currentElement = null; @@ -1568,31 +1574,60 @@ public org.apache.beam.sdk.state.Timer get(String dynamicTimerTag) { } } - @SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected + private static final long MIN_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MIN_VALUE.getMillis(); + private static final long MAX_TIMESTAMP_MILLIS = BoundedWindow.TIMESTAMP_MAX_VALUE.getMillis(); + private void checkTimestamp(Instant timestamp) { - Instant lowerBound; - try { - lowerBound = currentElement.getTimestamp().minus(doFn.getAllowedTimestampSkew()); - } catch (ArithmeticException e) { - lowerBound = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - - if (timestamp.isBefore(lowerBound) || timestamp.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - throw new IllegalArgumentException( - String.format( - "Cannot output with timestamp %s. Output timestamps must be no earlier than the " - + "timestamp of the current input (%s) minus the allowed skew (%s) and no later " - + "than %s. See the DoFn#getAllowedTimestampSkew() Javadoc for details on " - + "changing the allowed skew.", - timestamp, - currentElement.getTimestamp(), - doFn.getAllowedTimestampSkew().getMillis() >= Integer.MAX_VALUE - ? doFn.getAllowedTimestampSkew() - : PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod()), - BoundedWindow.TIMESTAMP_MAX_VALUE)); + checkOutputTimestamp(currentElement.getTimestamp(), timestamp, false); + } + + @SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected + private void checkOutputTimestamp(Instant baseTimestamp, Instant timestamp, boolean isTimer) { + long inputMillis = baseTimestamp.getMillis(); + long skewMillis = doFn.getAllowedTimestampSkew().getMillis(); + long lowerBoundMillis = inputMillis - skewMillis; + if (skewMillis == Long.MIN_VALUE + || ((inputMillis ^ skewMillis) & (inputMillis ^ lowerBoundMillis)) < 0) { + lowerBoundMillis = MIN_TIMESTAMP_MILLIS; + } + long outputMillis = timestamp.getMillis(); + if (outputMillis < lowerBoundMillis || outputMillis > MAX_TIMESTAMP_MILLIS) { + throwInvalidTimestamp(baseTimestamp, timestamp, isTimer); } } + @SuppressWarnings("deprecation") // Allowed Skew is deprecated for users, but must be respected + private void throwInvalidTimestamp(Instant baseTimestamp, Instant timestamp, boolean isTimer) { + Duration allowedSkew = doFn.getAllowedTimestampSkew(); + throw new IllegalArgumentException( + String.format( + "Cannot output with timestamp %s. Output timestamps must be no earlier than the " + + "timestamp of the %s (%s) minus the allowed skew (%s) and no later " + + "than %s. See the DoFn#getAllowedTimestampSkew() Javadoc for details on " + + "changing the allowed skew.", + timestamp, + isTimer ? "timer" : "current input", + baseTimestamp, + allowedSkew.getMillis() >= Integer.MAX_VALUE + ? allowedSkew + : PeriodFormat.getDefault().print(allowedSkew.toPeriod()), + BoundedWindow.TIMESTAMP_MAX_VALUE)); + } + + private void emitToConsumer( + TupleTag tag, + @Nullable FnDataReceiver> consumer, + WindowedValue windowedValue) { + if (consumer == null) { + throw unknownOutputTag(tag); + } + outputTo(consumer, windowedValue); + } + + private static IllegalArgumentException unknownOutputTag(TupleTag tag) { + return new IllegalArgumentException(String.format("Unknown output tag %s", tag)); + } + private class StartBundleArgumentProvider extends BaseArgumentProvider { private class Context extends DoFn.StartBundleContext { Context() { @@ -1705,15 +1740,7 @@ private class WindowObservingProcessBundleContext @Override public OutputBuilder builder(OutputT value) { - return WindowedValues.builder() - .setValue(value) - .setTimestamp(currentElement.getTimestamp()) - .setPaneInfo(currentElement.getPaneInfo()) - .setWindows(currentElement.getWindows()) - .setRecordOffset(currentElement.getRecordOffset()) - .setRecordId(currentElement.getRecordId()) - .setCausedByDrain(currentElement.causedByDrain()) - .setValueKind(currentElement.getValueKind()) + return WindowedValues.builder(currentElement, value) .setReceiver(windowedValue -> outputTo(mainOutputConsumer, windowedValue)); } @@ -1921,6 +1948,20 @@ public void outputWindowedValue( currentElement, output, timestamp, windows, paneInfo)); } + @Override + public void outputWindowedValue( + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + checkTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + currentElement, output, timestamp, windows, paneInfo, valueKind)); + } + @Override public void outputWithTimestamp(TupleTag tag, T output, Instant timestamp) { checkTimestamp(timestamp); @@ -1929,10 +1970,13 @@ public void outputWithTimestamp(TupleTag tag, T output, Instant timestamp if (consumer == null) { throw new IllegalArgumentException(String.format("Unknown output tag %s", tag)); } + @Nullable BoundedWindow singleWindow = WindowedValues.singleWindowOrNull(currentElement); outputTo( consumer, - WindowedValues.of( - output, timestamp, currentElement.getWindows(), currentElement.getPaneInfo())); + singleWindow != null + ? WindowedValues.of(output, timestamp, singleWindow, currentElement.getPaneInfo()) + : WindowedValues.of( + output, timestamp, currentElement.getWindows(), currentElement.getPaneInfo())); } @Override @@ -2113,24 +2157,61 @@ public void output(OutputT output) { @Override public void output(Row value) { - ProcessBundleContextBase.this.outputWindowedValue( + outputTo( + mainOutputConsumer, WindowedValues.ofWithCurrentContext( currentElement, fromRowFunction.apply(value))); } @Override public void outputWithTimestamp(Row value, Instant timestamp) { - ProcessBundleContextBase.this.outputWindowedValue( + outputTo( + mainOutputConsumer, WindowedValues.ofWithCurrentContext( currentElement, fromRowFunction.apply(value), timestamp)); } + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + currentElement, + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo)); + } + + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + currentElement, + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo, + valueKind)); + } + @Override public OutputBuilder builder(Row value) { return WindowedValues.builder(currentElement, value) .setReceiver( windowedRow -> - ProcessBundleContextBase.this.outputWindowedValue( + outputTo( + mainOutputConsumer, windowedRow.withValue( fromRowFunction.apply(windowedRow.getValue())))); } @@ -2151,6 +2232,10 @@ public OutputReceiver outputRowReceiver(DoFn doFn) { private final Map, OutputReceiver> taggedOutputReceivers = new HashMap<>(); private final Map, OutputReceiver> taggedRowReceivers = new HashMap<>(); + private FnDataReceiver> resolveConsumer(TupleTag tag) { + return (FnDataReceiver) localNameToConsumer.get(tag.getId()); + } + private OutputReceiver createTaggedOutputReceiver(TupleTag tag) { // Note that it is important that we use the non-tag versions here when using the main // output tag for performance reasons and we also rely on it for the splittable DoFn @@ -2158,25 +2243,54 @@ private OutputReceiver createTaggedOutputReceiver(TupleTag tag) { if (tag == null || mainOutputTag.equals(tag)) { return (OutputReceiver) ProcessBundleContextBase.this; } + // localNameToConsumer is immutable after construction; resolve once per tag. + final @Nullable FnDataReceiver> consumer = resolveConsumer(tag); return new OutputReceiver() { @Override public void output(T value) { - ProcessBundleContextBase.this.outputWindowedValue( - tag, WindowedValues.ofWithCurrentContext(currentElement, value)); + emitToConsumer( + tag, consumer, WindowedValues.ofWithCurrentContext(currentElement, value)); } @Override public void outputWithTimestamp(T value, Instant timestamp) { - ProcessBundleContextBase.this.outputWindowedValue( - tag, WindowedValues.ofWithCurrentContext(currentElement, value, timestamp)); + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext(currentElement, value, timestamp)); + } + + @Override + public void outputWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + currentElement, value, timestamp, windows, paneInfo)); + } + + @Override + public void outputWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + currentElement, value, timestamp, windows, paneInfo, valueKind)); } @Override public OutputBuilder builder(T value) { return WindowedValues.builder(currentElement, value) - .setReceiver( - windowedValue -> - ProcessBundleContextBase.this.outputWindowedValue(tag, windowedValue)); + .setReceiver(windowedValue -> emitToConsumer(tag, consumer, windowedValue)); } }; } @@ -2199,33 +2313,74 @@ private OutputReceiver createTaggedRowReceiver(TupleTag tag) { outputCoder instanceof SchemaCoder, "Output with tag %s must have a schema in order to call getRowReceiver", tag); + // localNameToConsumer is immutable after construction; resolve once per tag. + final @Nullable FnDataReceiver> consumer = resolveConsumer(tag); return new OutputReceiver() { - private SerializableFunction fromRowFunction = - ((SchemaCoder) outputCoder).getFromRowFunction(); + private final SerializableFunction fromRowFunction = + ((SchemaCoder) outputCoder).getFromRowFunction(); @Override public void output(Row value) { - ProcessBundleContextBase.this.outputWindowedValue( + emitToConsumer( tag, + consumer, WindowedValues.ofWithCurrentContext( currentElement, fromRowFunction.apply(value))); } @Override public void outputWithTimestamp(Row value, Instant timestamp) { - ProcessBundleContextBase.this.outputWindowedValue( + emitToConsumer( tag, + consumer, WindowedValues.ofWithCurrentContext( currentElement, fromRowFunction.apply(value), timestamp)); } + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + currentElement, + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo)); + } + + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + currentElement, + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo, + valueKind)); + } + @Override public OutputBuilder builder(Row value) { return WindowedValues.builder(currentElement, value) .setReceiver( windowedRow -> - ProcessBundleContextBase.this.outputWindowedValue( + emitToConsumer( tag, + consumer, windowedRow.withValue( fromRowFunction.apply(windowedRow.getValue())))); } @@ -2234,13 +2389,23 @@ public OutputBuilder builder(Row value) { @Override public OutputReceiver get(TupleTag tag) { - return (OutputReceiver) - taggedOutputReceivers.computeIfAbsent(tag, this::createTaggedOutputReceiver); + // Avoid computeIfAbsent(tag, this::create...) capturing-lambda allocation on cache hit. + OutputReceiver receiver = taggedOutputReceivers.get(tag); + if (receiver == null) { + receiver = createTaggedOutputReceiver(tag); + taggedOutputReceivers.put(tag, receiver); + } + return (OutputReceiver) receiver; } @Override public OutputReceiver getRowReceiver(TupleTag tag) { - return taggedRowReceivers.computeIfAbsent(tag, this::createTaggedRowReceiver); + OutputReceiver receiver = taggedRowReceivers.get(tag); + if (receiver == null) { + receiver = createTaggedRowReceiver(tag); + taggedRowReceivers.put(tag, receiver); + } + return receiver; } }; @@ -2362,12 +2527,35 @@ public PipelineOptions getPipelineOptions() { @Override public void output(OutputT output) { - OutputReceiver.super.output(output); + Instant holdTimestamp = currentTimer.getHoldTimestamp(); + checkOnWindowExpirationTimestamp(holdTimestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + holdTimestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); } @Override public void outputWithTimestamp(OutputT output, Instant timestamp) { - OutputReceiver.super.outputWithTimestamp(output, timestamp); + checkOnWindowExpirationTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + timestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); } @Override @@ -2376,7 +2564,39 @@ public void outputWindowedValue( Instant timestamp, Collection windows, PaneInfo paneInfo) { - OutputReceiver.super.outputWindowedValue(output, timestamp, windows, paneInfo); + checkOnWindowExpirationTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + checkOnWindowExpirationTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + valueKind)); } @Override @@ -2469,30 +2689,8 @@ public void outputWindowedValue(TupleTag tag, WindowedValue windowedVa outputTo(consumer, windowedValue); } - @SuppressWarnings( - "deprecation") // Allowed Skew is deprecated for users, but must be respected private void checkOnWindowExpirationTimestamp(Instant timestamp) { - Instant lowerBound; - try { - lowerBound = currentTimer.getHoldTimestamp().minus(doFn.getAllowedTimestampSkew()); - } catch (ArithmeticException e) { - lowerBound = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - if (timestamp.isBefore(lowerBound) - || timestamp.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - throw new IllegalArgumentException( - String.format( - "Cannot output with timestamp %s. Output timestamps must be no earlier than the " - + "timestamp of the timer (%s) minus the allowed skew (%s) and no later " - + "than %s. See the DoFn#getAllowedTimestampSkew() Javadoc for details on " - + "changing the allowed skew.", - timestamp, - currentTimer.getHoldTimestamp(), - doFn.getAllowedTimestampSkew().getMillis() >= Integer.MAX_VALUE - ? doFn.getAllowedTimestampSkew() - : PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod()), - BoundedWindow.TIMESTAMP_MAX_VALUE)); - } + checkOutputTimestamp(currentTimer.getHoldTimestamp(), timestamp, true); } } @@ -2608,8 +2806,8 @@ private OutputReceiver createTaggedRowReceiver(TupleTag tag) { "Output with tag %s must have a schema in order to call getRowReceiver", tag); return new OutputReceiver() { - private SerializableFunction fromRowFunction = - ((SchemaCoder) outputCoder).getFromRowFunction(); + private final SerializableFunction fromRowFunction = + ((SchemaCoder) outputCoder).getFromRowFunction(); @Override public OutputBuilder builder(Row value) { @@ -2630,13 +2828,22 @@ public OutputBuilder builder(Row value) { @Override public OutputReceiver get(TupleTag tag) { - return (OutputReceiver) - taggedOutputReceivers.computeIfAbsent(tag, this::createTaggedOutputReceiver); + OutputReceiver receiver = taggedOutputReceivers.get(tag); + if (receiver == null) { + receiver = createTaggedOutputReceiver(tag); + taggedOutputReceivers.put(tag, receiver); + } + return (OutputReceiver) receiver; } @Override public OutputReceiver getRowReceiver(TupleTag tag) { - return taggedRowReceivers.computeIfAbsent(tag, this::createTaggedRowReceiver); + OutputReceiver receiver = taggedRowReceivers.get(tag); + if (receiver == null) { + receiver = createTaggedRowReceiver(tag); + taggedRowReceivers.put(tag, receiver); + } + return receiver; } }; @@ -2700,7 +2907,7 @@ public T sideInput(PCollectionView view) { @Override public CausedByDrain causedByDrain() { - return causedByDrain; + return currentTimer.causedByDrain(); } @Override @@ -2710,7 +2917,7 @@ public OutputBuilder builder(OutputT value) { .setTimestamp(currentTimer.getHoldTimestamp()) .setWindow(currentWindow) .setPaneInfo(currentTimer.getPaneInfo()) - .setCausedByDrain(causedByDrain) + .setCausedByDrain(currentTimer.causedByDrain()) .setReceiver( windowedValue -> { checkTimerTimestamp(windowedValue.getTimestamp()); @@ -2720,12 +2927,35 @@ public OutputBuilder builder(OutputT value) { @Override public void output(OutputT output) { - OutputReceiver.super.output(output); + Instant holdTimestamp = currentTimer.getHoldTimestamp(); + checkTimerTimestamp(holdTimestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + holdTimestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); } @Override public void outputWithTimestamp(OutputT output, Instant timestamp) { - OutputReceiver.super.outputWithTimestamp(output, timestamp); + checkTimerTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + timestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); } @Override @@ -2734,7 +2964,39 @@ public void outputWindowedValue( Instant timestamp, Collection windows, PaneInfo paneInfo) { - OutputReceiver.super.outputWindowedValue(output, timestamp, windows, paneInfo); + checkTimerTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + OutputT output, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + checkTimerTimestamp(timestamp); + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + output, + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + valueKind)); } @Override @@ -2813,30 +3075,8 @@ public Instant timestamp() { return currentTimer.getHoldTimestamp(); } - @SuppressWarnings( - "deprecation") // Allowed Skew is deprecated for users, but must be respected private void checkTimerTimestamp(Instant timestamp) { - Instant lowerBound; - try { - lowerBound = currentTimer.getHoldTimestamp().minus(doFn.getAllowedTimestampSkew()); - } catch (ArithmeticException e) { - lowerBound = BoundedWindow.TIMESTAMP_MIN_VALUE; - } - if (timestamp.isBefore(lowerBound) - || timestamp.isAfter(BoundedWindow.TIMESTAMP_MAX_VALUE)) { - throw new IllegalArgumentException( - String.format( - "Cannot output with timestamp %s. Output timestamps must be no earlier than the " - + "timestamp of the timer (%s) minus the allowed skew (%s) and no later " - + "than %s. See the DoFn#getAllowedTimestampSkew() Javadoc for details on " - + "changing the allowed skew.", - timestamp, - currentTimer.getHoldTimestamp(), - doFn.getAllowedTimestampSkew().getMillis() >= Integer.MAX_VALUE - ? doFn.getAllowedTimestampSkew() - : PeriodFormat.getDefault().print(doFn.getAllowedTimestampSkew().toPeriod()), - BoundedWindow.TIMESTAMP_MAX_VALUE)); - } + checkOutputTimestamp(currentTimer.getHoldTimestamp(), timestamp, true); } } @@ -2888,6 +3128,75 @@ public OutputReceiver outputReceiver(DoFn doFn) { private final SerializableFunction fromRowFunction = mainOutputSchemaCoder.getFromRowFunction(); + @Override + public void output(Row value) { + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + currentTimer.getHoldTimestamp(), + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWithTimestamp(Row value, Instant timestamp) { + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + timestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + outputTo( + mainOutputConsumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + valueKind)); + } + @Override public OutputBuilder builder(Row value) { return WindowedValues.builder() @@ -2898,7 +3207,8 @@ public OutputBuilder builder(Row value) { .setCausedByDrain(currentTimer.causedByDrain()) .setReceiver( windowedValue -> - context.outputWindowedValue( + outputTo( + mainOutputConsumer, windowedValue.withValue( fromRowFunction.apply(windowedValue.getValue())))); } @@ -2923,7 +3233,83 @@ private OutputReceiver createTaggedOutputReceiver(TupleTag tag) { if (tag == null || mainOutputTag.equals(tag)) { return (OutputReceiver) context; } + // localNameToConsumer is immutable after construction; resolve once per tag. + final @Nullable FnDataReceiver> consumer = + (FnDataReceiver) localNameToConsumer.get(tag.getId()); return new OutputReceiver() { + @Override + public void output(T value) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + value, + currentTimer.getHoldTimestamp(), + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWithTimestamp(T value, Instant timestamp) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + value, + timestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + value, + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + T value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + value, + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + valueKind)); + } + @Override public OutputBuilder builder(T value) { return WindowedValues.builder() @@ -2932,7 +3318,7 @@ public OutputBuilder builder(T value) { .setWindow(currentWindow) .setCausedByDrain(currentTimer.causedByDrain()) .setPaneInfo(currentTimer.getPaneInfo()) - .setReceiver(windowedValue -> context.outputWindowedValue(tag, windowedValue)); + .setReceiver(windowedValue -> emitToConsumer(tag, consumer, windowedValue)); } }; } @@ -2952,9 +3338,85 @@ private OutputReceiver createTaggedRowReceiver(TupleTag tag) { outputCoder instanceof SchemaCoder, "Output with tag %s must have a schema in order to call getRowReceiver", tag); + // localNameToConsumer is immutable after construction; resolve once per tag. + final @Nullable FnDataReceiver> consumer = + (FnDataReceiver) localNameToConsumer.get(tag.getId()); return new OutputReceiver() { - private SerializableFunction fromRowFunction = - ((SchemaCoder) outputCoder).getFromRowFunction(); + private final SerializableFunction fromRowFunction = + ((SchemaCoder) outputCoder).getFromRowFunction(); + + @Override + public void output(Row value) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + currentTimer.getHoldTimestamp(), + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWithTimestamp(Row value, Instant timestamp) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + timestamp, + currentWindow, + currentTimer.getPaneInfo(), + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + ValueKind.INSERT)); + } + + @Override + public void outputWindowedValue( + Row value, + Instant timestamp, + Collection windows, + PaneInfo paneInfo, + ValueKind valueKind) { + emitToConsumer( + tag, + consumer, + WindowedValues.ofWithCurrentContext( + fromRowFunction.apply(value), + timestamp, + windows, + paneInfo, + null, + null, + currentTimer.causedByDrain(), + valueKind)); + } @Override public OutputBuilder builder(Row value) { @@ -2966,8 +3428,9 @@ public OutputBuilder builder(Row value) { .setCausedByDrain(currentTimer.causedByDrain()) .setReceiver( windowedValue -> - context.outputWindowedValue( + emitToConsumer( tag, + consumer, windowedValue.withValue( fromRowFunction.apply(windowedValue.getValue())))); } @@ -2976,13 +3439,22 @@ public OutputBuilder builder(Row value) { @Override public OutputReceiver get(TupleTag tag) { - return (OutputReceiver) - taggedOutputReceivers.computeIfAbsent(tag, this::createTaggedOutputReceiver); + OutputReceiver receiver = taggedOutputReceivers.get(tag); + if (receiver == null) { + receiver = createTaggedOutputReceiver(tag); + taggedOutputReceivers.put(tag, receiver); + } + return (OutputReceiver) receiver; } @Override public OutputReceiver getRowReceiver(TupleTag tag) { - return taggedRowReceivers.computeIfAbsent(tag, this::createTaggedRowReceiver); + OutputReceiver receiver = taggedRowReceivers.get(tag); + if (receiver == null) { + receiver = createTaggedRowReceiver(tag); + taggedRowReceivers.put(tag, receiver); + } + return receiver; } }; diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java index 4166b2a48dcc..395fe0a2a72f 100644 --- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java +++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java @@ -88,6 +88,7 @@ import org.apache.beam.sdk.options.ExperimentalOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.state.BagState; import org.apache.beam.sdk.state.CombiningState; import org.apache.beam.sdk.state.StateSpec; @@ -132,6 +133,8 @@ import org.apache.beam.sdk.values.Row; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; +import org.apache.beam.sdk.values.TypeDescriptor; +import org.apache.beam.sdk.values.ValueKind; import org.apache.beam.sdk.values.WindowedValue; import org.apache.beam.sdk.values.WindowedValues; import org.apache.beam.vendor.grpc.v1p69p0.com.google.protobuf.ByteString; @@ -1341,6 +1344,553 @@ public void testTimerRowOutputReceivers() throws Exception { Iterables.getOnlyElement(context.getTearDownFunctions()).run(); } + private static class TestProcessElementFastPathDoFn extends DoFn { + private final TupleTag mainOutput; + private final TupleTag sideConvertedTag; + private final TupleTag sideStringTag; + + private TestProcessElementFastPathDoFn( + TupleTag mainOutput, + TupleTag sideConvertedTag, + TupleTag sideStringTag) { + this.mainOutput = mainOutput; + this.sideConvertedTag = sideConvertedTag; + this.sideStringTag = sideStringTag; + } + + @ProcessElement + public void processElement( + @Element String elem, @Timestamp Instant ts, MultiOutputReceiver receiver) { + Instant shifted = ts.plus(Duration.millis(50)); + IntervalWindow w = new IntervalWindow(ts, ts.plus(Duration.millis(100))); + + // Exercises ProcessBundleContextBase.mainRowOutputReceiver. + OutputReceiver mainRow = receiver.getRowReceiver(mainOutput); + mainRow.output(row("m:" + elem)); + mainRow.outputWithTimestamp(row("mts:" + elem), shifted); + mainRow.outputWindowedValue( + row("mw:" + elem), + shifted, + Collections.singletonList(w), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + mainRow.outputWindowedValue( + row("mk:" + elem), + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.DELETE); + mainRow.builder(row("mb:" + elem)).setRecordId("override-" + elem).output(); + + // Exercises tagged RowOutputReceiver with non-identity SchemaCoder (Row -> String). + OutputReceiver sideRow = receiver.getRowReceiver(sideConvertedTag); + sideRow.output(row("sr:" + elem)); + sideRow.outputWithTimestamp(row("srts:" + elem), shifted); + sideRow.outputWindowedValue( + row("srw:" + elem), + shifted, + Collections.singletonList(w), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + sideRow.outputWindowedValue( + row("srk:" + elem), + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.UPDATE_AFTER); + sideRow.builder(row("srb:" + elem)).setRecordId("sr-override-" + elem).output(); + + // Exercises ProcessBundleContextBase.taggedOutputReceiver.get(sideStringTag). + OutputReceiver sideStr = receiver.get(sideStringTag); + sideStr.output("s:" + elem); + sideStr.outputWithTimestamp("sts:" + elem, shifted); + sideStr.outputWindowedValue( + "sw:" + elem, shifted, Collections.singletonList(w), PaneInfo.ON_TIME_AND_ONLY_FIRING); + sideStr.outputWindowedValue( + "sk:" + elem, + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.DELETE); + sideStr.builder("sb:" + elem).setRecordOffset(999L).output(); + } + } + + @Test + public void testProcessElementRowAndTaggedOutputReceiversMetadataPropagation() + throws Exception { + Pipeline p = Pipeline.create(); + PCollection input = p.apply(Create.of("unused")); + TupleTag mainOutput = new TupleTag("main") {}; + TupleTag sideConvertedTag = new TupleTag("sideRow") {}; + TupleTag sideStringTag = new TupleTag("sideStr") {}; + PCollectionTuple outputs = + input.apply( + TEST_TRANSFORM_ID, + ParDo.of( + new TestProcessElementFastPathDoFn( + mainOutput, sideConvertedTag, sideStringTag)) + .withOutputTags( + mainOutput, TupleTagList.of(sideConvertedTag).and(sideStringTag))); + outputs.get(mainOutput).setRowSchema(ROW_SCHEMA); + outputs + .get(sideConvertedTag) + .setCoder( + SchemaCoder.of( + ROW_SCHEMA, + TypeDescriptor.of(String.class), + s -> row(s), + r -> "conv:" + r.getString(0))); + + SdkComponents sdkComponents = SdkComponents.create(); + sdkComponents.registerEnvironment(Environment.getDefaultInstance()); + RunnerApi.Pipeline pProto = PipelineTranslation.toProto(p, sdkComponents); + String inputId = sdkComponents.registerPCollection(input); + String mainOutId = sdkComponents.registerPCollection(outputs.get(mainOutput)); + String sideRowId = sdkComponents.registerPCollection(outputs.get(sideConvertedTag)); + String sideStrId = sdkComponents.registerPCollection(outputs.get(sideStringTag)); + RunnerApi.PTransform pTransform = + pProto.getComponents().getTransformsOrThrow(TEST_TRANSFORM_ID); + + List> mainValues = new ArrayList<>(); + List> sideRowValues = new ArrayList<>(); + List> sideStrValues = new ArrayList<>(); + PTransformRunnerFactoryTestContext context = + PTransformRunnerFactoryTestContext.builder(TEST_TRANSFORM_ID, pTransform) + .processBundleInstructionId("57L") + .components(pProto.getComponents()) + .build(); + context.addPCollectionConsumer( + mainOutId, (FnDataReceiver) (FnDataReceiver>) mainValues::add); + context.addPCollectionConsumer( + sideRowId, (FnDataReceiver) (FnDataReceiver>) sideRowValues::add); + context.addPCollectionConsumer( + sideStrId, (FnDataReceiver) (FnDataReceiver>) sideStrValues::add); + + new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(context); + Iterables.getOnlyElement(context.getStartBundleFunctions()).run(); + + FnDataReceiver> inputConsumer = + (FnDataReceiver) context.getPCollectionConsumer(inputId); + Instant ts = new Instant(1000L); + IntervalWindow w1 = new IntervalWindow(ts, ts.plus(Duration.millis(500))); + // Process two elements to exercise both cache miss and cache hit on taggedOutputReceiver. + inputConsumer.accept( + WindowedValues.of( + "A", + ts, + w1, + PaneInfo.NO_FIRING, + "rid-A", + 11L, + CausedByDrain.CAUSED_BY_DRAIN, + null, + ValueKind.UPDATE_BEFORE)); + inputConsumer.accept( + WindowedValues.of( + "B", + ts.plus(Duration.millis(200)), + GlobalWindow.INSTANCE, + PaneInfo.NO_FIRING, + "rid-B", + 22L, + CausedByDrain.NORMAL, + null, + ValueKind.INSERT)); + + assertEquals(10, mainValues.size()); + assertEquals(row("m:A"), mainValues.get(0).getValue()); + assertEquals("rid-A", mainValues.get(0).getRecordId()); + assertEquals(Long.valueOf(11L), mainValues.get(0).getRecordOffset()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, mainValues.get(0).causedByDrain()); + assertEquals(ValueKind.UPDATE_BEFORE, mainValues.get(0).getValueKind()); + assertEquals(new Instant(1050L), mainValues.get(1).getTimestamp()); + assertEquals(ValueKind.DELETE, mainValues.get(3).getValueKind()); + assertEquals("override-A", mainValues.get(4).getRecordId()); + assertEquals(row("m:B"), mainValues.get(5).getValue()); + assertEquals("rid-B", mainValues.get(5).getRecordId()); + + assertEquals(10, sideRowValues.size()); + assertEquals("conv:sr:A", sideRowValues.get(0).getValue()); + assertEquals("rid-A", sideRowValues.get(0).getRecordId()); + assertEquals(Long.valueOf(11L), sideRowValues.get(0).getRecordOffset()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, sideRowValues.get(0).causedByDrain()); + assertEquals("conv:srts:A", sideRowValues.get(1).getValue()); + assertEquals(new Instant(1050L), sideRowValues.get(1).getTimestamp()); + assertEquals("conv:srw:A", sideRowValues.get(2).getValue()); + assertEquals(PaneInfo.ON_TIME_AND_ONLY_FIRING, sideRowValues.get(2).getPaneInfo()); + assertEquals("conv:srk:A", sideRowValues.get(3).getValue()); + assertEquals(ValueKind.UPDATE_AFTER, sideRowValues.get(3).getValueKind()); + assertEquals("conv:srb:A", sideRowValues.get(4).getValue()); + assertEquals("sr-override-A", sideRowValues.get(4).getRecordId()); + assertEquals("conv:sr:B", sideRowValues.get(5).getValue()); + + assertEquals(10, sideStrValues.size()); + assertEquals("s:A", sideStrValues.get(0).getValue()); + assertEquals("rid-A", sideStrValues.get(0).getRecordId()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, sideStrValues.get(0).causedByDrain()); + assertEquals(ValueKind.UPDATE_BEFORE, sideStrValues.get(0).getValueKind()); + assertEquals(new Instant(1050L), sideStrValues.get(1).getTimestamp()); + assertEquals(ValueKind.DELETE, sideStrValues.get(3).getValueKind()); + assertEquals("sb:A", sideStrValues.get(4).getValue()); + assertEquals(Long.valueOf(999L), sideStrValues.get(4).getRecordOffset()); + assertEquals("s:B", sideStrValues.get(5).getValue()); + assertEquals("rid-B", sideStrValues.get(5).getRecordId()); + + Iterables.getOnlyElement(context.getFinishBundleFunctions()).run(); + Iterables.getOnlyElement(context.getTearDownFunctions()).run(); + } + + private static class TestTimerFastPathsDoFn extends DoFn, String> { + @TimerId("event") + private final TimerSpec eventTimerSpec = TimerSpecs.timer(TimeDomain.EVENT_TIME); + + private final TupleTag mainOutput; + private final TupleTag sideOutput; + private final TupleTag unknownOutput; + + private TestTimerFastPathsDoFn( + TupleTag mainOutput, + TupleTag sideOutput, + TupleTag unknownOutput) { + this.mainOutput = mainOutput; + this.sideOutput = sideOutput; + this.unknownOutput = unknownOutput; + } + + @ProcessElement + public void processElement(ProcessContext c, @TimerId("event") Timer timer) { + timer.set(c.timestamp()); + } + + @OnTimer("event") + public void onTimer( + @Key String key, + @Timestamp Instant holdTs, + OutputReceiver mainReceiver, + MultiOutputReceiver multi) { + if ("bad-ts".equals(key)) { + mainReceiver.outputWithTimestamp("fail", holdTs.minus(Duration.millis(1))); + return; + } + if ("bad-tag".equals(key)) { + multi.get(unknownOutput).output("fail"); + return; + } + Instant shifted = holdTs.plus(Duration.millis(10)); + IntervalWindow w = new IntervalWindow(holdTs, holdTs.plus(Duration.millis(100))); + mainReceiver.output("tm:" + key); + mainReceiver.outputWithTimestamp("tmts:" + key, shifted); + mainReceiver.outputWindowedValue( + "tmw:" + key, shifted, Collections.singletonList(w), PaneInfo.ON_TIME_AND_ONLY_FIRING); + mainReceiver.outputWindowedValue( + "tmk:" + key, + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.DELETE); + + OutputReceiver mainRow = multi.getRowReceiver(mainOutput); + mainRow.output(row("tmr:" + key)); + mainRow.outputWithTimestamp(row("tmrts:" + key), shifted); + mainRow.outputWindowedValue( + row("tmrw:" + key), + shifted, + Collections.singletonList(w), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + mainRow.outputWindowedValue( + row("tmrk:" + key), + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.UPDATE_BEFORE); + + OutputReceiver side = multi.get(sideOutput); + side.output("ts:" + key); + side.outputWithTimestamp("tsts:" + key, shifted); + side.outputWindowedValue( + "tsw:" + key, shifted, Collections.singletonList(w), PaneInfo.ON_TIME_AND_ONLY_FIRING); + side.outputWindowedValue( + "tsk:" + key, + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.UPDATE_AFTER); + + OutputReceiver sideRow = multi.getRowReceiver(sideOutput); + sideRow.output(row("tsr:" + key)); + sideRow.outputWithTimestamp(row("tsrts:" + key), shifted); + sideRow.outputWindowedValue( + row("tsrw:" + key), + shifted, + Collections.singletonList(w), + PaneInfo.ON_TIME_AND_ONLY_FIRING); + sideRow.outputWindowedValue( + row("tsrk:" + key), + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.DELETE); + } + + @OnWindowExpiration + public void onWindowExpiration( + @Key String key, @Timestamp Instant holdTs, OutputReceiver mainReceiver) { + if ("bad-exp-ts".equals(key)) { + mainReceiver.outputWithTimestamp("fail", holdTs.minus(Duration.millis(1))); + return; + } + Instant shifted = holdTs.plus(Duration.millis(20)); + IntervalWindow w = new IntervalWindow(holdTs, holdTs.plus(Duration.millis(100))); + mainReceiver.output("exp:" + key); + mainReceiver.outputWithTimestamp("expts:" + key, shifted); + mainReceiver.outputWindowedValue( + "expw:" + key, shifted, Collections.singletonList(w), PaneInfo.ON_TIME_AND_ONLY_FIRING); + mainReceiver.outputWindowedValue( + "expk:" + key, + shifted, + Collections.singletonList(w), + PaneInfo.NO_FIRING, + ValueKind.DELETE); + } + } + + @Test + public void testTimerAndWindowExpirationOutputFastPaths() throws Exception { + TupleTag mainTag = new TupleTag("main") {}; + TupleTag sideTag = new TupleTag("side") {}; + TupleTag unknownTag = new TupleTag("unknown") {}; + SchemaCoder stringSchemaCoder = + SchemaCoder.of( + ROW_SCHEMA, + TypeDescriptor.of(String.class), + s -> row(s), + r -> "fromRow:" + r.getString(0)); + + Pipeline p = Pipeline.create(); + PCollection> input = p.apply(Create.of(KV.of("unused", "unused"))); + PCollectionTuple outputs = + input.apply( + TEST_TRANSFORM_ID, + ParDo.of(new TestTimerFastPathsDoFn(mainTag, sideTag, unknownTag)) + .withOutputTags(mainTag, TupleTagList.of(sideTag))); + outputs.get(mainTag).setCoder(stringSchemaCoder); + outputs.get(sideTag).setCoder(stringSchemaCoder); + + SdkComponents sdkComponents = SdkComponents.create(); + sdkComponents.registerEnvironment(Environment.getDefaultInstance()); + RunnerApi.Pipeline pProto = PipelineTranslation.toProto(p, sdkComponents); + String mainOutId = sdkComponents.registerPCollection(outputs.get(mainTag)); + String sideOutId = sdkComponents.registerPCollection(outputs.get(sideTag)); + RunnerApi.PTransform pTransform = + pProto.getComponents().getTransformsOrThrow(TEST_TRANSFORM_ID); + + List> mainValues = new ArrayList<>(); + List> sideValues = new ArrayList<>(); + PTransformRunnerFactoryTestContext context = + PTransformRunnerFactoryTestContext.builder(TEST_TRANSFORM_ID, pTransform) + .beamFnStateClient(new FakeBeamFnStateClient(StringUtf8Coder.of(), ImmutableMap.of())) + .processBundleInstructionId("57L") + .components( + RunnerApi.Components.newBuilder() + .putAllCoders(pProto.getComponents().getCodersMap()) + .putAllEnvironments(Collections.emptyMap()) + .putAllWindowingStrategies(pProto.getComponents().getWindowingStrategiesMap()) + .putAllPcollections(pProto.getComponentsOrBuilder().getPcollectionsMap()) + .build()) + .outboundAggregators( + ImmutableMap.of( + ApiServiceDescriptor.getDefaultInstance(), + new TestBeamFnDataOutboundAggregator(() -> "57L"))) + .timerApiServiceDescriptor(ApiServiceDescriptor.getDefaultInstance()) + .build(); + context.addPCollectionConsumer( + mainOutId, (FnDataReceiver) (FnDataReceiver>) mainValues::add); + context.addPCollectionConsumer( + sideOutId, (FnDataReceiver) (FnDataReceiver>) sideValues::add); + + new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(context); + Iterables.getOnlyElement(context.getStartBundleFunctions()).run(); + + Instant holdTs = new Instant(1400L); + Instant fireTs = new Instant(2400L); + FnDataReceiver eventTimer = + context.getIncomingTimerEndpoint("ts-event").getReceiver(); + eventTimer.accept( + org.apache.beam.sdk.util.construction.Timer.of( + "A", + "", + Collections.singletonList(GlobalWindow.INSTANCE), + fireTs, + holdTs, + PaneInfo.createPane(false, false, PaneInfo.Timing.EARLY, 1, 0), + CausedByDrain.CAUSED_BY_DRAIN)); + // Second timer triggers cached lookup in OnTimerContext.taggedOutputReceiver. + eventTimer.accept( + org.apache.beam.sdk.util.construction.Timer.of( + "B", + "", + Collections.singletonList(GlobalWindow.INSTANCE), + fireTs, + holdTs, + PaneInfo.NO_FIRING, + CausedByDrain.NORMAL)); + + assertEquals(16, mainValues.size()); + assertEquals("tm:A", mainValues.get(0).getValue()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, mainValues.get(0).causedByDrain()); + assertEquals(new Instant(1410L), mainValues.get(1).getTimestamp()); + assertEquals(PaneInfo.ON_TIME_AND_ONLY_FIRING, mainValues.get(2).getPaneInfo()); + assertEquals(ValueKind.DELETE, mainValues.get(3).getValueKind()); + assertEquals("fromRow:tmr:A", mainValues.get(4).getValue()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, mainValues.get(4).causedByDrain()); + assertEquals(ValueKind.UPDATE_BEFORE, mainValues.get(7).getValueKind()); + assertEquals("tm:B", mainValues.get(8).getValue()); + assertEquals(CausedByDrain.NORMAL, mainValues.get(8).causedByDrain()); + + assertEquals(16, sideValues.size()); + assertEquals("ts:A", sideValues.get(0).getValue()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, sideValues.get(0).causedByDrain()); + assertEquals(ValueKind.UPDATE_AFTER, sideValues.get(3).getValueKind()); + assertEquals("fromRow:tsr:A", sideValues.get(4).getValue()); + assertEquals(ValueKind.DELETE, sideValues.get(7).getValueKind()); + assertEquals("ts:B", sideValues.get(8).getValue()); + assertEquals(CausedByDrain.NORMAL, sideValues.get(8).causedByDrain()); + + // Timestamp skew violation reports "timestamp of the timer". + Exception timerTsEx = + Assert.assertThrows( + Exception.class, + () -> eventTimer.accept(timerInGlobalWindow("bad-ts", holdTs, fireTs))); + assertThat(timerTsEx.getCause(), instanceOf(IllegalArgumentException.class)); + assertThat(timerTsEx.getCause().getMessage(), containsString("timestamp of the timer")); + + // Unknown output tag inside @OnTimer. + Exception unknownTagEx = + Assert.assertThrows( + Exception.class, + () -> eventTimer.accept(timerInGlobalWindow("bad-tag", holdTs, fireTs))); + assertThat(unknownTagEx.getCause(), instanceOf(IllegalArgumentException.class)); + + // @OnWindowExpiration fast paths + drain + timestamp skew validation. + mainValues.clear(); + String onWindowExpirationId = + RunnerApi.ParDoPayload.parseFrom(pTransform.getSpec().getPayload()) + .getOnWindowExpirationTimerFamilySpec(); + FnDataReceiver expTimer = + context.getIncomingTimerEndpoint(onWindowExpirationId).getReceiver(); + expTimer.accept( + org.apache.beam.sdk.util.construction.Timer.of( + "E", + "", + Collections.singletonList(GlobalWindow.INSTANCE), + fireTs, + holdTs, + PaneInfo.NO_FIRING, + CausedByDrain.CAUSED_BY_DRAIN)); + assertEquals(4, mainValues.size()); + assertEquals("exp:E", mainValues.get(0).getValue()); + assertEquals(CausedByDrain.CAUSED_BY_DRAIN, mainValues.get(0).causedByDrain()); + assertEquals(new Instant(1420L), mainValues.get(1).getTimestamp()); + assertEquals(PaneInfo.ON_TIME_AND_ONLY_FIRING, mainValues.get(2).getPaneInfo()); + assertEquals(ValueKind.DELETE, mainValues.get(3).getValueKind()); + + Exception expTsEx = + Assert.assertThrows( + Exception.class, + () -> expTimer.accept(timerInGlobalWindow("bad-exp-ts", holdTs, fireTs))); + assertThat(expTsEx.getCause(), instanceOf(IllegalArgumentException.class)); + assertThat(expTsEx.getCause().getMessage(), containsString("timestamp of the timer")); + + Iterables.getOnlyElement(context.getFinishBundleFunctions()).run(); + Iterables.getOnlyElement(context.getTearDownFunctions()).run(); + } + + @Test + public void testNonWindowObservingOutputFastPathsAndUnknownTag() throws Exception { + TupleTag unknownTag = new TupleTag("unknown") {}; + TupleTag mainTag = new TupleTag("main") {}; + DoFn doFn = + new DoFn() { + @Override + public Duration getAllowedTimestampSkew() { + return Duration.millis(Long.MAX_VALUE); + } + + @ProcessElement + public void processElement( + ProcessContext c, OutputReceiver out, MultiOutputReceiver multi) { + if ("unknown".equals(c.element())) { + multi.get(unknownTag).output("boom"); + return; + } + out.outputWithTimestamp("skewed:" + c.element(), BoundedWindow.TIMESTAMP_MIN_VALUE); + out.outputWindowedValue( + "kind:" + c.element(), + c.timestamp(), + Collections.singletonList(GlobalWindow.INSTANCE), + PaneInfo.NO_FIRING, + ValueKind.DELETE); + } + }; + + Pipeline p = Pipeline.create(); + PCollection input = p.apply(Create.of("unused")); + PCollectionTuple outputs = + input.apply( + TEST_TRANSFORM_ID, ParDo.of(doFn).withOutputTags(mainTag, TupleTagList.empty())); + + SdkComponents sdkComponents = SdkComponents.create(); + sdkComponents.registerEnvironment(Environment.getDefaultInstance()); + RunnerApi.Pipeline pProto = PipelineTranslation.toProto(p, sdkComponents); + String inputId = sdkComponents.registerPCollection(input); + String mainOutId = sdkComponents.registerPCollection(outputs.get(mainTag)); + RunnerApi.PTransform pTransform = + pProto.getComponents().getTransformsOrThrow(TEST_TRANSFORM_ID); + + List> mainValues = new ArrayList<>(); + PTransformRunnerFactoryTestContext context = + PTransformRunnerFactoryTestContext.builder(TEST_TRANSFORM_ID, pTransform) + .processBundleInstructionId("57L") + .components(pProto.getComponents()) + .build(); + context.addPCollectionConsumer( + mainOutId, (FnDataReceiver) (FnDataReceiver>) mainValues::add); + + new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(context); + Iterables.getOnlyElement(context.getStartBundleFunctions()).run(); + + FnDataReceiver> inputConsumer = + (FnDataReceiver) context.getPCollectionConsumer(inputId); + // Negative timestamp - Long.MAX_VALUE overflows long -> clamps lower bound to MIN_VALUE. + inputConsumer.accept( + WindowedValues.of( + "ok", + new Instant(-100L), + GlobalWindow.INSTANCE, + PaneInfo.NO_FIRING, + "rid-skew", + 3L, + CausedByDrain.CAUSED_BY_DRAIN, + null, + ValueKind.UPDATE_BEFORE)); + + assertEquals(2, mainValues.size()); + assertEquals("skewed:ok", mainValues.get(0).getValue()); + assertEquals(BoundedWindow.TIMESTAMP_MIN_VALUE, mainValues.get(0).getTimestamp()); + assertEquals("rid-skew", mainValues.get(0).getRecordId()); + assertEquals(ValueKind.UPDATE_BEFORE, mainValues.get(0).getValueKind()); + assertEquals("kind:ok", mainValues.get(1).getValue()); + assertEquals(ValueKind.DELETE, mainValues.get(1).getValueKind()); + + Exception thrown = + Assert.assertThrows( + Exception.class, + () -> inputConsumer.accept(WindowedValues.valueInGlobalWindow("unknown"))); + assertThat(thrown.getCause(), instanceOf(IllegalArgumentException.class)); + + Iterables.getOnlyElement(context.getFinishBundleFunctions()).run(); + Iterables.getOnlyElement(context.getTearDownFunctions()).run(); + } + private static class TestWindowExpirationDoFn extends DoFn, String> { @StateId("bag") private final StateSpec> bagStateSpec = StateSpecs.bag(StringUtf8Coder.of()); From 4e7f6654209a70e22de56b75828c1cdc37e5b728 Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Sat, 28 Nov 2026 09:27:01 -0800 Subject: [PATCH 3/4] trigger validatesRunner --- ...stCommit_Java_ValidatesRunner_Dataflow_Streaming_Engine.json | 2 +- .../beam_PostCommit_Java_ValidatesRunner_Dataflow_V2.json | 2 +- ...m_PostCommit_Java_ValidatesRunner_Dataflow_V2_Streaming.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_Streaming_Engine.json b/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_Streaming_Engine.json index 0726e6343b31..22f6c3813b60 100644 --- a/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_Streaming_Engine.json +++ b/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_Streaming_Engine.json @@ -1,4 +1,4 @@ { "comment": "Modify this file in a trivial way to cause this test suite to run!", - "modification": 4 + "modification": 5 } diff --git a/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2.json b/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2.json index 04ea96054d2a..96de892e773c 100644 --- a/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2.json +++ b/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2.json @@ -1,5 +1,5 @@ { "comment": "Modify this file in a trivial way to cause this test suite to run!", - "modification": 5, + "modification": 6, "https://github.com/apache/beam/pull/39990": "removing dead code from FnApiDoFnRunner" } diff --git a/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2_Streaming.json b/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2_Streaming.json index 04f535101511..fefeb07db060 100644 --- a/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2_Streaming.json +++ b/.github/trigger_files/beam_PostCommit_Java_ValidatesRunner_Dataflow_V2_Streaming.json @@ -1,5 +1,5 @@ { "comment": "Modify this file in a trivial way to cause this test suite to run!", - "modification": 3, + "modification": 4, "https://github.com/apache/beam/pull/39990": "removing dead code from FnApiDoFnRunner" } From 65f6f5b69ca9b45388693ac87f69cd9b4fbd7bdd Mon Sep 17 00:00:00 2001 From: Reuven Lax Date: Sat, 28 Nov 2026 09:56:33 -0800 Subject: [PATCH 4/4] remove regression --- .../beam/runners/core/SimpleDoFnRunner.java | 21 ++--- .../runners/core/SimpleDoFnRunnerTest.java | 77 ++++++++----------- 2 files changed, 38 insertions(+), 60 deletions(-) diff --git a/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java b/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java index b0bd3523e973..dfb32af4ae2f 100644 --- a/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java +++ b/runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java @@ -227,24 +227,18 @@ public void startBundle() { @Override public void processElement(WindowedValue compressedElem) { @Nullable Context desired = compressedElem.getOpenTelemetryContext(); - @Nullable Context current = ContextStorage.get().current(); - if (desired == current) { - // Fast path covers both (null, null) and identical active contexts with zero Scope - // allocation. + if (desired == null) { processElementInternal(compressedElem); } else { - processElementWithContextChange(compressedElem, desired, current); + processElementWithContext(compressedElem, desired); } } - private void processElementWithContextChange( - WindowedValue compressedElem, @Nullable Context desired, @Nullable Context current) { - Context root = Context.root(); - Context target = desired != null ? desired : root; - if (current == target || (current == null && target == root)) { + private void processElementWithContext(WindowedValue compressedElem, Context desired) { + if (desired == ContextStorage.get().current()) { processElementInternal(compressedElem); } else { - try (Scope ignore = target.makeCurrent()) { + try (Scope ignore = desired.makeCurrent()) { processElementInternal(compressedElem); } } @@ -606,7 +600,7 @@ public PaneInfo pane() { @Override public void output(OutputT output) { checkNotNull(mainOutputTag, "Tag passed to output cannot be null"); - outputManager.output(mainOutputTag, outputValueWithCurrentContext(currentElem(), output)); + outputManager.output(mainOutputTag, currentElem().withValue(output)); } @Override @@ -626,8 +620,7 @@ public void outputWindowedValue( @Override public void output(TupleTag tag, T output) { checkNotNull(tag, "Tag passed to output cannot be null"); - SimpleDoFnRunner.this.outputWindowedValue( - tag, outputValueWithCurrentContext(currentElem(), output)); + SimpleDoFnRunner.this.outputWindowedValue(tag, currentElem().withValue(output)); } @Override diff --git a/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java b/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java index 43990b8bd502..c1bce880b0c1 100644 --- a/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java +++ b/runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java @@ -674,7 +674,7 @@ public void testOnTimerNoSkew() { } @Test - public void testProcessElementIsolatesOpenTelemetryContext() { + public void testProcessElementPropagatesOpenTelemetryContext() { ContextKey testKey = ContextKey.named("beam-test-key"); List observedValues = new ArrayList<>(); TupleTag mainTag = new TupleTag<>("main"); @@ -703,7 +703,7 @@ public void processElement(@Element String elem, OutputReceiver out) { DoFnSchemaInformation.create(), Collections.emptyMap()); - // Build an untraced element under Context.root() -> normalized openTelemetryContext is null. + // Untraced element built under Context.root() normalizes openTelemetryContext to null. WindowedValue untraced; try (Scope ignored = Context.root().makeCurrent()) { untraced = @@ -724,66 +724,49 @@ public void processElement(@Element String elem, OutputReceiver out) { CausedByDrain.NORMAL, elemCtx, ValueKind.INSERT); - WindowedValue explicitRoot = - WindowedValues.of( - "root", - BoundedWindow.TIMESTAMP_MIN_VALUE, - GlobalWindow.INSTANCE, - PaneInfo.NO_FIRING, - null, - null, - CausedByDrain.NORMAL, - Context.root(), - ValueKind.INSERT); - // Executing an untraced element while ambientCtx is active must NOT leak ambientCtx. + // Explicit element context activates during @ProcessElement and restores ambientCtx afterward. try (Scope ignored = ambientCtx.makeCurrent()) { - runner.processElement(untraced); - assertSame(ambientCtx, Context.current()); - runner.processElement(traced); assertSame(ambientCtx, Context.current()); - - runner.processElement(explicitRoot); - assertSame(ambientCtx, Context.current()); } - // Running explicit Context.root() with no attached thread context should also work cleanly. - runner.processElement(explicitRoot); + // Untraced element under normal root thread context emits null openTelemetryContext. + runner.processElement(untraced); assertSame(Context.root(), Context.current()); - assertEquals(4, observedValues.size()); - assertNull(observedValues.get(0)); - assertEquals("element", observedValues.get(1)); - assertNull(observedValues.get(2)); - assertNull(observedValues.get(3)); + // Already-active elemCtx hits the desired == current fast path without altering scope. + try (Scope ignored = elemCtx.makeCurrent()) { + runner.processElement(traced); + assertSame(elemCtx, Context.current()); + } + + assertEquals(3, observedValues.size()); + assertEquals("element", observedValues.get(0)); + assertNull(observedValues.get(1)); + assertEquals("element", observedValues.get(2)); List> emitted = outputManager.outputs.get(mainTag); - assertEquals(4, emitted.size()); - assertNull(emitted.get(0).getOpenTelemetryContext()); - assertSame(elemCtx, emitted.get(1).getOpenTelemetryContext()); - assertNull(emitted.get(2).getOpenTelemetryContext()); - assertNull(emitted.get(3).getOpenTelemetryContext()); - - // ProcessContext.output() must capture a span started inside @ProcessElement even when - // the input element had null openTelemetryContext (consistent with OutputReceiver.output). - Context childCtx = Context.root().with(testKey, "in-dofn-span"); - ListOutputManager legacyOut = new ListOutputManager(); - DoFn spanCreatingFn = + assertEquals(3, emitted.size()); + assertSame(elemCtx, emitted.get(0).getOpenTelemetryContext()); + assertNull(emitted.get(1).getOpenTelemetryContext()); + assertSame(elemCtx, emitted.get(2).getOpenTelemetryContext()); + + // ProcessContext.output() preserves the input element's openTelemetryContext via withValue(). + ListOutputManager pcOut = new ListOutputManager(); + DoFn pcFn = new DoFn() { @ProcessElement public void processElement(ProcessContext c) { - try (Scope ignored = childCtx.makeCurrent()) { - c.output("tagged-" + c.element()); - } + c.output("pc-" + c.element()); } }; - DoFnRunner legacyRunner = + DoFnRunner pcRunner = new SimpleDoFnRunner<>( null, - spanCreatingFn, + pcFn, NullSideInputReader.empty(), - legacyOut, + pcOut, mainTag, Collections.emptyList(), mockStepContext, @@ -792,8 +775,10 @@ public void processElement(ProcessContext c) { WindowingStrategy.of(new GlobalWindows()), DoFnSchemaInformation.create(), Collections.emptyMap()); - legacyRunner.processElement(untraced); - assertSame(childCtx, legacyOut.outputs.get(mainTag).get(0).getOpenTelemetryContext()); + pcRunner.processElement(traced); + pcRunner.processElement(untraced); + assertSame(elemCtx, pcOut.outputs.get(mainTag).get(0).getOpenTelemetryContext()); + assertNull(pcOut.outputs.get(mainTag).get(1).getOpenTelemetryContext()); } @Test