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


##########
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:
   can we change ActiveMessageMetadata to include a start time instead of a 
stopwatch?  It seems like all the users just get the elapsed time which they 
can calculate themselves from the start time.  Then we can simplify here.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowOperationContext.java:
##########
@@ -117,9 +144,18 @@ public Closeable enterStart() {
     return enter(startState);
   }
 
+  /**
+   * Enters the {@code process} execution state.
+   *
+   * <p>For allocation-free execution, the returned {@link Closeable} may be 
reused across
+   * sequential calls on the execution thread. Callers must always pair it via 
{@code

Review Comment:
   this comment isn't clear to me.  if we can't reclose after a subsequen 
enterProcess call when would we reuse it?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowOperationContext.java:
##########
@@ -157,6 +193,96 @@ private Closeable enter(ExecutionState state) {
     return executionStateTracker.enterState(state);
   }
 
+  private interface ProcessScope extends Closeable {
+    Closeable enter();
+  }
+
+  private static final class DirectProcessScope implements ProcessScope {
+    private final ExecutionStateTracker tracker;
+    private final ExecutionState processElementState;
+    private boolean inUse;
+    private @Nullable ExecutionState previous;
+
+    DirectProcessScope(ExecutionStateTracker tracker, ExecutionState 
processElementState) {
+      this.tracker = tracker;
+      this.processElementState = processElementState;
+    }
+
+    @Override
+    public Closeable enter() {
+      if (!inUse) {
+        inUse = true;
+        try {
+          previous = tracker.enterStateDirect(processElementState);
+          return this;
+        } catch (Throwable t) {
+          inUse = false;
+          previous = null;
+          throw t;
+        }
+      }
+      return tracker.enterState(processElementState);
+    }
+
+    @Override
+    public void close() {
+      if (!inUse) {
+        return;
+      }
+      ExecutionState prev = previous;
+      previous = null;
+      inUse = false;
+      tracker.exitStateDirect(prev);
+    }
+  }
+
+  private static final class StreamingProcessScope implements ProcessScope {
+    private final DataflowExecutionStateTracker tracker;
+    private final ExecutionState processElementState;
+    private final @Nullable StepProcessingStats stepStats;
+    private boolean inUse;
+    private @Nullable ExecutionState previous;
+
+    StreamingProcessScope(
+        DataflowExecutionStateTracker tracker,
+        ExecutionState processElementState,
+        @Nullable StepProcessingStats stepStats) {
+      this.tracker = tracker;
+      this.processElementState = processElementState;
+      this.stepStats = stepStats;
+    }
+
+    @Override
+    public Closeable enter() {
+      if (!inUse) {
+        inUse = true;
+        try {
+          previous =
+              stepStats != null
+                  ? tracker.enterStreamingProcessDirect(processElementState, 
stepStats)
+                  : tracker.enterStateDirect(processElementState);
+          return this;
+        } catch (Throwable t) {
+          inUse = false;
+          previous = null;
+          throw t;
+        }
+      }
+      return tracker.enterState(processElementState);
+    }
+
+    @Override
+    public void close() {
+      if (!inUse) {

Review Comment:
   ditto



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowOperationContext.java:
##########
@@ -157,6 +193,96 @@ private Closeable enter(ExecutionState state) {
     return executionStateTracker.enterState(state);
   }
 
+  private interface ProcessScope extends Closeable {
+    Closeable enter();
+  }
+
+  private static final class DirectProcessScope implements ProcessScope {
+    private final ExecutionStateTracker tracker;
+    private final ExecutionState processElementState;
+    private boolean inUse;
+    private @Nullable ExecutionState previous;
+
+    DirectProcessScope(ExecutionStateTracker tracker, ExecutionState 
processElementState) {
+      this.tracker = tracker;
+      this.processElementState = processElementState;
+    }
+
+    @Override
+    public Closeable enter() {
+      if (!inUse) {
+        inUse = true;
+        try {
+          previous = tracker.enterStateDirect(processElementState);
+          return this;
+        } catch (Throwable t) {
+          inUse = false;
+          previous = null;
+          throw t;
+        }
+      }
+      return tracker.enterState(processElementState);
+    }
+
+    @Override
+    public void close() {
+      if (!inUse) {

Review Comment:
   should this be a checkState?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowExecutionContext.java:
##########
@@ -332,6 +624,164 @@ public DataflowExecutionStateTracker(
       } else {
         this.isStreaming = false;
       }
+      boolean noOpElementTracker =
+          this.elementExecutionTracker == 
ElementExecutionTracker.NO_OP_INSTANCE;

Review Comment:
   This NO_OP_INSTANCE appears just not used for experiment time_per_element 
which is very old.  Should we just remove support for that experiment?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowExecutionContext.java:
##########
@@ -261,30 +265,318 @@ public ExecutionStateTracker getExecutionStateTracker() {
 
   /**
    * An extension of {@link ExecutionStateTracker} that also installs a {@link 
MetricsContainer}
-   * using the current state to locate the {@link MetricsEnvironment}.
+   * using the current state to locate the {@link MetricsEnvironment}, and 
tracks streaming
+   * active-element latency and per-step processing-time distributions on the 
hot execution path.
+   *
+   * <p>To avoid locks and per-element object allocations (such as {@link 
Stopwatch} / {@link
+   * ActiveMessageMetadata} instances), this tracker exposes mutable streaming 
state to concurrent
+   * heartbeat, lull-reporting, and work-completion reader threads using two 
single-writer,
+   * multi-reader sequence locks (seqlocks) implemented with {@link VarHandle}:
+   *
+   * <ul>
+   *   <li>{@code activeSeq} guards the currently executing {@code 
(activeStepName,
+   *       activeStartNanos)} pair read by {@link #getActiveMessageMetadata()}.
+   *   <li>{@code StepProcessingStats.seq} guards each step's {@code (count, 
sum, min, max)}
+   *       statistics read by {@link #getProcessingTimesByStepCopy()}.
+   * </ul>
+   *
+   * <p>Registered {@code StepProcessingStats} instances are also published 
without locks via a
+   * monotonically growing {@code stepStatsBuffer} + volatile {@code 
stepStatsCount} pair.
+   *
+   * <p>All mutations on the hot path are performed by the single tracked 
execution thread; cold
+   * lifecycle transitions ({@link #activate()}, {@link #deactivate()}, {@link 
#reset()}) hold the
+   * tracker's monitor lock, establishing happens-before across thread 
handoffs between bundles.
    */
   public static class DataflowExecutionStateTracker extends 
ExecutionStateTracker {
 
+    private static final long NANOS_PER_MILLI = 1_000_000L;
+    private static final StepProcessingStats[] EMPTY_STEP_STATS = new 
StepProcessingStats[0];
+    private static final int MAX_ACTIVE_METADATA_ATTEMPTS = 64;
+    private static final long SEQLOCK_PARK_NANOS = 10_000L;
+
+    private static final VarHandle ACTIVE_SEQ;
+    private static final VarHandle ACTIVE_STEP_NAME;
+    private static final VarHandle ACTIVE_START_NANOS;
+
+    static {
+      try {
+        MethodHandles.Lookup lookup = MethodHandles.lookup();
+        ACTIVE_SEQ =
+            lookup.findVarHandle(DataflowExecutionStateTracker.class, 
"activeSeq", long.class);
+        ACTIVE_STEP_NAME =
+            lookup.findVarHandle(
+                DataflowExecutionStateTracker.class, "activeStepName", 
String.class);
+        ACTIVE_START_NANOS =
+            lookup.findVarHandle(
+                DataflowExecutionStateTracker.class, "activeStartNanos", 
long.class);
+      } catch (ReflectiveOperationException e) {
+        throw new ExceptionInInitializerError(e);
+      }
+    }
+
+    @SuppressWarnings("ThreadPriorityCheck") // Seqlock reader backoff for a 
preempted writer.
+    private static void seqlockBackoff(int attempt) {
+      if (attempt < 16) {
+        Thread.onSpinWait();
+      } else if (attempt < 32 || Thread.currentThread().isInterrupted()) {
+        // LockSupport.parkNanos returns immediately while the interrupt flag 
is set; yield
+        // instead to avoid busy-spinning without clearing the interrupt 
status.
+        Thread.yield();
+      } else {
+        LockSupport.parkNanos(SEQLOCK_PARK_NANOS);
+      }
+    }
+
+    /**
+     * Lock-free per-step processing time summary written exclusively by the 
tracked execution
+     * thread via {@link VarHandle} stores and read concurrently by heartbeat, 
lull-reporting, and
+     * completion threads using a sequence lock ({@code seq}).
+     *
+     * <p><b>Seqlock protocol ({@code seq}):</b> {@code seq} is a strictly 
monotonic version counter
+     * whose parity encodes whether a multi-field update is in progress:
+     *
+     * <ul>
+     *   <li><b>Even {@code seq}:</b> {@code (count, sum, min, max)} is 
consistent and readable.
+     *   <li><b>Odd {@code seq}:</b> the writer is updating one or more of 
those fields; readers
+     *       must back off and retry rather than trusting the payload.
+     * </ul>
+     *
+     * <p>Every non-trivial update ({@link #record(int)}) and {@link #reset()} 
advances {@code seq}
+     * {@code s → s+1 (odd) → s+2 (even)} without ever resetting it to zero, 
preventing ABA races
+     * across sequential writes or cross-bundle resets.
+     *
+     * <p><b>Barrier pairing (x86_64/TSO and ARM64/weak memory models):</b>
+     *
+     * <pre>{@code
+     * Writer (record):                       Reader (snapshot):
+     *   SEQ.setOpaque(s + 1)   // odd          s1 = SEQ.getAcquire()   // 
must be even
+     *   storeStoreFence()      // dmb ishst    c/sum/min/max = *.getOpaque()
+     *   count/sum/min/max = *.setOpaque(...)   loadLoadFence()         // dmb 
ishld
+     *   SEQ.setRelease(s + 2)  // even         s2 = SEQ.getOpaque()    // 
verify s2 == s1
+     * }</pre>
+     *
+     * {@link VarHandle#storeStoreFence()} (rather than {@code setRelease(s + 
1)}) is required on
+     * entry to the write window because a release store only prevents 
<em>earlier</em> stores from
+     * drifting after it, not <em>later</em> payload stores from hoisting 
ahead of it. On the reader
+     * side, {@code getAcquire()} orders {@code s1} before payload loads (and 
synchronizes with the
+     * writer's prior {@code setRelease(s1)}), and {@link 
VarHandle#loadLoadFence()} stops the
+     * closing {@code s2 = SEQ.getOpaque()} validation load from hoisting 
ahead of the payload
+     * loads. Both fences are free compiler barriers on x86_64.
+     *
+     * <p><b>Fast path for 0 ms elements ({@link #recordZeroMillis()}):</b> 
once at least one sample
+     * with {@code 0} has been recorded (so {@code min <= 0 <= max}), another 
0 ms element changes
+     * only {@code count} — {@code sum}, {@code min}, and {@code max} stay 
invariant. In that case
+     * the writer executes a single {@code COUNT.setRelease(count + 1)} 
<em>without</em> bumping
+     * {@code seq}. Because {@code s1 = SEQ.getAcquire()} in {@link 
#snapshot()} already makes the
+     * published {@code sum/min/max} visible, observing either {@code c} or 
{@code c + 1} produces a
+     * valid, linearizable snapshot while keeping {@code seq} completely quiet 
for sub-millisecond
+     * elements (avoiding both writer barriers and reader retry churn).
+     *
+     * <p><b>Plain single-writer reads:</b> the execution thread reads its own 
fields with plain
+     * {@link VarHandle#get} instead of maintaining duplicate shadow fields; 
cross-thread {@link
+     * #reset()} and {@link DataflowExecutionStateTracker#activate()} are both 
{@code synchronized}
+     * on the enclosing tracker so happens-before holds across bundle 
handoffs. Without duplicate
+     * shadows this object is ~48 bytes (fitting in a single 64-byte cache 
line under compressed
+     * OOPs).
+     */
+    static final class StepProcessingStats {
+      private static final VarHandle SEQ;
+      private static final VarHandle COUNT;
+      private static final VarHandle SUM;
+      private static final VarHandle MIN;
+      private static final VarHandle MAX;
+
+      static {
+        try {
+          MethodHandles.Lookup lookup = MethodHandles.lookup();
+          SEQ = lookup.findVarHandle(StepProcessingStats.class, "seq", 
long.class);
+          COUNT = lookup.findVarHandle(StepProcessingStats.class, "count", 
long.class);
+          SUM = lookup.findVarHandle(StepProcessingStats.class, "sum", 
long.class);
+          MIN = lookup.findVarHandle(StepProcessingStats.class, "min", 
int.class);
+          MAX = lookup.findVarHandle(StepProcessingStats.class, "max", 
int.class);
+        } catch (ReflectiveOperationException e) {
+          throw new ExceptionInInitializerError(e);
+        }
+      }
+
+      final String stepName;
+
+      // Single-writer fields read via plain VarHandle.get() by the execution 
thread and via
+      // acquire/opaque loads by concurrent reader threads. Declared volatile 
so Java's memory
+      // model guarantees 64-bit atomicity even if accessed directly; all 
hot-path reads/writes
+      // route through the VarHandles above to avoid unnecessary fences.
+      @SuppressWarnings("UnusedVariable")
+      private volatile long seq;
+
+      @SuppressWarnings("UnusedVariable")
+      private volatile long count;
+
+      @SuppressWarnings("UnusedVariable")
+      private volatile long sum;
+
+      @SuppressWarnings("UnusedVariable")
+      private volatile int min = Integer.MAX_VALUE;
+
+      @SuppressWarnings("UnusedVariable")
+      private volatile int max = Integer.MIN_VALUE;
+
+      StepProcessingStats(String stepName) {
+        this.stepName = stepName;
+      }
+
+      void recordZeroMillis() {
+        // Common fast path: once min <= 0 <= max is already published, a 0 ms 
sample leaves
+        // sum/min/max unchanged, so only count needs a single release store 
(no seqlock bump).
+        // First 0 ms sample falls through to record(0) so seq bumps once and 
establishes min = 0.
+        if ((int) MIN.get(this) <= 0 && (int) MAX.get(this) >= 0) {
+          COUNT.setRelease(this, (long) COUNT.get(this) + 1L);
+          return;
+        }
+        record(0);
+      }
+
+      void record(int processingTimeMillis) {
+        // Only primitive ops occur inside the odd window, so no exception can 
leave seq stuck odd.
+        long s = (long) SEQ.get(this);
+        // 1. Open write window (even -> odd). storeStoreFence ensures readers 
observing any new
+        //    payload value below will also see seq >= s + 1 on their closing 
seq check.
+        SEQ.setOpaque(this, s + 1L);
+        VarHandle.storeStoreFence();
+        // 2. Opaque payload writes prevent 64-bit tearing and dead-store 
elimination without
+        // fences.
+        COUNT.setOpaque(this, (long) COUNT.get(this) + 1L);
+        if (processingTimeMillis != 0) {
+          SUM.setOpaque(this, (long) SUM.get(this) + processingTimeMillis);
+        }
+        if (processingTimeMillis < (int) MIN.get(this)) {
+          MIN.setOpaque(this, processingTimeMillis);
+        }
+        if (processingTimeMillis > (int) MAX.get(this)) {
+          MAX.setOpaque(this, processingTimeMillis);
+        }
+        // 3. Close write window (odd -> even). Release semantics guarantee 
all payload writes
+        //    above are visible to any reader whose SEQ.getAcquire() observes 
s + 2.
+        SEQ.setRelease(this, s + 2L);
+      }
+
+      void reset() {
+        // Cold path called under the tracker's monitor lock between bundles. 
Seed from volatile seq
+        // (never reset to 0) so a cross-thread reset() strictly advances past 
any sequence a
+        // concurrent reader may be validating, prevents ABA, and heals odd 
parity if ever skewed.
+        long s = (long) SEQ.getVolatile(this);
+        long odd = (s & 1L) != 0L ? s + 2L : s + 1L;
+        SEQ.setVolatile(this, odd);
+        COUNT.setVolatile(this, 0L);
+        SUM.setVolatile(this, 0L);
+        MIN.setVolatile(this, Integer.MAX_VALUE);
+        MAX.setVolatile(this, Integer.MIN_VALUE);
+        SEQ.setVolatile(this, odd + 1L);
+      }
+
+      @VisibleForTesting
+      long getSeqForTesting() {
+        return (long) SEQ.getVolatile(this);
+      }
+
+      /**
+       * Returns a consistent snapshot of this step's statistics, or {@code 
null} if {@code count ==
+       * 0}. Retries are unbounded because completion/lull snapshots require 
exact per-step counts
+       * and {@code seq} only advances on {@code >= 1 ms} elements (sub-ms 
completions take the
+       * seq-free {@link #recordZeroMillis()} fast path).
+       */
+      @Nullable IntSummaryStatistics snapshot() {
+        int attempt = 0;
+        while (true) {
+          // 1. Read starting seq with acquire semantics, synchronizing with 
the writer's closing
+          //    SEQ.setRelease(s1) so all fields from version s1 are visible 
below.
+          long s1 = (long) SEQ.getAcquire(this);
+          if ((s1 & 1L) != 0L) {
+            // Writer is inside record() or reset(); wait for an even sequence 
number.
+            seqlockBackoff(attempt);
+            if (attempt < 32) {
+              attempt++;
+            }
+            continue;
+          }
+          // 2. Read payload optimistically with opaque loads (atomic, 
un-hoisted).
+          long c = (long) COUNT.getOpaque(this);
+          if (c == 0L) {
+            // Confirm count == 0 wasn't caught mid-reset or mid-first-record 
before returning null.
+            VarHandle.loadLoadFence();
+            if ((long) SEQ.getOpaque(this) == s1) {
+              return null;
+            }
+            seqlockBackoff(attempt);
+            if (attempt < 32) {
+              attempt++;
+            }
+            continue;
+          }
+          long total = (long) SUM.getOpaque(this);
+          int lo = (int) MIN.getOpaque(this);
+          int hi = (int) MAX.getOpaque(this);
+          // 3. loadLoadFence keeps all payload loads ordered before the 
closing seq check.
+          //    If seq is still s1, no record() or reset() overlapped our read 
window (at most
+          //    seq-free recordZeroMillis() increments of count ran, keeping 
sum/min/max valid).
+          //    lo <= hi guards IntSummaryStatistics' constructor precondition 
defensively.
+          VarHandle.loadLoadFence();
+          if ((long) SEQ.getOpaque(this) == s1 && lo <= hi) {
+            return new IntSummaryStatistics(c, lo, hi, total);
+          }
+          seqlockBackoff(attempt);
+          if (attempt < 32) {
+            attempt++;
+          }
+        }
+      }
+    }
+
     private final ElementExecutionTracker elementExecutionTracker;
     private final DataflowOperationContext.DataflowExecutionState otherState;
     private final ContextActivationObserverRegistry 
contextActivationObserverRegistry;
     private final String workItemId;
 
     private final boolean isStreaming;
+    private final boolean isSimpleStateTransition;
+    private final boolean supportsFastProcessTransition;
 
-    /**
-     * Metadata on the message whose processing is currently being managed by 
this tracker. If no
-     * message is actively being processed, activeMessageMetadata will be null.
-     */
-    @GuardedBy("this")
-    @Nullable
-    private ActiveMessageMetadata activeMessageMetadata = null;
+    // Sequence lock guarding (activeStepName, activeStartNanos). Uses the 
same even/odd protocol
+    // and VarHandle fence pairing as StepProcessingStats.seq:
+    //   - Even activeSeq: stable, readable (activeStepName, activeStartNanos) 
snapshot.
+    //   - Odd activeSeq: writer is in setActiveMessage() or reset(); readers 
must retry.
+    // Strictly monotonic (never reset to 0) so readers cannot confuse a 
reused pair across fused
+    // steps, repeated elements, or bundle resets (no ABA). 
clearActiveMessage() does not bump
+    // activeSeq: it only sets activeStepName to null via setRelease(), 
leaving activeStartNanos
+    // unchanged so a concurrent reader still observes either empty or the 
prior matching pair.
+    @SuppressWarnings("UnusedVariable")
+    private volatile long activeSeq = 0L;
+
+    @SuppressWarnings("UnusedVariable")
+    private volatile @Nullable String activeStepName = null;
+
+    @SuppressWarnings("UnusedVariable")
+    private volatile long activeStartNanos = 0L;
+
+    // Execution-thread-only references (reset under tracker monitor lock in 
reset()).
+    private @Nullable StepProcessingStats localActiveStepStats = null;
+    private @Nullable String lastLookupStepName = null;
+    private @Nullable StepProcessingStats lastLookupStepStats = null;
 
     /** Clock used to either provide real system time or mocked to virtualize 
time for testing. */
     private final Clock clock;
 
-    @GuardedBy("this")
-    private final Map<String, IntSummaryStatistics> processingTimesByStep = 
new HashMap<>();
+    // Registered step stats (append-only across a worker tracker's lifetime):

Review Comment:
   Is the StepProcessingStats array and count needed? 
   
   It is used in reset, but concurrenthashmap iteration seems likely fine for 
reset as it is per budnle.
   It is used for the lull copy, but that is expensive anyway and only if 
things are slow so I don't think we need the complication.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowOperationContext.java:
##########
@@ -157,6 +193,96 @@ private Closeable enter(ExecutionState state) {
     return executionStateTracker.enterState(state);
   }
 
+  private interface ProcessScope extends Closeable {
+    Closeable enter();
+  }
+
+  private static final class DirectProcessScope implements ProcessScope {

Review Comment:
   can we merge this and the other process scope? Seems like it is equivalent 
if stepStats is null?



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