damccorm commented on code in PR #41815:
URL: https://github.com/apache/beam/pull/41815#discussion_r4786129572


##########
runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java:
##########
@@ -188,23 +226,35 @@ public void startBundle() {
 
   @Override
   public void processElement(WindowedValue<InputT> compressedElem) {
-    Context openTelemetryContext = compressedElem.getOpenTelemetryContext();
-    if (openTelemetryContext == null) {
+    @Nullable Context desired = compressedElem.getOpenTelemetryContext();
+    if (desired == null) {
+      processElementInternal(compressedElem);
+    } else {
+      processElementWithContext(compressedElem, desired);
+    }
+  }
+
+  private void processElementWithContext(WindowedValue<InputT> compressedElem, 
Context desired) {
+    if (desired == ContextStorage.get().current()) {
       processElementInternal(compressedElem);
     } else {
-      try (Scope ignore = openTelemetryContext.makeCurrent()) {
+      try (Scope ignore = desired.makeCurrent()) {
         processElementInternal(compressedElem);
       }
     }
   }

Review Comment:
   Two subtle OpenTelemetry issues here (especially stacked on #41813):
   
   1. **`desired == Context.root()` misses the fast path on untraced threads 
(line 238):** `ThreadLocalContextStorage.current()` returns `null` on a fresh 
thread (and resets back to `null` when the outermost `Scope` closes), whereas 
Dataflow's `UngroupedWindmillReader` / `WindmillKeyedWorkItem` 
(`WindmillOpenTelemetryContextPropagator.read`) returns `Context.root()` for 
untraced elements. Because `Context.root() == null` is `false`, line 238 falls 
through to `desired.makeCurrent()` and allocates a `ScopeImpl` (plus two 
`ThreadLocal.set` calls) on every untraced Windmill element. Checking `desired 
== current || (desired == Context.root() && current == null)` avoids that 
allocation at zero cost to the `desired == null` path.
   
   2. **Cross-element trace leak when `desired == null` under an active 
non-root span (lines 229–231):** On `master`, elements emitted via 
`OutputReceiver` or decoded by `FullWindowedValueCoder` carried non-null 
`Context.root()`, so `SimpleDoFnRunner` isolated `@ProcessElement` to 
`Context.root()` whenever another span was active on the thread. Now that 
#41813 normalizes `Context.root()` to `null`, skipping context isolation when 
`desired == null` means a fused downstream `DoFn` (e.g., Dataflow 
`SimpleParDoFnHelpers` / Spark `FusedOutput` forwarding a buffered untraced 
`WindowedValue` while an upstream `DoFn` is inside a traced element's `Scope`, 
or any runner dispatching inside an ambient span) will execute under the 
unrelated ambient span — and `OutputReceiver.output(...)` 
(`WindowedValues.ofWithCurrentContext`) will stamp that unrelated span onto the 
untraced output.
   
      *(Note `testProcessElementPropagatesOpenTelemetryContext` closes 
`ambientCtx.makeCurrent()` right before `runner.processElement(untraced)` at 
line 735, so this case isn't covered.)*
   
   If isolating `desired == null` is desired (matching 
`WindowedValue#getOpenTelemetryContext` Javadoc in #41813), something like:
   
   ```java
   @Nullable Context current = ContextStorage.get().current();
   if (desired == null) {
     if (current == null || current == Context.root()) {
       processElementInternal(compressedElem);
     } else {
       try (Scope ignore = Context.root().makeCurrent()) {
         processElementInternal(compressedElem);
       }
     }
   } else if (desired == current || (desired == Context.root() && current == 
null)) {
     processElementInternal(compressedElem);
   } else {
     try (Scope ignore = desired.makeCurrent()) {
       processElementInternal(compressedElem);
     }
   }
   ```
   
   (If skipping `ThreadLocal.get()` on `desired == null` is an intentional perf 
trade-off — or intended to let `ProcessContext.output()` inherit a manual span 
— we should at least fix #1 above and document/test the `desired == null` + 
ambient-context behavior explicitly.)



##########
runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java:
##########
@@ -641,19 +791,214 @@ public TimeDomain timeDomain(DoFn<InputT, OutputT> doFn) 
{
 
     @Override
     public OutputReceiver<OutputT> outputReceiver(DoFn<InputT, OutputT> doFn) {
-      return DoFnOutputReceivers.windowedReceiver(this, builderSupplier, 
mainOutputTag);
+      return getOrCreateMainOutputReceiver();
+    }
+
+    private DirectOutputReceiver<OutputT> getOrCreateMainOutputReceiver() {
+      DirectOutputReceiver<OutputT> receiver = cachedOutputReceiver;
+      if (receiver == null) {
+        receiver = new DirectOutputReceiver<>(mainOutputTag, outputManager);
+        cachedOutputReceiver = receiver;
+      }
+      return receiver;
     }
 
     @Override
     public OutputReceiver<Row> outputRowReceiver(DoFn<InputT, OutputT> doFn) {
-      checkStateNotNull(mainOutputSchemaCoder, "cannot provide row receiver 
without schema coder");
-      return DoFnOutputReceivers.rowReceiver(
-          this, builderSupplier, mainOutputTag, mainOutputSchemaCoder);
+      OutputReceiver<Row> 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<InputT, OutputT> 
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<T>
+        implements OutputReceiver<T>, WindowedValueReceiver<T> {
+      private final TupleTag<T> tag;
+      private final WindowedValueMultiReceiver receiverOutputManager;
+
+      DirectOutputReceiver(TupleTag<T> tag, WindowedValueMultiReceiver 
receiverOutputManager) {
+        this.tag = tag;
+        this.receiverOutputManager = receiverOutputManager;
+      }
+
+      @Override
+      public void output(T output) {
+        WindowedValue<InputT> current = currentElem();
+        Instant ts = current.getTimestamp();
+        checkTimestamp(ts, ts);
+        receiverOutputManager.output(tag, 
outputValueWithCurrentContext(current, output));
+      }
+
+      @Override
+      public void outputWithTimestamp(T output, Instant timestamp) {
+        WindowedValue<InputT> current = currentElem();
+        checkTimestamp(current.getTimestamp(), timestamp);
+        receiverOutputManager.output(
+            tag, WindowedValues.ofWithCurrentContext(current, output, 
timestamp));
+      }
+
+      @Override
+      public void outputWindowedValue(
+          T value,
+          Instant timestamp,
+          Collection<? extends BoundedWindow> windows,
+          PaneInfo paneInfo) {
+        WindowedValue<InputT> 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<? extends BoundedWindow> windows,
+          PaneInfo paneInfo,
+          ValueKind valueKind) {
+        WindowedValue<InputT> current = currentElem();
+        checkTimestamp(current.getTimestamp(), timestamp);
+        receiverOutputManager.output(
+            tag,
+            WindowedValues.ofWithCurrentContext(
+                current, value, timestamp, windows, paneInfo, valueKind));
+      }
+
+      @Override
+      public OutputBuilder<T> builder(T value) {
+        return WindowedValues.builder(currentElem(), value).setReceiver(this);
+      }
+
+      @Override
+      public void output(WindowedValue<T> windowedValue) {
+        checkTimestamp(currentElem().getTimestamp(), 
windowedValue.getTimestamp());
+        receiverOutputManager.output(tag, windowedValue);
+      }
+    }
+
+    private final class CachedMultiOutputReceiver implements 
MultiOutputReceiver {
+      // 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<OutputT> mainReceiver;
+      private @Nullable TupleTag<?> cachedSingleExtraTag;
+      private final @Nullable DirectOutputReceiver<?> singleExtraReceiver;
+      private @Nullable Map<TupleTag<?>, DirectOutputReceiver<?>> 
extraReceivers;
+      private @Nullable Map<TupleTag<?>, OutputReceiver<Row>> rowReceivers;
+
+      CachedMultiOutputReceiver(
+          @Nullable TupleTag<OutputT> mainTag, DirectOutputReceiver<OutputT> 
mainReceiver) {
+        this.cachedMainTag = mainTag;
+        this.mainReceiver = mainReceiver;
+        TupleTag<?> onlyExtra = singleExtraOutputTag;
+        if (onlyExtra != null) {
+          this.cachedSingleExtraTag = onlyExtra;
+          this.singleExtraReceiver = newDirectReceiver(onlyExtra);
+        } else {
+          this.cachedSingleExtraTag = null;
+          this.singleExtraReceiver = null;
+        }
+      }
+
+      private <T> DirectOutputReceiver<T> newDirectReceiver(TupleTag<T> tag) {
+        return new DirectOutputReceiver<>(tag, outputManager);
+      }
+
+      @Override
+      @SuppressWarnings({"unchecked", "ReferenceEquality"})
+      public <T> OutputReceiver<T> get(TupleTag<T> tag) {
+        if (tag == null || tag == cachedMainTag) {
+          return (OutputReceiver<T>) mainReceiver;
+        }
+        DirectOutputReceiver<?> onlyExtra = this.singleExtraReceiver;
+        if (onlyExtra != null && tag == cachedSingleExtraTag) {
+          return (OutputReceiver<T>) onlyExtra;
+        }
+        return getSlowPath(tag);
+      }
+
+      @SuppressWarnings("unchecked")
+      private <T> OutputReceiver<T> getSlowPath(TupleTag<T> tag) {
+        if (Objects.equals(cachedMainTag, tag)) {
+          cachedMainTag = tag;
+          return (OutputReceiver<T>) mainReceiver;
+        }
+        DirectOutputReceiver<?> onlyExtra = this.singleExtraReceiver;
+        if (onlyExtra != null && Objects.equals(cachedSingleExtraTag, tag)) {
+          cachedSingleExtraTag = tag;
+          return (OutputReceiver<T>) onlyExtra;
+        }
+        Map<TupleTag<?>, DirectOutputReceiver<?>> map = this.extraReceivers;
+        if (map != null) {
+          DirectOutputReceiver<?> cached = map.get(tag);
+          if (cached != null) {
+            return (OutputReceiver<T>) cached;
+          }
+        }
+        if (outputTags.contains(tag)) {
+          if (map == null) {
+            map = new HashMap<>(4);
+            this.extraReceivers = map;
+          }
+          DirectOutputReceiver<T> created = new DirectOutputReceiver<>(tag, 
outputManager);
+          map.put(tag, created);
+          return created;
+        }
+        return DoFnOutputReceivers.windowedReceiver(
+            DoFnProcessContext.this, DoFnProcessContext.this, tag);
+      }
+
+      @Override
+      @SuppressWarnings({"unchecked", "ReferenceEquality"})
+      public <T> OutputReceiver<Row> getRowReceiver(TupleTag<T> tag) {
+        Map<TupleTag<?>, Coder<?>> coders = checkNotNull(outputCoders);
+        if (tag == cachedMainTag && mainOutputSchemaCoder != null) {

Review Comment:
   Because `get(mainCopy)` mutates `cachedMainTag = mainCopy` (line 941), 
checking only `tag == cachedMainTag` here can miss both when 
`getRowReceiver(mainCopy)` is called before `get(mainCopy)` *and* when 
`getRowReceiver(mainTag)` (with the canonical constructor tag) is called after 
`get(mainCopy)` — allocating `rowReceivers`, caching a second 
`RowOutputReceiver`, and flipping returned instance identity depending on call 
order.
   
   Checking `Objects.equals(cachedMainTag, tag)` (and updating `cachedMainTag = 
tag`) when `mainOutputSchemaCoder != null` avoids the duplicate receiver and 
keeps identity consistent.



##########
runners/core-java/src/main/java/org/apache/beam/runners/core/SimpleDoFnRunner.java:
##########
@@ -167,6 +202,9 @@ public SimpleDoFnRunner(
         (Coder<BoundedWindow>) 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();

Review Comment:
   Caching `fn.getAllowedTimestampSkew()` once in the constructor looks safe 
for all in-repo `DoFn`s (every override returns a constant or final field), and 
handles `null` cleanly. Worth briefly noting in a comment that this assumes 
`getAllowedTimestampSkew()` is invariant after runner construction (or 
alternatively refreshing in `startBundle()` too if 
`@Setup`/`@StartBundle`-initialized skew should remain supported).



##########
runners/core-java/src/test/java/org/apache/beam/runners/core/SimpleDoFnRunnerTest.java:
##########
@@ -647,6 +673,233 @@ public void testOnTimerNoSkew() {
                     
PeriodFormat.getDefault().print(Duration.ZERO.toPeriod())))));
   }
 
+  @Test
+  public void testProcessElementPropagatesOpenTelemetryContext() {
+    ContextKey<String> testKey = ContextKey.named("beam-test-key");
+    List<String> observedValues = new ArrayList<>();
+    TupleTag<String> mainTag = new TupleTag<>("main");
+    ListOutputManager outputManager = new ListOutputManager();
+    DoFn<String, String> recordingFn =
+        new DoFn<String, String>() {
+          @ProcessElement
+          public void processElement(@Element String elem, 
OutputReceiver<String> out) {
+            observedValues.add(Context.current().get(testKey));
+            out.output(elem);
+          }
+        };
+
+    DoFnRunner<String, String> runner =
+        new SimpleDoFnRunner<>(
+            null,
+            recordingFn,
+            NullSideInputReader.empty(),
+            outputManager,
+            mainTag,
+            Collections.emptyList(),
+            mockStepContext,
+            null,
+            Collections.emptyMap(),
+            WindowingStrategy.of(new GlobalWindows()),
+            DoFnSchemaInformation.create(),
+            Collections.emptyMap());
+
+    // Untraced element built under Context.root() normalizes 
openTelemetryContext to null.
+    WindowedValue<String> 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<String> traced =
+        WindowedValues.of(
+            "traced",
+            BoundedWindow.TIMESTAMP_MIN_VALUE,
+            GlobalWindow.INSTANCE,
+            PaneInfo.NO_FIRING,
+            null,
+            null,
+            CausedByDrain.NORMAL,
+            elemCtx,
+            ValueKind.INSERT);
+
+    // Explicit element context activates during @ProcessElement and restores 
ambientCtx afterward.
+    try (Scope ignored = ambientCtx.makeCurrent()) {
+      runner.processElement(traced);
+      assertSame(ambientCtx, Context.current());
+    }
+
+    // Untraced element under normal root thread context emits null 
openTelemetryContext.
+    runner.processElement(untraced);
+    assertSame(Context.root(), Context.current());
+
+    // 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<WindowedValue<?>> emitted = outputManager.outputs.get(mainTag);
+    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<String, String> pcFn =
+        new DoFn<String, String>() {
+          @ProcessElement
+          public void processElement(ProcessContext c) {
+            c.output("pc-" + c.element());
+          }
+        };
+    DoFnRunner<String, String> pcRunner =
+        new SimpleDoFnRunner<>(
+            null,
+            pcFn,
+            NullSideInputReader.empty(),
+            pcOut,
+            mainTag,
+            Collections.emptyList(),
+            mockStepContext,
+            null,
+            Collections.emptyMap(),
+            WindowingStrategy.of(new GlobalWindows()),
+            DoFnSchemaInformation.create(),
+            Collections.emptyMap());
+    pcRunner.processElement(traced);
+    pcRunner.processElement(untraced);
+    assertSame(elemCtx, 
pcOut.outputs.get(mainTag).get(0).getOpenTelemetryContext());
+    assertNull(pcOut.outputs.get(mainTag).get(1).getOpenTelemetryContext());
+  }
+
+  @Test
+  public void testProcessElementOutputPreservesEmptyWindows() throws Exception 
{
+    TupleTag<String> mainTag = new TupleTag<>("main");
+    ListOutputManager outputManager = new ListOutputManager();
+    DoFn<String, String> doFn =
+        new DoFn<String, String>() {
+          @ProcessElement
+          public void processElement(ProcessContext c) {
+            c.output("out:" + c.element());
+          }
+        };
+    DoFnRunner<String, String> 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<String> 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<String> 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<WindowedValue<?>> 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());

Review Comment:
   `c.output("out:" + c.element())` hits `DoFnProcessContext.output(OutputT)` 
(`currentElem().withValue(output)` at `SimpleDoFnRunner.java:603`), so this 
test doesn't actually exercise `outputValueWithCurrentContext`'s empty-window 
fallback (and the `activeCtx.makeCurrent()` block at line 826 has no effect on 
`c.output(...)`).
   
   Could we also test `OutputReceiver<String>.output(...)` (and optionally 
`OutputReceiver<Row>.output(...)`) on `emptyWrapper` and `decodedZero` here?
   
   *(Minor nit: lines 815–824 also use FQNs for `StringUtf8Coder` and 
`PaneInfo`, which are already imported.)*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to