github-actions[bot] commented on code in PR #41572:
URL: https://github.com/apache/beam/pull/41572#discussion_r4660993050


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/IntrinsicMapTaskExecutorFactory.java:
##########
@@ -55,17 +60,25 @@
 import 
org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver;
 import org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoFn;
 import 
org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation;
+import 
org.apache.beam.runners.dataflow.worker.util.common.worker.RawWindowedByteSizeObservable;
 import 
org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation;
 import org.apache.beam.runners.dataflow.worker.util.common.worker.Receiver;
 import org.apache.beam.runners.dataflow.worker.util.common.worker.Sink;
+import 
org.apache.beam.runners.dataflow.worker.util.common.worker.StageTrampoline;
 import 
org.apache.beam.runners.dataflow.worker.util.common.worker.WriteOperation;
 import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.InstantCoder;
 import org.apache.beam.sdk.coders.KvCoder;
 import org.apache.beam.sdk.fn.IdGenerator;
 import org.apache.beam.sdk.options.PipelineOptions;
 import org.apache.beam.sdk.options.StreamingOptions;
+import org.apache.beam.sdk.transforms.reflect.FusedSegmentCompiler;

Review Comment:
   **🔴 Critical**: Several new classes referenced in this file and across the 
PR (`FusedSegmentCompiler`, `FastStatelessParDoFn`, `StageTrampoline`, 
`RawWindowedByteSizeObservable`, `InlineableFunctionProvider`, 
`HarnessStageTrampoline`, and the 
`:runners:google-cloud-dataflow-java:worker:jmh` directory in 
`settings.gradle.kts`) are missing from the commit. Please ensure all newly 
created files are staged and committed so the build succeeds.



##########
sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFnOutputReceivers.java:
##########
@@ -54,7 +56,39 @@ private RowOutputReceiver(
       this.context = context;
       this.builderSupplier = builderSupplier;
       this.tag = outputTag;
-      this.schemaCoder = schemaCoder;
+      this.fromRowFunction = schemaCoder.getFromRowFunction();
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public void output(Row value) {
+      if (Context.current() != Context.root()) {

Review Comment:
   **🟠 High**: `Context.current() != Context.root()` is always true whenever an 
incoming element has a non-root OpenTelemetry context (since `SimpleDoFnRunner` 
and `FnApiDoFnRunner` activate the element's context via 
`openTelemetryContext.makeCurrent()` before invoking `@ProcessElement`). This 
causes every element with tracing enabled to fall back to 
`OutputReceiver.super.output(value)` (allocating a builder and lambda per 
element) instead of only falling back when the `DoFn` itself modified the 
OpenTelemetry context.
   
   In `WindowedContextOutputReceiver` (lines 152 and 167), the 
`Context.current()` check can be removed altogether because 
`SimpleDoFnRunner.DoFnProcessContext` and 
`FnApiDoFnRunner.ProcessBundleContextBase` already check `currentOtel != 
Context.root() && currentOtel != elem.getOpenTelemetryContext()` inside 
`context.output(...)` and `context.outputWithTimestamp(...)`. For 
`RowOutputReceiver` (lines 65 and 81), delegating directly to 
`context.output(...)` / `context.outputWithTimestamp(...)` will likewise 
preserve any updated `Context.current()` without the unnecessary builder 
fallback.



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java:
##########
@@ -141,6 +201,272 @@ public PCollectionConsumerRegistry(
                 
.putAllWindowingStrategies(processBundleDescriptor.getWindowingStrategiesMap())
                 .build());
     this.dataSampler = dataSampler;
+    this.stageTrampoline = stageTrampoline;
+    this.trampolineThreshold = trampolineThreshold;
+    for (PTransform pTransform : 
processBundleDescriptor.getTransformsMap().values()) {
+      if 
(PTransformTranslation.FLATTEN_TRANSFORM_URN.equals(pTransform.getSpec().getUrn()))
 {
+        
this.flattenOutputPCollections.addAll(pTransform.getOutputsMap().values());
+      }
+      for (String outPc : pTransform.getOutputsMap().values()) {
+        this.pCollectionProducerCounts.merge(outPc, 1, Integer::sum);
+      }
+    }
+  }
+
+  private static final FnDataReceiver<WindowedValue<?>> 
CLAIMED_INLINE_CONSUMER =
+      elem -> {
+        throw new IllegalStateException("PCollection was claimed inline by a 
compiled segment");
+      };
+
+  private static final class PendingCompiledChain {
+    final List<FusedSegmentCompiler.StepSpec> stepsFromHeadToTail;
+    final FusedSegmentCompiler.CompiledNode tailNode;
+
+    PendingCompiledChain(
+        List<FusedSegmentCompiler.StepSpec> stepsFromHeadToTail,
+        FusedSegmentCompiler.CompiledNode tailNode) {
+      this.stepsFromHeadToTail = stepsFromHeadToTail;
+      this.tailNode = tailNode;
+    }
+  }
+
+  private static final class RunnerV2TailReceiver extends 
FusedSegmentCompiler.TailReceiver {
+    private final FnDataReceiver<WindowedValue<?>> downstream;
+
+    RunnerV2TailReceiver(FnDataReceiver<WindowedValue<?>> downstream) {
+      this.downstream = downstream;
+    }
+
+    @Override
+    public void accept(WindowedValue<?> elem) throws Exception {
+      downstream.accept(elem);
+    }
+  }
+
+  private final class RunnerV2StepHook<T> extends 
FusedSegmentCompiler.StepHook {
+    private final ExecutionState executionState;
+    private final ExecutionStateTracker executionStateTracker;
+    private final String ptransformId;
+    private final BundleCounter elementCountCounter;
+    private final SampleByteSizeDistribution<T> sampledByteSizeDistribution;
+    private final Coder<T> coder;
+
+    RunnerV2StepHook(String pCollectionId, Coder<T> coder, ConsumerAndMetadata 
consumerMeta) {
+      this.executionState = consumerMeta.getExecutionState();
+      this.executionStateTracker = consumerMeta.getExecutionStateTracker();
+      this.ptransformId = consumerMeta.getPTransformId();
+      this.coder = coder;
+
+      HashMap<String, String> labels = new HashMap<>();
+      labels.put(Labels.PCOLLECTION, pCollectionId);
+      MonitoringInfoMetricName elementCountMetricName =
+          
MonitoringInfoMetricName.named(MonitoringInfoConstants.Urns.ELEMENT_COUNT, 
labels);
+      String elementCountShortId =
+          shortIdMap.getOrCreateShortId(
+              new SimpleMonitoringInfoBuilder()
+                  .setUrn(MonitoringInfoConstants.Urns.ELEMENT_COUNT)
+                  .setType(TypeUrns.SUM_INT64_TYPE)
+                  .setLabels(labels)
+                  .build());
+      this.elementCountCounter =
+          Metrics.bundleProcessingThreadCounter(elementCountShortId, 
elementCountMetricName);
+      bundleProgressReporterRegistrar.register(elementCountCounter);
+
+      MonitoringInfoMetricName sampledByteSizeMetricName =
+          MonitoringInfoMetricName.named(Urns.SAMPLED_BYTE_SIZE, labels);
+      String sampledByteSizeShortId =
+          shortIdMap.getOrCreateShortId(
+              new SimpleMonitoringInfoBuilder()
+                  .setUrn(Urns.SAMPLED_BYTE_SIZE)
+                  .setType(TypeUrns.DISTRIBUTION_INT64_TYPE)
+                  .setLabels(labels)
+                  .build());
+      BundleDistribution sampledByteSizeUnderlyingDistribution =
+          Metrics.bundleProcessingThreadDistribution(
+              sampledByteSizeShortId, sampledByteSizeMetricName);
+      this.sampledByteSizeDistribution =
+          new 
SampleByteSizeDistribution<>(sampledByteSizeUnderlyingDistribution);
+      
bundleProgressReporterRegistrar.register(sampledByteSizeUnderlyingDistribution);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public @Nullable Object beforeStep(WindowedValue<?> elem) throws Exception 
{
+      this.elementCountCounter.inc(elem.getWindows().size());
+      this.sampledByteSizeDistribution.tryUpdate((T) elem.getValue(), 
this.coder);
+      this.executionState.activate();
+      return null;
+    }
+
+    @Override
+    public void afterStepNormal(WindowedValue<?> elem, @Nullable Object 
stateToken) {
+      this.executionState.deactivate();
+      this.sampledByteSizeDistribution.finishLazyUpdate();
+    }
+
+    @Override
+    public void afterStepException(Throwable t, WindowedValue<?> elem, 
@Nullable Object stateToken)
+        throws Exception {
+      this.executionState.deactivate();

Review Comment:
   **🟠 High**: In `RunnerV2StepHook.afterStepException` (and 
`afterFuncException` on line 346, as well as 
`MetricTrackingFnDataReceiver.acceptRaw` / `accept` on lines 790 and 828), 
`this.executionState.deactivate()` is called *before* `logAndRethrow(...)`. 
However, `logAndRethrow` checks `executionState.isActive()` and attributes the 
exception to the previous/enclosing `PTransform` 
(`executionStateTracker.getCurrentState()`) whenever 
`executionState.isActive()` is false. Deactivating before `logAndRethrow` will 
misattribute exceptions thrown by the step itself to the upstream caller 
instead of `ptransformId`. `deactivate()` should be called in a `finally` block 
wrapping `logAndRethrow` (matching the original `try 
(ExecutionState.ActiveState a = executionState.scopedActivate())` behavior).



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/data/PCollectionConsumerRegistry.java:
##########
@@ -141,6 +201,272 @@ public PCollectionConsumerRegistry(
                 
.putAllWindowingStrategies(processBundleDescriptor.getWindowingStrategiesMap())
                 .build());
     this.dataSampler = dataSampler;
+    this.stageTrampoline = stageTrampoline;
+    this.trampolineThreshold = trampolineThreshold;
+    for (PTransform pTransform : 
processBundleDescriptor.getTransformsMap().values()) {
+      if 
(PTransformTranslation.FLATTEN_TRANSFORM_URN.equals(pTransform.getSpec().getUrn()))
 {
+        
this.flattenOutputPCollections.addAll(pTransform.getOutputsMap().values());
+      }
+      for (String outPc : pTransform.getOutputsMap().values()) {
+        this.pCollectionProducerCounts.merge(outPc, 1, Integer::sum);
+      }
+    }
+  }
+
+  private static final FnDataReceiver<WindowedValue<?>> 
CLAIMED_INLINE_CONSUMER =
+      elem -> {
+        throw new IllegalStateException("PCollection was claimed inline by a 
compiled segment");
+      };
+
+  private static final class PendingCompiledChain {
+    final List<FusedSegmentCompiler.StepSpec> stepsFromHeadToTail;
+    final FusedSegmentCompiler.CompiledNode tailNode;
+
+    PendingCompiledChain(
+        List<FusedSegmentCompiler.StepSpec> stepsFromHeadToTail,
+        FusedSegmentCompiler.CompiledNode tailNode) {
+      this.stepsFromHeadToTail = stepsFromHeadToTail;
+      this.tailNode = tailNode;
+    }
+  }
+
+  private static final class RunnerV2TailReceiver extends 
FusedSegmentCompiler.TailReceiver {
+    private final FnDataReceiver<WindowedValue<?>> downstream;
+
+    RunnerV2TailReceiver(FnDataReceiver<WindowedValue<?>> downstream) {
+      this.downstream = downstream;
+    }
+
+    @Override
+    public void accept(WindowedValue<?> elem) throws Exception {
+      downstream.accept(elem);
+    }
+  }
+
+  private final class RunnerV2StepHook<T> extends 
FusedSegmentCompiler.StepHook {
+    private final ExecutionState executionState;
+    private final ExecutionStateTracker executionStateTracker;
+    private final String ptransformId;
+    private final BundleCounter elementCountCounter;
+    private final SampleByteSizeDistribution<T> sampledByteSizeDistribution;
+    private final Coder<T> coder;
+
+    RunnerV2StepHook(String pCollectionId, Coder<T> coder, ConsumerAndMetadata 
consumerMeta) {
+      this.executionState = consumerMeta.getExecutionState();
+      this.executionStateTracker = consumerMeta.getExecutionStateTracker();
+      this.ptransformId = consumerMeta.getPTransformId();
+      this.coder = coder;
+
+      HashMap<String, String> labels = new HashMap<>();
+      labels.put(Labels.PCOLLECTION, pCollectionId);
+      MonitoringInfoMetricName elementCountMetricName =
+          
MonitoringInfoMetricName.named(MonitoringInfoConstants.Urns.ELEMENT_COUNT, 
labels);
+      String elementCountShortId =
+          shortIdMap.getOrCreateShortId(
+              new SimpleMonitoringInfoBuilder()
+                  .setUrn(MonitoringInfoConstants.Urns.ELEMENT_COUNT)
+                  .setType(TypeUrns.SUM_INT64_TYPE)
+                  .setLabels(labels)
+                  .build());
+      this.elementCountCounter =
+          Metrics.bundleProcessingThreadCounter(elementCountShortId, 
elementCountMetricName);
+      bundleProgressReporterRegistrar.register(elementCountCounter);
+
+      MonitoringInfoMetricName sampledByteSizeMetricName =
+          MonitoringInfoMetricName.named(Urns.SAMPLED_BYTE_SIZE, labels);
+      String sampledByteSizeShortId =
+          shortIdMap.getOrCreateShortId(
+              new SimpleMonitoringInfoBuilder()
+                  .setUrn(Urns.SAMPLED_BYTE_SIZE)
+                  .setType(TypeUrns.DISTRIBUTION_INT64_TYPE)
+                  .setLabels(labels)
+                  .build());
+      BundleDistribution sampledByteSizeUnderlyingDistribution =
+          Metrics.bundleProcessingThreadDistribution(
+              sampledByteSizeShortId, sampledByteSizeMetricName);
+      this.sampledByteSizeDistribution =
+          new 
SampleByteSizeDistribution<>(sampledByteSizeUnderlyingDistribution);
+      
bundleProgressReporterRegistrar.register(sampledByteSizeUnderlyingDistribution);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public @Nullable Object beforeStep(WindowedValue<?> elem) throws Exception 
{
+      this.elementCountCounter.inc(elem.getWindows().size());
+      this.sampledByteSizeDistribution.tryUpdate((T) elem.getValue(), 
this.coder);
+      this.executionState.activate();

Review Comment:
   **🟠 High**: If `FusedSegmentCompiler` invokes `beforeStep` (or `beforeFunc` 
on line 324) outside the `try` block that triggers 
`afterStepException`/`afterFuncException`, any exception thrown by 
`sampledByteSizeDistribution.tryUpdate(...)` or between `beforeStep` and the 
`try` block will leave `executionState` activated. Also, in 
`afterStepException` / `afterFuncException`, if `t` is an `Error` (not an 
`instanceof Exception`) and the caller does not rethrow `t`, swallowing 
non-`Exception` throwables here would suppress fatal errors.



##########
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java:
##########
@@ -198,6 +208,148 @@ public final void addRunnerForPTransform(Context context) 
throws IOException {
         }
       }
     }
+
+    @SuppressWarnings({"unchecked", "nullness"})
+    private boolean tryAddInlineableFunctionRunner(Context context) throws 
IOException {
+      PTransform pTransform = context.getPTransform();
+      if 
(!PTransformTranslation.PAR_DO_TRANSFORM_URN.equals(pTransform.getSpec().getUrn())
+          || pTransform.getOutputsCount() != 1) {
+        return false;
+      }
+      ParDoPayload payload = 
ParDoPayload.parseFrom(pTransform.getSpec().getPayload());
+      if (!payload.getSideInputsMap().isEmpty()
+          || !payload.getStateSpecsMap().isEmpty()
+          || !payload.getTimerFamilySpecsMap().isEmpty()
+          || payload.getRequestsFinalization()) {
+        return false;
+      }
+      DoFn<?, ?> fn = ParDoTranslation.getDoFn(payload);
+      if (!(fn instanceof InlineableFunctionProvider)) {
+        return false;
+      }
+      DoFnSignature sig = DoFnSignatures.signatureForDoFn(fn);
+      if (sig.processElement().observesWindow()
+          || sig.processElement().isSplittable()
+          || sig.setup() != null
+          || sig.startBundle() != null
+          || sig.finishBundle() != null
+          || sig.teardown() != null
+          || sig.onWindowExpiration() != null) {
+        return false;
+      }

Review Comment:
   **🟡 Medium**: Calling `Pipeline.create()` inside 
`tryAddInlineableFunctionRunner` constructs a new `Pipeline` (and default 
`PipelineOptions`) for every inlineable `ParDo` transform during bundle 
processor initialization. 
`RehydratedComponents.forComponents(context.getComponents())` does not require 
a `Pipeline` instance strictly to call `getCoder(...)` (as done on line 433 of 
`FnApiDoFnRunner`). Removing `.withPipeline(Pipeline.create())` avoids 
unnecessary overhead during bundle setup.
   
   ```suggestion
         RehydratedComponents rehydrated = 
RehydratedComponents.forComponents(context.getComponents());
   ```



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/IntrinsicMapTaskExecutorFactory.java:
##########
@@ -153,8 +169,319 @@ public DataflowMapTaskExecutor create(
       LOG.info("Map task network: {}", Networks.toDot(network));
     }
 
-    return IntrinsicMapTaskExecutor.withSharedCounterSet(
-        topoSortedOperations, counterSet, 
executionContext.getExecutionStateTracker());
+    IntrinsicMapTaskExecutor executor =
+        IntrinsicMapTaskExecutor.withSharedCounterSet(
+            topoSortedOperations, counterSet, 
executionContext.getExecutionStateTracker());
+    installStageTrampolineIfNeeded(network, topoOrder, topoSortedOperations, 
executor, options);
+    installCompiledSegmentsIfPossible(network, topoOrder, options);
+    return executor;
+  }
+
+  @SuppressWarnings({"unchecked", "nullness"})
+  private static void installCompiledSegmentsIfPossible(
+      Network<Node, Edge> network, List<Node> topoOrder, PipelineOptions 
options) {
+    List<String> experiments = 
options.as(DataflowPipelineDebugOptions.class).getExperiments();
+    if (experiments != null
+        && 
experiments.contains(FusedSegmentCompiler.DISABLE_CODEGEN_EXPERIMENT)) {
+      return;
+    }
+
+    Set<OperationNode> claimedOps = new HashSet<>();
+    for (Node node : topoOrder) {
+      if (!(node instanceof OperationNode)) {
+        continue;
+      }
+      OperationNode headNode = (OperationNode) node;
+      if (claimedOps.contains(headNode)) {
+        continue;
+      }
+      FastStatelessParDoFn<?, ?> headFn = extractCompilableParDoFn(headNode);
+      if (headFn == null) {
+        continue;
+      }
+
+      List<FastStatelessParDoFn.ChainLink> links = new ArrayList<>();
+      OperationNode curOpNode = headNode;
+      while (network.outDegree(curOpNode) == 1) {
+        Node succ = Iterables.getOnlyElement(network.successors(curOpNode));
+        if (!(succ instanceof OutputReceiverNode)) {
+          break;
+        }
+        OutputReceiverNode outNode = (OutputReceiverNode) succ;
+        OutputReceiver outRecv = outNode.getOutputReceiver();
+        if (!outRecv.hasSimpleSinglePath()
+            || network.inDegree(outNode) != 1
+            || network.outDegree(outNode) != 1) {
+          break;
+        }
+        Node nextCandidate = 
Iterables.getOnlyElement(network.successors(outNode));
+        if (!(nextCandidate instanceof OperationNode)
+            || network.inDegree(nextCandidate) != 1
+            || claimedOps.contains(nextCandidate)) {
+          break;
+        }
+        OperationNode nextOpNode = (OperationNode) nextCandidate;
+        FastStatelessParDoFn<?, ?> nextFn = 
extractCompilableParDoFn(nextOpNode);
+        if (nextFn == null) {
+          break;
+        }
+        ParDoOperation nextParDoOp = (ParDoOperation) 
nextOpNode.getOperation();
+        OperationContext.FastProcessContext fastCtx = 
nextParDoOp.getFastProcessContext();
+        if (fastCtx == null) {
+          break;
+        }
+
+        links.add(new FastStatelessParDoFn.ChainLink(outRecv.getOnlyCounter(), 
fastCtx, nextFn));
+        claimedOps.add(nextOpNode);
+        curOpNode = nextOpNode;
+      }
+
+      if (!links.isEmpty()) {
+        claimedOps.add(headNode);
+        headFn.setDownstreamChain(links);
+      }
+    }
+  }
+
+  @SuppressWarnings("nullness")
+  private static FastStatelessParDoFn<?, ?> 
extractCompilableParDoFn(OperationNode opNode) {
+    Operation op = opNode.getOperation();
+    if (!(op instanceof ParDoOperation)) {
+      return null;
+    }
+    ParDoOperation parDoOp = (ParDoOperation) op;
+    if (parDoOp.getFastProcessContext() == null) {
+      return null;
+    }
+    try {
+      ParDoFn fn = parDoOp.getFn();
+      if (fn instanceof FastStatelessParDoFn) {
+        FastStatelessParDoFn<?, ?> fastFn = (FastStatelessParDoFn<?, ?>) fn;
+        if (fastFn.canCompileInSegment()) {
+          return fastFn;
+        }
+      }
+    } catch (Exception ignored) {
+      // ignore
+    }
+    return null;
+  }
+
+  static final int DEFAULT_TRAMPOLINE_FUSION_THRESHOLD = 90;
+  static final int DEFAULT_COMPILED_TRAMPOLINE_THRESHOLD = 115;
+  private static final String TRAMPOLINE_THRESHOLD_PREFIX = 
"trampoline_fusion_threshold=";
+  private static final String DISABLE_TRAMPOLINE_EXPERIMENT = 
"disable_fusion_trampoline";
+
+  static int resolveTrampolineThreshold(PipelineOptions options) {
+    List<String> experiments = 
options.as(DataflowPipelineDebugOptions.class).getExperiments();
+    if (experiments != null) {
+      if (experiments.contains(DISABLE_TRAMPOLINE_EXPERIMENT)) {
+        return 0;
+      }
+      for (String exp : experiments) {
+        if (exp != null && exp.startsWith(TRAMPOLINE_THRESHOLD_PREFIX)) {
+          return 
Integer.parseInt(exp.substring(TRAMPOLINE_THRESHOLD_PREFIX.length()));

Review Comment:
   **🟢 Low**: If a user specifies a malformed experiment such as 
`trampoline_fusion_threshold=abc`, `Integer.parseInt` will throw an unhandled 
`NumberFormatException` with no context about which experiment failed. Consider 
logging a warning or throwing an `IllegalArgumentException` mentioning the 
invalid experiment value.



-- 
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