reuvenlax commented on code in PR #41541:
URL: https://github.com/apache/beam/pull/41541#discussion_r4743930532


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowExecutionContext.java:
##########
@@ -421,78 +876,151 @@ protected void reportBundleLull(Thread trackedThread, 
long millisElapsedSinceBun
      */
     @Override
     public Closeable enterState(ExecutionState newState) {
-      Closeable baseCloseable = super.enterState(newState);
+      if (isSimpleStateTransition) {
+        return super.enterState(newState);
+      }
       final boolean isDataflowProcessElementState =
-          newState.isProcessElementState && newState instanceof 
DataflowExecutionState;
-      if (isDataflowProcessElementState) {
-        DataflowExecutionState newDFState = (DataflowExecutionState) newState;
+          newState instanceof DataflowExecutionState && 
newState.isProcessElementState;
+      if (!isDataflowProcessElementState) {
+        return super.enterState(newState);
+      }
+      DataflowExecutionState newDFState = (DataflowExecutionState) newState;
+      final boolean trackElementExecution =
+          elementExecutionTracker != ElementExecutionTracker.NO_OP_INSTANCE;
+      final ExecutionState previous = enterStateDirect(newState);
+      boolean activatedStreaming = false;
+      try {
         if (isStreaming) {
-          if (newDFState.getStepName() != null && 
newDFState.getStepName().userName() != null) {
-            recordActiveMessageInProcessingTimesMap();
-            synchronized (this) {
-              this.activeMessageMetadata =
-                  ActiveMessageMetadata.create(
-                      newDFState.getStepName().userName(), 
Stopwatch.createStarted());
+          NameContext stepName = newDFState.getStepName();
+          String userName = stepName != null ? stepName.userName() : null;
+          if (userName != null) {
+            StepProcessingStats stepStats = getStepStatsFast(userName);
+            long nowNanos = System.nanoTime();
+            StepProcessingStats prevActive = localActiveStepStats;
+            if (prevActive != null) {
+              recordElapsedNanos(prevActive, nowNanos - (long) 
ACTIVE_START_NANOS.get(this));
             }
+            setActiveMessage(stepStats, nowNanos);
+            activatedStreaming = true;
           }
         }
-        elementExecutionTracker.enter(newDFState.getStepName());
+        if (trackElementExecution) {
+          elementExecutionTracker.enter(newDFState.getStepName());
+        }
+      } catch (Throwable t) {
+        if (activatedStreaming) {
+          clearActiveMessage();
+        }
+        try {
+          exitStateDirect(previous);
+        } catch (Throwable suppressed) {
+          t.addSuppressed(suppressed);
+        }
+        throw t;
       }
 
       return () -> {
-        if (isDataflowProcessElementState) {
-          if (isStreaming) {
-            recordActiveMessageInProcessingTimesMap();
+        if (isStreaming) {
+          StepProcessingStats active = localActiveStepStats;
+          if (active != null) {
+            recordElapsedNanos(active, System.nanoTime() - (long) 
ACTIVE_START_NANOS.get(this));
+            clearActiveMessage();
           }
+        }
+        if (trackElementExecution) {
           elementExecutionTracker.exit();
         }
-        baseCloseable.close();
+        exitStateDirect(previous);
       };
     }
 
     public String getWorkItemId() {
       return this.workItemId;
     }
 
-    public synchronized Optional<ActiveMessageMetadata> 
getActiveMessageMetadata() {
-      return Optional.ofNullable(activeMessageMetadata);
+    private static Stopwatch createStopwatchStartedAt(long startNanos) {
+      Ticker ticker =
+          new Ticker() {
+            private boolean firstRead = true;
+
+            @Override
+            public long read() {
+              if (firstRead) {
+                firstRead = false;
+                return startNanos;
+              }
+              return System.nanoTime();
+            }
+          };
+      return Stopwatch.createStarted(ticker);
     }
 
-    public synchronized Map<String, IntSummaryStatistics> 
getProcessingTimesByStepCopy() {
-      Map<String, IntSummaryStatistics> processingTimesCopy =
-          processingTimesByStep.entrySet().stream()
-              .collect(
-                  Collectors.toMap(
-                      e -> e.getKey(),
-                      e -> {
-                        IntSummaryStatistics clone = new 
IntSummaryStatistics();
-                        clone.combine(e.getValue());
-                        return clone;
-                      }));
-      return processingTimesCopy;
+    /**
+     * Reads a consistent snapshot of the currently active streaming step and 
its start time using
+     * the {@code activeSeq} seqlock (allocating a {@link Stopwatch} only here 
on the cold reader
+     * path, never on the hot execution path).
+     *
+     * <p>Retries are bounded to {@code MAX_ACTIVE_METADATA_ATTEMPTS} (64) so 
a fast-transitioning
+     * stage or preempted writer cannot starve Windmill heartbeat threads; if 
{@code activeSeq}
+     * keeps advancing across every attempt, no single element is stalled, so 
returning {@link
+     * Optional#empty()} is safe.
+     */
+    public Optional<ActiveMessageMetadata> getActiveMessageMetadata() {
+      for (int attempt = 0; attempt < MAX_ACTIVE_METADATA_ATTEMPTS; attempt++) 
{
+        // 1. Read starting activeSeq with acquire semantics, synchronizing 
with the writer's
+        //    closing ACTIVE_SEQ.setRelease(s1). Odd means 
setActiveMessage()/reset() is active.
+        long s1 = (long) ACTIVE_SEQ.getAcquire(this);
+        if ((s1 & 1L) != 0L) {
+          seqlockBackoff(attempt);
+          continue;
+        }
+        // 2. Read activeStepName. If clearActiveMessage() nulled it out 
without advancing
+        //    activeSeq, loadLoadFence + matching s2 == s1 confirms the clear 
and returns empty.
+        String stepName = (String) ACTIVE_STEP_NAME.getOpaque(this);
+        if (stepName == null) {
+          VarHandle.loadLoadFence();
+          if ((long) ACTIVE_SEQ.getOpaque(this) == s1) {
+            return Optional.empty();
+          }
+          seqlockBackoff(attempt);
+          continue;
+        }
+        // 3. Read activeStartNanos, then fence before checking the closing 
activeSeq. Because
+        //    clearActiveMessage() leaves activeStartNanos untouched, if s2 == 
s1 no subsequent
+        //    setActiveMessage() or reset() intervened, so (stepName, 
startNanos) is an exact pair.
+        long startNanos = (long) ACTIVE_START_NANOS.getOpaque(this);
+        VarHandle.loadLoadFence();
+        if ((long) ACTIVE_SEQ.getOpaque(this) == s1) {
+          return Optional.of(
+              ActiveMessageMetadata.create(stepName, 
createStopwatchStartedAt(startNanos)));

Review Comment:
   Done — replaced Stopwatch in ActiveMessageMetadata with startTimeNanos() + 
elapsedMillis(), removed createStopwatchStartedAt / anonymous Ticker, and 
updated Work and getBundleLullMessage to use elapsedMillis() (which also fixes 
the pre-existing clock.currentTimeMillis() - stopwatch.elapsed(...) bug in the 
lull log).



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