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


##########
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:
   emoved stepStatsBuffer, stepStatsCount, and synchronized registration. 
getOrCreateStepStats now just uses stepStatsByName.computeIfAbsent(...), and 
reset() / getProcessingTimesByStepCopy() iterate stepStatsByName.values() 
directly.



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