You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "parveensania (via GitHub)" <gi...@apache.org> on 2026/03/12 21:26:44 UTC

[PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

parveensania opened a new pull request, #37840:
URL: https://github.com/apache/beam/pull/37840

   Adds a FailoverChannel wrapper class on top of IsolationChannels to maintain primary channel and failover channel and fallback to failover channel if connectivity over primary channel cannot be established. The primary channel will again be retried after a period. 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979102711


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:

Review Comment:
   Done. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050380683

   Assigning reviewers:
   
   R: @Abacn added as fallback since no labels match configuration
   
   
   Note: If you would like to opt out of this review, comment `assign to next reviewer`.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979098410


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:
+      case UNKNOWN:
+        return true;
+      default:
+        return false;
+    }
+  }
+
+  private boolean hasFallbackChannel() {
+    return fallback != null;
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  private boolean shouldFallBackDueToPrimaryState() {
+    ConnectivityState connectivityState = primary.getState(true);
+    if (connectivityState == ConnectivityState.READY) {
+      primaryNotReadySinceNanos.set(-1);
+      return false;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (primaryNotReadySinceNanos.get() < 0) {
+      primaryNotReadySinceNanos.set(currentTimeNanos);
+    }
+    return currentTimeNanos - primaryNotReadySinceNanos.get() > PRIMARY_NOT_READY_WAIT_NANOS;
+  }
+
+  private void notifyFailure(Status status, boolean isFallback, String methodName) {
+    if (!status.isOk()
+        && !isFallback
+        && hasFallbackChannel()
+        && shouldFallbackBasedOnRPCStatus(status)) {
+      if (useFallbackDueToRPC.compareAndSet(false, true)) {
+        lastRPCFallbackTimeNanos.set(nanoClock.getAsLong());
+        LOG.warn(
+            "Primary connection failed for method: {}. Switching to secondary connection. Status: {}",
+            methodName,
+            status.getCode());
+      }
+    } else if (isFallback && !status.isOk()) {
+      LOG.warn(
+          "Secondary connection failed for method: {}. Status: {}", methodName, status.getCode());
+    }
+  }
+
+  private final class FailoverClientCall<ReqT, RespT>
+      extends SimpleForwardingClientCall<ReqT, RespT> {
+    private final boolean isFallback;
+    private final String methodName;
+
+    /**
+     * @param delegate the underlying ClientCall (either primary or fallback)
+     * @param isFallback true if {@code delegate} is a fallback channel call, false if it is a
+     *     primary channel call. This flag is inspected by {@link #notifyFailure} to determine
+     *     whether a failure should trigger switching to the fallback channel (only primary failures
+     *     do).
+     * @param methodName full gRPC method name (for logging)
+     */
+    FailoverClientCall(ClientCall<ReqT, RespT> delegate, boolean isFallback, String methodName) {
+      super(delegate);
+      this.isFallback = isFallback;
+      this.methodName = methodName;
+    }
+
+    @Override
+    public void start(Listener<RespT> responseListener, Metadata headers) {
+      super.start(
+          new SimpleForwardingClientCallListener<RespT>(responseListener) {
+            @Override
+            public void onClose(Status status, Metadata trailers) {

Review Comment:
   Done.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "arunpandianp (via GitHub)" <gi...@apache.org>.
arunpandianp commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2938804506


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel. It fails over to the
+ * fallback channel if the primary channel returns {@link Status#UNAVAILABLE}.
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after a failure, to avoid retrying too quickly
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final AtomicBoolean useFallback = new AtomicBoolean(false);
+  private final AtomicLong lastFallbackTimeNanos = new AtomicLong(0);
+  private final LongSupplier nanoClock;
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+  }
+
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    if (useFallback.get()) {
+      long elapsedNanos = nanoClock.getAsLong() - lastFallbackTimeNanos.get();
+      if (elapsedNanos > FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallback.compareAndSet(true, false)) {
+          LOG.info("Fallback cooling period elapsed. Retrying direct path.");
+        }
+      } else {
+        CallOptions fallbackCallOptions = callOptions;
+        if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+          fallbackCallOptions = callOptions.withCallCredentials(fallbackCallCredentials);
+        }
+        // The boolean `true` marks that the ClientCall is using the
+        // fallback (cloudpath) channel. The inner call listener uses this
+        // flag so `notifyFailure` will only transition to fallback when a
+        // non-fallback (primary) call fails; fallback calls simply log
+        // failures and do not re-trigger another fallback transition.
+        return new FailoverClientCall<>(
+            fallback.newCall(methodDescriptor, fallbackCallOptions),
+            true,
+            methodDescriptor.getFullMethodName());
+      }
+    }
+    // The boolean `false` marks that the ClientCall is using the
+    // primary (direct) channel. If this call closes with a non-OK status,
+    // `notifyFailure` will flip `useFallback` to true, causing subsequent
+    // calls to go to the fallback channel for the cooling period.
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private void notifyFailure(Status status, boolean isFallback, String methodName) {
+    if (!status.isOk() && !isFallback && fallback != null) {

Review Comment:
   The javadoc on the class says we fallback only on UNAVAILABLE errors. Based on the code here it looks like we'll fallback on any errors. Is this expected?
   
   https://grpc.io/docs/guides/error/ says network level issues may return UNAVAILABLE or 
   UNKNOWN or DEADLINE_EXCEEDED. should we include them here?



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979097306


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);

Review Comment:
   Done. stateChangeListenerRegistered is still outside the State object as it is unrelated to all other Atomics.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4165971076

   /rerun


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979108754


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050421125

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992472175


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java:
##########
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall.Listener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+@RunWith(JUnit4.class)
+public class FailoverChannelTest {
+
+  private MethodDescriptor<Object, Object> methodDescriptor =
+      MethodDescriptor.newBuilder()
+          .setType(MethodDescriptor.MethodType.UNARY)
+          .setFullMethodName(MethodDescriptor.generateFullMethodName("test", "test"))
+          .setRequestMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .setResponseMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .build();
+
+  private static FailoverChannel createForTest(ManagedChannel primary, ManagedChannel fallback) {
+    return FailoverChannel.forTest(primary, fallback, null, System::nanoTime);
+  }
+
+  /**
+   * Starts a call on the primary channel, captures the injected listener, and fires onClose with
+   * the given status. Use this to trigger RPC-based failover in tests.
+   */
+  private void triggerRPCFailure(
+      FailoverChannel channel, ClientCall<Object, Object> underlying, Status status)
+      throws Exception {
+    channel
+        .newCall(methodDescriptor, CallOptions.DEFAULT)
+        .start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlying).start(captor.capture(), any());

Review Comment:
   Done



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java:
##########
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall.Listener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+@RunWith(JUnit4.class)
+public class FailoverChannelTest {
+
+  private MethodDescriptor<Object, Object> methodDescriptor =
+      MethodDescriptor.newBuilder()
+          .setType(MethodDescriptor.MethodType.UNARY)
+          .setFullMethodName(MethodDescriptor.generateFullMethodName("test", "test"))
+          .setRequestMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .setResponseMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .build();
+
+  private static FailoverChannel createForTest(ManagedChannel primary, ManagedChannel fallback) {
+    return FailoverChannel.forTest(primary, fallback, null, System::nanoTime);
+  }
+
+  /**
+   * Starts a call on the primary channel, captures the injected listener, and fires onClose with
+   * the given status. Use this to trigger RPC-based failover in tests.
+   */
+  private void triggerRPCFailure(
+      FailoverChannel channel, ClientCall<Object, Object> underlying, Status status)
+      throws Exception {
+    channel
+        .newCall(methodDescriptor, CallOptions.DEFAULT)
+        .start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlying).start(captor.capture(), any());
+    captor.getValue().onClose(status, new Metadata());
+  }
+
+
+  public void testRPCFailureTriggersFallback() throws Exception {
+    // RPC failure with UNAVAILABLE should switch to fallback channel.
+    ManagedChannel mockChannel = mock(ManagedChannel.class);
+    ManagedChannel mockFallbackChannel = mock(ManagedChannel.class);
+    ClientCall<Object, Object> underlyingCall = mock(ClientCall.class);
+    ClientCall<Object, Object> fallbackCall = mock(ClientCall.class);
+    when(mockChannel.newCall(any(), any())).thenReturn(underlyingCall);
+    when(mockFallbackChannel.newCall(any(), any())).thenReturn(fallbackCall);
+
+    FailoverChannel failoverChannel = createForTest(mockChannel, mockFallbackChannel);
+
+    ClientCall<Object, Object> call1 =
+        failoverChannel.newCall(methodDescriptor, CallOptions.DEFAULT);
+    Metadata metadata1 = new Metadata();
+    call1.start(new NoopClientCall.NoopClientCallListener<>(), metadata1);
+
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlyingCall).start(captor.capture(), same(metadata1));
+    captor.getValue().onClose(Status.UNAVAILABLE, new Metadata());
+
+    ClientCall<Object, Object> call2 =
+        failoverChannel.newCall(methodDescriptor, CallOptions.DEFAULT);
+    call2.start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    verify(mockFallbackChannel, atLeastOnce()).newCall(any(), any());
+  }
+
+  @Test
+  public void testRPCFailureRecoveryAfterCoolingPeriod() throws Exception {
+    // After RPC failure, channel stays on fallback during cooling period, then returns to primary.
+    ManagedChannel mockChannel = mock(ManagedChannel.class);
+    ManagedChannel mockFallbackChannel = mock(ManagedChannel.class);
+    ClientCall<Object, Object> underlyingCall = mock(ClientCall.class);
+    ClientCall<Object, Object> fallbackCall = mock(ClientCall.class);
+    when(mockChannel.newCall(any(), any())).thenReturn(underlyingCall, mock(ClientCall.class));
+    when(mockFallbackChannel.newCall(any(), any())).thenReturn(fallbackCall);
+
+    when(mockChannel.getState(false)).thenReturn(ConnectivityState.READY);
+
+    AtomicLong time = new AtomicLong(0);
+    FailoverChannel failoverChannel =
+        FailoverChannel.forTest(mockChannel, mockFallbackChannel, null, time::get);
+
+    // Trigger RPC failure fallback

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992480267


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");

Review Comment:
   Added a static atomicint counter as per the suggestion. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r3018140963


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -813,25 +813,25 @@ private static ChannelCache createChannelCache(
       GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
         ChannelCache.create(
-            (currentFlowControlSettings, serviceAddress) ->
-                // IsolationChannel wraps FailoverChannel so that each active RPC gets its own
-                // FailoverChannel instance. FailoverChannel creates two channels (primary,
-                // fallback)
-                // per active RPC.
-                IsolationChannel.create(
-                    () ->
-                        FailoverChannel.create(
-                            remoteChannel(
-                                serviceAddress,
-                                workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                                currentFlowControlSettings),
-                            remoteChannel(
-                                dispatcherClient.getDispatcherEndpoints().iterator().next(),
-                                workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                                currentFlowControlSettings),
-                            MoreCallCredentials.from(
-                                new VendoredCredentialsAdapter(workerOptions.getGcpCredential()))),
-                    currentFlowControlSettings.getOnReadyThresholdBytes()));
+            (currentFlowControlSettings, serviceAddress) -> {
+              // IsolationChannel wrapping FailoverChannel so that each active RPC gets its own
+              // FailoverChannel instance. FailoverChannel creates two channels (primary,
+              // fallback) per active RPC.
+              return IsolationChannel.create(
+                  () ->
+                      FailoverChannel.create(
+                          remoteChannel(
+                              serviceAddress,
+                              workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
+                              currentFlowControlSettings),
+                          remoteChannel(

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r3024581743


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return create(primary, () -> fallback, fallbackCallCredentials);
+  }
+
+  static FailoverChannel forTest(

Review Comment:
   Done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {

Review Comment:
   Yeah, not needed anymore. Removed it. 



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return create(primary, () -> fallback, fallbackCallCredentials);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return forTest(primary, fallback, fallbackCallCredentials, nanoClock, 0L);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    return new FailoverChannel(
+        primary, () -> fallback, fallbackCallCredentials, nanoClock, rpcFailureThresholdNanos);
+  }
+
+  /** Returns the fallback channel, creating it from the supplier at most once. */
+  private ManagedChannel getOrCreateFallback() {
+    fallback = fallbackSupplier.get();

Review Comment:
   Suppliers.memoize should return the same instance(if already created) whenever .get() is called. But applied the suggestion for clarity. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2986786228


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");

Review Comment:
   maybe it would be helpful to have an id that we put in the logs so we can correlate them for the same failover channel.
   
   You could just number off channels based upon a static atomicint



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;

Review Comment:
   could call the clock once outside the synchronized block and pass the time into check and update state fallback also



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection
+        // was healthy and the timeout is an application-level issue, not a connectivity problem.
+        return !receivedResponse;
+      default:
+        return false;
+    }
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  /**
+   * Checks primary channel connectivity state and updates {@code state.useFallbackDueToState} if
+   * the primary has been not-ready long enough to warrant failover.
+   */
+  @GuardedBy("state")
+  private void checkAndUpdateStateFallback(ConnectivityState connectivityState) {

Review Comment:
   ditto, could be a synchronized method on State



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java:
##########
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall.Listener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+@RunWith(JUnit4.class)
+public class FailoverChannelTest {
+
+  private MethodDescriptor<Object, Object> methodDescriptor =
+      MethodDescriptor.newBuilder()
+          .setType(MethodDescriptor.MethodType.UNARY)
+          .setFullMethodName(MethodDescriptor.generateFullMethodName("test", "test"))
+          .setRequestMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .setResponseMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .build();
+
+  private static FailoverChannel createForTest(ManagedChannel primary, ManagedChannel fallback) {
+    return FailoverChannel.forTest(primary, fallback, null, System::nanoTime);
+  }
+
+  /**
+   * Starts a call on the primary channel, captures the injected listener, and fires onClose with
+   * the given status. Use this to trigger RPC-based failover in tests.
+   */
+  private void triggerRPCFailure(
+      FailoverChannel channel, ClientCall<Object, Object> underlying, Status status)
+      throws Exception {
+    channel
+        .newCall(methodDescriptor, CallOptions.DEFAULT)
+        .start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlying).start(captor.capture(), any());

Review Comment:
   could verify the metadata equality with what was passed to start here too



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection
+        // was healthy and the timeout is an application-level issue, not a connectivity problem.
+        return !receivedResponse;
+      default:
+        return false;
+    }
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  /**
+   * Checks primary channel connectivity state and updates {@code state.useFallbackDueToState} if
+   * the primary has been not-ready long enough to warrant failover.
+   */
+  @GuardedBy("state")
+  private void checkAndUpdateStateFallback(ConnectivityState connectivityState) {
+    // gRPC's state machine only transitions to IDLE from READY. Hence, we treat both
+    // READY and IDLE as healthy states.
+    if (connectivityState == ConnectivityState.READY
+        || connectivityState == ConnectivityState.IDLE) {
+      state.primaryNotReadySinceNanos = -1;
+      return;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (state.primaryNotReadySinceNanos < 0) {
+      state.primaryNotReadySinceNanos = currentTimeNanos;
+    }
+    if (currentTimeNanos - state.primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+      if (!state.useFallbackDueToState) {
+        state.useFallbackDueToState = true;
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+    }
+  }
+
+  private void notifyCallDone(
+      Status status, boolean isFallback, String methodName, boolean receivedResponse) {
+    if (!status.isOk() && !isFallback && shouldFallbackBasedOnRPCStatus(status, receivedResponse)) {
+      synchronized (state) {
+        if (!state.useFallbackDueToRPC) {
+          state.useFallbackDueToRPC = true;
+          state.lastRPCFallbackTimeNanos = nanoClock.getAsLong();
+          LOG.warn(
+              "Primary connection failed for method: {}. Switching to secondary connection."
+                  + " Status: {}",
+              methodName,
+              status.getCode());
+        }
+      }
+    } else if (isFallback && !status.isOk()) {
+      LOG.warn(
+          "Secondary connection failed for method: {}. Status: {}", methodName, status.getCode());
+    }
+  }
+
+  private final class FailoverClientCall<ReqT, RespT>
+      extends SimpleForwardingClientCall<ReqT, RespT> {
+    private final boolean isFallback;
+    private final String methodName;
+    // Tracks whether any response message was received. Volatile ensures the write in onMessage
+    // is visible to the read in onClose even if they execute on different threads within gRPC's
+    // SerializingExecutor.
+    private volatile boolean receivedResponse = false;
+
+    /**
+     * @param delegate the underlying ClientCall (either primary or fallback)
+     * @param isFallback true if {@code delegate} is a fallback channel call, false if it is a
+     *     primary channel call. This flag is inspected by {@link #notifyCallDone} to determine
+     *     whether a failure should trigger switching to the fallback channel (only primary failures
+     *     do).
+     * @param methodName gRPC method name (for logging)
+     */
+    FailoverClientCall(ClientCall<ReqT, RespT> delegate, boolean isFallback, String methodName) {
+      super(delegate);
+      this.isFallback = isFallback;
+      this.methodName = methodName;
+    }
+
+    @Override
+    public void start(Listener<RespT> responseListener, Metadata headers) {
+      super.start(
+          new SimpleForwardingClientCallListener<RespT>(responseListener) {
+            @Override
+            public void onMessage(RespT message) {
+              receivedResponse = true;
+              super.onMessage(message);
+            }
+
+            @Override
+            public void onClose(Status status, Metadata trailers) {
+              notifyCallDone(status, isFallback, methodName, receivedResponse);
+              super.onClose(status, trailers);
+            }
+          },
+          headers);
+    }
+  }
+
+  /** Registers callback for primary channel state changes. */
+  private void registerPrimaryStateChangeListener() {

Review Comment:
   Could get rid of the connectivity state call during rpc start and just use the listener as the way to update the current connectivity state?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection

Review Comment:
   Should we just return true if we got a response regardless of whatever the status is? Since we're just trying to detect networking stack setup failure that seems safer to not get unnecessary fallbacks.



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/IsolationChannelTest.java:
##########
@@ -49,42 +49,12 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.InOrder;
 
-/**
- * {@link NoopClientCall} is a class that is designed for use in tests. It is designed to be used in
- * places where a scriptable call is necessary. By default, all methods are noops, and designed to
- * be overridden.
- */
-class NoopClientCall<ReqT, RespT> extends ClientCall<ReqT, RespT> {
-
-  /**
-   * {@link NoopClientCall.NoopClientCallListener} is a class that is designed for use in tests. It
-   * is designed to be used in places where a scriptable call listener is necessary. By default, all
-   * methods are noops, and designed to be overridden.
-   */
-  public static class NoopClientCallListener<T> extends ClientCall.Listener<T> {}
-
-  @Override
-  public void start(ClientCall.Listener<RespT> listener, Metadata headers) {}
-
-  @Override
-  public void request(int numMessages) {}
-
-  @Override
-  public void cancel(String message, Throwable cause) {}
-
-  @Override
-  public void halfClose() {}
-
-  @Override
-  public void sendMessage(ReqT message) {}
-}
-
 @RunWith(JUnit4.class)
 public class IsolationChannelTest {
 
   private Supplier<ManagedChannel> channelSupplier = mock(Supplier.class);
 
-  private static class NoopMarshaller implements Marshaller<Object> {
+  public static class NoopMarshaller implements Marshaller<Object> {

Review Comment:
   move the marshaller into the NoOpClientCall instead of having the other test refer to this



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -804,20 +808,31 @@ private static void validateWorkerOptions(DataflowWorkerHarnessOptions options)
   }
 
   private static ChannelCache createChannelCache(
-      DataflowWorkerHarnessOptions workerOptions, ComputationConfig.Fetcher configFetcher) {
+      DataflowWorkerHarnessOptions workerOptions,
+      ComputationConfig.Fetcher configFetcher,
+      GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
         ChannelCache.create(
-            (currentFlowControlSettings, serviceAddress) -> {
-              // IsolationChannel will create and manage separate RPC channels to the same
-              // serviceAddress.
-              return IsolationChannel.create(
-                  () ->
-                      remoteChannel(
-                          serviceAddress,
-                          workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                          currentFlowControlSettings),
-                  currentFlowControlSettings.getOnReadyThresholdBytes());
-            });
+            (currentFlowControlSettings, serviceAddress) ->
+                // IsolationChannel wraps FailoverChannel so that each active RPC gets its own
+                // FailoverChannel instance. FailoverChannel creates two channels (primary,
+                // fallback)
+                // per active RPC.

Review Comment:
   nit: wrapping



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java:
##########
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall.Listener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+@RunWith(JUnit4.class)
+public class FailoverChannelTest {
+
+  private MethodDescriptor<Object, Object> methodDescriptor =
+      MethodDescriptor.newBuilder()
+          .setType(MethodDescriptor.MethodType.UNARY)
+          .setFullMethodName(MethodDescriptor.generateFullMethodName("test", "test"))
+          .setRequestMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .setResponseMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .build();
+
+  private static FailoverChannel createForTest(ManagedChannel primary, ManagedChannel fallback) {
+    return FailoverChannel.forTest(primary, fallback, null, System::nanoTime);
+  }
+
+  /**
+   * Starts a call on the primary channel, captures the injected listener, and fires onClose with
+   * the given status. Use this to trigger RPC-based failover in tests.
+   */
+  private void triggerRPCFailure(
+      FailoverChannel channel, ClientCall<Object, Object> underlying, Status status)
+      throws Exception {
+    channel
+        .newCall(methodDescriptor, CallOptions.DEFAULT)
+        .start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlying).start(captor.capture(), any());
+    captor.getValue().onClose(status, new Metadata());
+  }
+
+
+  public void testRPCFailureTriggersFallback() throws Exception {
+    // RPC failure with UNAVAILABLE should switch to fallback channel.
+    ManagedChannel mockChannel = mock(ManagedChannel.class);
+    ManagedChannel mockFallbackChannel = mock(ManagedChannel.class);
+    ClientCall<Object, Object> underlyingCall = mock(ClientCall.class);
+    ClientCall<Object, Object> fallbackCall = mock(ClientCall.class);
+    when(mockChannel.newCall(any(), any())).thenReturn(underlyingCall);
+    when(mockFallbackChannel.newCall(any(), any())).thenReturn(fallbackCall);
+
+    FailoverChannel failoverChannel = createForTest(mockChannel, mockFallbackChannel);
+
+    ClientCall<Object, Object> call1 =
+        failoverChannel.newCall(methodDescriptor, CallOptions.DEFAULT);
+    Metadata metadata1 = new Metadata();
+    call1.start(new NoopClientCall.NoopClientCallListener<>(), metadata1);
+
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlyingCall).start(captor.capture(), same(metadata1));
+    captor.getValue().onClose(Status.UNAVAILABLE, new Metadata());
+
+    ClientCall<Object, Object> call2 =
+        failoverChannel.newCall(methodDescriptor, CallOptions.DEFAULT);
+    call2.start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    verify(mockFallbackChannel, atLeastOnce()).newCall(any(), any());
+  }
+
+  @Test
+  public void testRPCFailureRecoveryAfterCoolingPeriod() throws Exception {
+    // After RPC failure, channel stays on fallback during cooling period, then returns to primary.
+    ManagedChannel mockChannel = mock(ManagedChannel.class);
+    ManagedChannel mockFallbackChannel = mock(ManagedChannel.class);
+    ClientCall<Object, Object> underlyingCall = mock(ClientCall.class);
+    ClientCall<Object, Object> fallbackCall = mock(ClientCall.class);
+    when(mockChannel.newCall(any(), any())).thenReturn(underlyingCall, mock(ClientCall.class));
+    when(mockFallbackChannel.newCall(any(), any())).thenReturn(fallbackCall);
+
+    when(mockChannel.getState(false)).thenReturn(ConnectivityState.READY);
+
+    AtomicLong time = new AtomicLong(0);
+    FailoverChannel failoverChannel =
+        FailoverChannel.forTest(mockChannel, mockFallbackChannel, null, time::get);
+
+    // Trigger RPC failure fallback

Review Comment:
   ditto use helper



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection
+        // was healthy and the timeout is an application-level issue, not a connectivity problem.
+        return !receivedResponse;
+      default:
+        return false;
+    }
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {

Review Comment:
   is the callOptions.getCredentials() == null necessary? I'm not sure when the callOptions would or wouldn't already have it set. It seems more straightforward to always override, 



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection
+        // was healthy and the timeout is an application-level issue, not a connectivity problem.
+        return !receivedResponse;
+      default:
+        return false;
+    }
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  /**
+   * Checks primary channel connectivity state and updates {@code state.useFallbackDueToState} if
+   * the primary has been not-ready long enough to warrant failover.
+   */
+  @GuardedBy("state")
+  private void checkAndUpdateStateFallback(ConnectivityState connectivityState) {
+    // gRPC's state machine only transitions to IDLE from READY. Hence, we treat both
+    // READY and IDLE as healthy states.
+    if (connectivityState == ConnectivityState.READY
+        || connectivityState == ConnectivityState.IDLE) {
+      state.primaryNotReadySinceNanos = -1;
+      return;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (state.primaryNotReadySinceNanos < 0) {
+      state.primaryNotReadySinceNanos = currentTimeNanos;
+    }
+    if (currentTimeNanos - state.primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+      if (!state.useFallbackDueToState) {
+        state.useFallbackDueToState = true;
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+    }
+  }
+
+  private void notifyCallDone(
+      Status status, boolean isFallback, String methodName, boolean receivedResponse) {
+    if (!status.isOk() && !isFallback && shouldFallbackBasedOnRPCStatus(status, receivedResponse)) {
+      synchronized (state) {
+        if (!state.useFallbackDueToRPC) {
+          state.useFallbackDueToRPC = true;
+          state.lastRPCFallbackTimeNanos = nanoClock.getAsLong();
+          LOG.warn(
+              "Primary connection failed for method: {}. Switching to secondary connection."
+                  + " Status: {}",
+              methodName,
+              status.getCode());
+        }
+      }
+    } else if (isFallback && !status.isOk()) {
+      LOG.warn(
+          "Secondary connection failed for method: {}. Status: {}", methodName, status.getCode());
+    }
+  }
+
+  private final class FailoverClientCall<ReqT, RespT>
+      extends SimpleForwardingClientCall<ReqT, RespT> {
+    private final boolean isFallback;
+    private final String methodName;
+    // Tracks whether any response message was received. Volatile ensures the write in onMessage
+    // is visible to the read in onClose even if they execute on different threads within gRPC's
+    // SerializingExecutor.
+    private volatile boolean receivedResponse = false;
+
+    /**
+     * @param delegate the underlying ClientCall (either primary or fallback)
+     * @param isFallback true if {@code delegate} is a fallback channel call, false if it is a
+     *     primary channel call. This flag is inspected by {@link #notifyCallDone} to determine
+     *     whether a failure should trigger switching to the fallback channel (only primary failures
+     *     do).
+     * @param methodName gRPC method name (for logging)
+     */
+    FailoverClientCall(ClientCall<ReqT, RespT> delegate, boolean isFallback, String methodName) {
+      super(delegate);
+      this.isFallback = isFallback;
+      this.methodName = methodName;
+    }
+
+    @Override
+    public void start(Listener<RespT> responseListener, Metadata headers) {
+      super.start(
+          new SimpleForwardingClientCallListener<RespT>(responseListener) {
+            @Override
+            public void onMessage(RespT message) {
+              receivedResponse = true;
+              super.onMessage(message);
+            }
+
+            @Override
+            public void onClose(Status status, Metadata trailers) {
+              notifyCallDone(status, isFallback, methodName, receivedResponse);
+              super.onClose(status, trailers);
+            }
+          },
+          headers);
+    }
+  }
+
+  /** Registers callback for primary channel state changes. */
+  private void registerPrimaryStateChangeListener() {
+    if (!stateChangeListenerRegistered.getAndSet(true)) {
+      try {
+        ConnectivityState currentState = primary.getState(false);
+        primary.notifyWhenStateChanged(currentState, this::onPrimaryStateChanged);
+      } catch (Exception e) {
+        LOG.warn(
+            "Failed to register channel state monitor. Continuing with fallback detection.", e);
+        stateChangeListenerRegistered.set(false);
+      }
+    }
+  }
+
+  /** Callback invoked when primary channel connectivity state changes. */
+  private void onPrimaryStateChanged() {
+    if (isShutdown() || isTerminated()) {
+      return;
+    }
+
+    // If primary is READY, clear both useFallbackDueToState useFallbackDueToRPC flag.
+    // This ensures we switch back to primary as soon as it recovers,
+    // regardless of which failover mode triggered the switch.
+    if (primary.getState(false) == ConnectivityState.READY) {
+      synchronized (state) {

Review Comment:
   make a method on State



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {

Review Comment:
   nit: could move this to a method on State then you could just make method synchronized



##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java:
##########
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall.Listener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+@RunWith(JUnit4.class)
+public class FailoverChannelTest {
+
+  private MethodDescriptor<Object, Object> methodDescriptor =
+      MethodDescriptor.newBuilder()
+          .setType(MethodDescriptor.MethodType.UNARY)
+          .setFullMethodName(MethodDescriptor.generateFullMethodName("test", "test"))
+          .setRequestMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .setResponseMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .build();
+
+  private static FailoverChannel createForTest(ManagedChannel primary, ManagedChannel fallback) {
+    return FailoverChannel.forTest(primary, fallback, null, System::nanoTime);
+  }
+
+  /**
+   * Starts a call on the primary channel, captures the injected listener, and fires onClose with
+   * the given status. Use this to trigger RPC-based failover in tests.
+   */
+  private void triggerRPCFailure(
+      FailoverChannel channel, ClientCall<Object, Object> underlying, Status status)
+      throws Exception {
+    channel
+        .newCall(methodDescriptor, CallOptions.DEFAULT)
+        .start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlying).start(captor.capture(), any());
+    captor.getValue().onClose(status, new Metadata());
+  }
+
+
+  public void testRPCFailureTriggersFallback() throws Exception {
+    // RPC failure with UNAVAILABLE should switch to fallback channel.
+    ManagedChannel mockChannel = mock(ManagedChannel.class);
+    ManagedChannel mockFallbackChannel = mock(ManagedChannel.class);
+    ClientCall<Object, Object> underlyingCall = mock(ClientCall.class);
+    ClientCall<Object, Object> fallbackCall = mock(ClientCall.class);
+    when(mockChannel.newCall(any(), any())).thenReturn(underlyingCall);
+    when(mockFallbackChannel.newCall(any(), any())).thenReturn(fallbackCall);
+
+    FailoverChannel failoverChannel = createForTest(mockChannel, mockFallbackChannel);
+
+    ClientCall<Object, Object> call1 =
+        failoverChannel.newCall(methodDescriptor, CallOptions.DEFAULT);
+    Metadata metadata1 = new Metadata();
+    call1.start(new NoopClientCall.NoopClientCallListener<>(), metadata1);
+
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);

Review Comment:
   it seems like you could use triggerRPCFailure here



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979101174


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:
+      case UNKNOWN:
+        return true;
+      default:
+        return false;
+    }
+  }
+
+  private boolean hasFallbackChannel() {
+    return fallback != null;
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  private boolean shouldFallBackDueToPrimaryState() {
+    ConnectivityState connectivityState = primary.getState(true);
+    if (connectivityState == ConnectivityState.READY) {
+      primaryNotReadySinceNanos.set(-1);
+      return false;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (primaryNotReadySinceNanos.get() < 0) {
+      primaryNotReadySinceNanos.set(currentTimeNanos);
+    }
+    return currentTimeNanos - primaryNotReadySinceNanos.get() > PRIMARY_NOT_READY_WAIT_NANOS;
+  }
+
+  private void notifyFailure(Status status, boolean isFallback, String methodName) {

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050415529

   R: @arunpandianp @scwhittle


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2937967264


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -804,20 +808,54 @@ private static void validateWorkerOptions(DataflowWorkerHarnessOptions options)
   }
 
   private static ChannelCache createChannelCache(
-      DataflowWorkerHarnessOptions workerOptions, ComputationConfig.Fetcher configFetcher) {
+      DataflowWorkerHarnessOptions workerOptions,
+      ComputationConfig.Fetcher configFetcher,
+      GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
-        ChannelCache.create(
-            (currentFlowControlSettings, serviceAddress) -> {
-              // IsolationChannel will create and manage separate RPC channels to the same
-              // serviceAddress.
-              return IsolationChannel.create(
-                  () ->
-                      remoteChannel(
-                          serviceAddress,
-                          workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                          currentFlowControlSettings),
-                  currentFlowControlSettings.getOnReadyThresholdBytes());
-            });
+        Boolean.TRUE.equals(
+                workerOptions

Review Comment:
   Good to know. Removed the ternary condition.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050341890

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4087247554

   > When looking for similar implementations, I came across GcpMultiEndpointChannel https://github.com/GoogleCloudPlatform/grpc-gcp-java/blob/master/grpc-gcp/src/main/java/com/google/cloud/grpc/GcpMultiEndpointChannel.java
   > 
   > GcpMultiEndpointChannel uses the channel ConnectivityStatus to determine which channel to use. Will it be more robust, if FailoverChannel uses ConnectivityStatus instead if RPC status to failover?
   > 
   > Thinking something like wait X seconds for primary to become ready the first time and failover to the fallback channel if it takes more than X minutes. We can let primary retry connections in the background and switch to it whenever it becomes ready.
   
   I went for a hybrid approach, check both connection state + RPC status. ConnectionState could be transient errors, so we move back to primary as soon as state changes to READY. RPC status can capture server side issues too, like backend not responding (for instance requests getting rejected by security policies, there could be other reasons too). For this I've used longer cooling period before we re-try primary. WDYT? 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992479411


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4166060794

   Run Java PreCommit


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "arunpandianp (via GitHub)" <gi...@apache.org>.
arunpandianp commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r3020571083


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return create(primary, () -> fallback, fallbackCallCredentials);
+  }
+
+  static FailoverChannel forTest(

Review Comment:
   remove and add a helper method in test class that calls the other forTest method?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {

Review Comment:
   Can we remove this? looks unused.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "arunpandianp (via GitHub)" <gi...@apache.org>.
arunpandianp commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2928643539


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -804,20 +808,54 @@ private static void validateWorkerOptions(DataflowWorkerHarnessOptions options)
   }
 
   private static ChannelCache createChannelCache(
-      DataflowWorkerHarnessOptions workerOptions, ComputationConfig.Fetcher configFetcher) {
+      DataflowWorkerHarnessOptions workerOptions,
+      ComputationConfig.Fetcher configFetcher,
+      GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
-        ChannelCache.create(
-            (currentFlowControlSettings, serviceAddress) -> {
-              // IsolationChannel will create and manage separate RPC channels to the same
-              // serviceAddress.
-              return IsolationChannel.create(
-                  () ->
-                      remoteChannel(
-                          serviceAddress,
-                          workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                          currentFlowControlSettings),
-                  currentFlowControlSettings.getOnReadyThresholdBytes());
-            });
+        Boolean.TRUE.equals(
+                workerOptions

Review Comment:
   We don't need to guard with the flag. The flag is defaulted to true and removing it in https://github.com/apache/beam/pull/37844.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979107761


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:
+      case UNKNOWN:
+        return true;
+      default:
+        return false;
+    }
+  }
+
+  private boolean hasFallbackChannel() {
+    return fallback != null;
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  private boolean shouldFallBackDueToPrimaryState() {
+    ConnectivityState connectivityState = primary.getState(true);

Review Comment:
   Done. The original change was to retry connection. But looks like grpc already retries failed connections, so this was unnecessary. Also, if getState returns IDLE, we not treat it as healthy. 



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979138155


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -804,20 +809,37 @@ private static void validateWorkerOptions(DataflowWorkerHarnessOptions options)
   }
 
   private static ChannelCache createChannelCache(
-      DataflowWorkerHarnessOptions workerOptions, ComputationConfig.Fetcher configFetcher) {
+      DataflowWorkerHarnessOptions workerOptions,
+      ComputationConfig.Fetcher configFetcher,
+      GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
         ChannelCache.create(
             (currentFlowControlSettings, serviceAddress) -> {
-              // IsolationChannel will create and manage separate RPC channels to the same
-              // serviceAddress.
-              return IsolationChannel.create(
-                  () ->
-                      remoteChannel(
-                          serviceAddress,
-                          workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                          currentFlowControlSettings),
-                  currentFlowControlSettings.getOnReadyThresholdBytes());
+              ManagedChannel primaryChannel =
+                  IsolationChannel.create(

Review Comment:
   Addressed this. IsolationChannel now wraps FailoverChannel which creates two channels per active RPC. 
   
   The original intent was to keep IsolationChannel unmodified (since it is used by dispatcher client) and handle fallback at per-worker level. The new ordering (IsolationChannel over FailoverChannel) changes the semantic to per-RPC failover. Which means in case of connectivity issues, each RPC would independently discover the failure and switch at different times, rather than switching together in a coordinated way.
   
   I do agree managing state at per RPC level seems to be less error prone, but would like to callout this semantic change. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2994343861


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -82,6 +85,74 @@ private static final class FailoverState {
     // Time when primary first became not-ready. -1 when primary is currently READY.
     @GuardedBy("this")
     long primaryNotReadySinceNanos = -1;
+
+    private final int channelId;
+
+    FailoverState(int channelId) {
+      this.channelId = channelId;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Transitions the fallback state. When toFallback is true (RPC failure) it enables RPC-based
+     * fallback if not already active and returns true so the caller can log the failure details.
+     * When toFallback is false (primary recovered) it clears all fallback flags and returns true if
+     * recovery actually changed state, so the caller can log it.
+     */
+    synchronized boolean transitionFallback(boolean toFallback, long nowNanos) {

Review Comment:
   nit: how about two separate methods? the bool is just forking internally
   
   I think then you could name them to reflect where they are called then,
   markPrimaryReady()
   notePrimaryRpcFailure()



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -813,25 +813,25 @@ private static ChannelCache createChannelCache(
       GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
         ChannelCache.create(
-            (currentFlowControlSettings, serviceAddress) ->
-                // IsolationChannel wraps FailoverChannel so that each active RPC gets its own
-                // FailoverChannel instance. FailoverChannel creates two channels (primary,
-                // fallback)
-                // per active RPC.
-                IsolationChannel.create(
-                    () ->
-                        FailoverChannel.create(
-                            remoteChannel(
-                                serviceAddress,
-                                workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                                currentFlowControlSettings),
-                            remoteChannel(
-                                dispatcherClient.getDispatcherEndpoints().iterator().next(),
-                                workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                                currentFlowControlSettings),
-                            MoreCallCredentials.from(
-                                new VendoredCredentialsAdapter(workerOptions.getGcpCredential()))),
-                    currentFlowControlSettings.getOnReadyThresholdBytes()));
+            (currentFlowControlSettings, serviceAddress) -> {
+              // IsolationChannel wrapping FailoverChannel so that each active RPC gets its own
+              // FailoverChannel instance. FailoverChannel creates two channels (primary,
+              // fallback) per active RPC.
+              return IsolationChannel.create(
+                  () ->
+                      FailoverChannel.create(
+                          remoteChannel(
+                              serviceAddress,
+                              workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
+                              currentFlowControlSettings),
+                          remoteChannel(

Review Comment:
   maybe the fallback parameter should be Supplier that FailoverChannel will call at-most-once but which could internally defer to calling until we actually want to fall-over (can wrap the provided supplier with Suppliers.memoize).  Then we could avoid creating a channel to dispatcher if we never fallback.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r3018146411


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -82,6 +85,74 @@ private static final class FailoverState {
     // Time when primary first became not-ready. -1 when primary is currently READY.
     @GuardedBy("this")
     long primaryNotReadySinceNanos = -1;
+
+    private final int channelId;
+
+    FailoverState(int channelId) {
+      this.channelId = channelId;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Transitions the fallback state. When toFallback is true (RPC failure) it enables RPC-based
+     * fallback if not already active and returns true so the caller can log the failure details.
+     * When toFallback is false (primary recovered) it clears all fallback flags and returns true if
+     * recovery actually changed state, so the caller can log it.
+     */
+    synchronized boolean transitionFallback(boolean toFallback, long nowNanos) {

Review Comment:
   Split the method into 2 as per the suggestion. Also, added a 30sec wait time before we fallback for RPC based failover. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4165885080

   /retest


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2979112888


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period

Review Comment:
   Handled this. If we are on fallback channel due to RPC based error, but in the background connection state changes to READY, we immediately switch to primary channel.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992474467


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992473013


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java:
##########
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall.Listener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentCaptor;
+
+@RunWith(JUnit4.class)
+public class FailoverChannelTest {
+
+  private MethodDescriptor<Object, Object> methodDescriptor =
+      MethodDescriptor.newBuilder()
+          .setType(MethodDescriptor.MethodType.UNARY)
+          .setFullMethodName(MethodDescriptor.generateFullMethodName("test", "test"))
+          .setRequestMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .setResponseMarshaller(new IsolationChannelTest.NoopMarshaller())
+          .build();
+
+  private static FailoverChannel createForTest(ManagedChannel primary, ManagedChannel fallback) {
+    return FailoverChannel.forTest(primary, fallback, null, System::nanoTime);
+  }
+
+  /**
+   * Starts a call on the primary channel, captures the injected listener, and fires onClose with
+   * the given status. Use this to trigger RPC-based failover in tests.
+   */
+  private void triggerRPCFailure(
+      FailoverChannel channel, ClientCall<Object, Object> underlying, Status status)
+      throws Exception {
+    channel
+        .newCall(methodDescriptor, CallOptions.DEFAULT)
+        .start(new NoopClientCall.NoopClientCallListener<>(), new Metadata());
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);
+    verify(underlying).start(captor.capture(), any());
+    captor.getValue().onClose(status, new Metadata());
+  }
+
+
+  public void testRPCFailureTriggersFallback() throws Exception {
+    // RPC failure with UNAVAILABLE should switch to fallback channel.
+    ManagedChannel mockChannel = mock(ManagedChannel.class);
+    ManagedChannel mockFallbackChannel = mock(ManagedChannel.class);
+    ClientCall<Object, Object> underlyingCall = mock(ClientCall.class);
+    ClientCall<Object, Object> fallbackCall = mock(ClientCall.class);
+    when(mockChannel.newCall(any(), any())).thenReturn(underlyingCall);
+    when(mockFallbackChannel.newCall(any(), any())).thenReturn(fallbackCall);
+
+    FailoverChannel failoverChannel = createForTest(mockChannel, mockFallbackChannel);
+
+    ClientCall<Object, Object> call1 =
+        failoverChannel.newCall(methodDescriptor, CallOptions.DEFAULT);
+    Metadata metadata1 = new Metadata();
+    call1.start(new NoopClientCall.NoopClientCallListener<>(), metadata1);
+
+    ArgumentCaptor<Listener<Object>> captor = ArgumentCaptor.forClass(ClientCall.Listener.class);

Review Comment:
   Done



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -804,20 +808,31 @@ private static void validateWorkerOptions(DataflowWorkerHarnessOptions options)
   }
 
   private static ChannelCache createChannelCache(
-      DataflowWorkerHarnessOptions workerOptions, ComputationConfig.Fetcher configFetcher) {
+      DataflowWorkerHarnessOptions workerOptions,
+      ComputationConfig.Fetcher configFetcher,
+      GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
         ChannelCache.create(
-            (currentFlowControlSettings, serviceAddress) -> {
-              // IsolationChannel will create and manage separate RPC channels to the same
-              // serviceAddress.
-              return IsolationChannel.create(
-                  () ->
-                      remoteChannel(
-                          serviceAddress,
-                          workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                          currentFlowControlSettings),
-                  currentFlowControlSettings.getOnReadyThresholdBytes());
-            });
+            (currentFlowControlSettings, serviceAddress) ->
+                // IsolationChannel wraps FailoverChannel so that each active RPC gets its own
+                // FailoverChannel instance. FailoverChannel creates two channels (primary,
+                // fallback)
+                // per active RPC.

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992473787


##########
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/IsolationChannelTest.java:
##########
@@ -49,42 +49,12 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.InOrder;
 
-/**
- * {@link NoopClientCall} is a class that is designed for use in tests. It is designed to be used in
- * places where a scriptable call is necessary. By default, all methods are noops, and designed to
- * be overridden.
- */
-class NoopClientCall<ReqT, RespT> extends ClientCall<ReqT, RespT> {
-
-  /**
-   * {@link NoopClientCall.NoopClientCallListener} is a class that is designed for use in tests. It
-   * is designed to be used in places where a scriptable call listener is necessary. By default, all
-   * methods are noops, and designed to be overridden.
-   */
-  public static class NoopClientCallListener<T> extends ClientCall.Listener<T> {}
-
-  @Override
-  public void start(ClientCall.Listener<RespT> listener, Metadata headers) {}
-
-  @Override
-  public void request(int numMessages) {}
-
-  @Override
-  public void cancel(String message, Throwable cause) {}
-
-  @Override
-  public void halfClose() {}
-
-  @Override
-  public void sendMessage(ReqT message) {}
-}
-
 @RunWith(JUnit4.class)
 public class IsolationChannelTest {
 
   private Supplier<ManagedChannel> channelSupplier = mock(Supplier.class);
 
-  private static class NoopMarshaller implements Marshaller<Object> {
+  public static class NoopMarshaller implements Marshaller<Object> {

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2957422336


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel. It fails over to the
+ * fallback channel if the primary channel returns {@link Status#UNAVAILABLE}.
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after a failure, to avoid retrying too quickly
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final AtomicBoolean useFallback = new AtomicBoolean(false);
+  private final AtomicLong lastFallbackTimeNanos = new AtomicLong(0);
+  private final LongSupplier nanoClock;
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+  }
+
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    if (useFallback.get()) {
+      long elapsedNanos = nanoClock.getAsLong() - lastFallbackTimeNanos.get();
+      if (elapsedNanos > FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallback.compareAndSet(true, false)) {
+          LOG.info("Fallback cooling period elapsed. Retrying direct path.");
+        }
+      } else {
+        CallOptions fallbackCallOptions = callOptions;
+        if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+          fallbackCallOptions = callOptions.withCallCredentials(fallbackCallCredentials);
+        }
+        // The boolean `true` marks that the ClientCall is using the
+        // fallback (cloudpath) channel. The inner call listener uses this
+        // flag so `notifyFailure` will only transition to fallback when a
+        // non-fallback (primary) call fails; fallback calls simply log
+        // failures and do not re-trigger another fallback transition.
+        return new FailoverClientCall<>(
+            fallback.newCall(methodDescriptor, fallbackCallOptions),
+            true,
+            methodDescriptor.getFullMethodName());
+      }
+    }
+    // The boolean `false` marks that the ClientCall is using the
+    // primary (direct) channel. If this call closes with a non-OK status,
+    // `notifyFailure` will flip `useFallback` to true, causing subsequent
+    // calls to go to the fallback channel for the cooling period.
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private void notifyFailure(Status status, boolean isFallback, String methodName) {
+    if (!status.isOk() && !isFallback && fallback != null) {

Review Comment:
   I was previously triggering fallback only on UNAVAILABLE but later changed it to non-OK status, but forgot to update the comment. I have now changed the check to look for UNAVAILABLE or
   UNKNOWN or DEADLINE_EXCEEDED non-ok status to trigger fallback 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050419043

   Stopping reviewer notifications for this pull request: requested by reviewer. If you'd like to restart, comment `assign set of reviewers`


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050372930

   assign set of reviewers


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050332747

   R: @arunpandianp


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "Abacn (via GitHub)" <gi...@apache.org>.
Abacn merged PR #37840:
URL: https://github.com/apache/beam/pull/37840


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992478636


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection
+        // was healthy and the timeout is an application-level issue, not a connectivity problem.
+        return !receivedResponse;
+      default:
+        return false;
+    }
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {

Review Comment:
   Done. No, it is not necessary. If set, it should be same as fallbackCallCredentials. So, ok to remove it. 



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection

Review Comment:
   Done



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2992681997


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,345 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established) and connection status is not READY, switches to fallback channel and
+ *       waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+
+  private final ManagedChannel primary;
+  private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  // All mutable routing state is consolidated here to ensure related fields are updated atomically.
+  private final FailoverState state = new FailoverState();
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Read connectivity state before acquiring the lock to avoid calling an external API while
+    // holding our lock.
+    ConnectivityState primaryState = primary.getState(false);
+    final boolean useFallback;
+    synchronized (state) {
+      // Step 1: If we switched to fallback due to a failed RPC, check whether enough time has
+      // elapsed to retry primary. If so, clear the flag — the next step will then re-evaluate
+      // whether primary is actually healthy before committing to routing there.
+      if (state.useFallbackDueToRPC) {
+        long timeSinceLastFallback = nanoClock.getAsLong() - state.lastRPCFallbackTimeNanos;
+        if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+          state.useFallbackDueToRPC = false;
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+
+      // Step 2: If neither fallback flag is set, inspect the primary's connectivity state. This
+      // may set useFallbackDueToState if primary has been non-READY for longer than the
+      // threshold. Skipped when already on fallback.
+      // useFallbackDueToState is cleared in onPrimaryStateChanged callback when primary becomes
+      // READY again.
+      if (!state.useFallbackDueToRPC && !state.useFallbackDueToState) {
+        checkAndUpdateStateFallback(primaryState);
+      }
+
+      // Step 3: Decide which channel to route the request to based on the current state.
+      useFallback = state.useFallbackDueToRPC || state.useFallbackDueToState;
+    }
+
+    if (useFallback) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    fallback.shutdown();
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    fallback.shutdownNow();
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && fallback.isShutdown();
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && fallback.isTerminated();
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+    return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status, boolean receivedResponse) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case UNKNOWN:
+        return true;
+      case DEADLINE_EXCEEDED:
+        // Only failover if no response was received. If a response was received, the connection
+        // was healthy and the timeout is an application-level issue, not a connectivity problem.
+        return !receivedResponse;
+      default:
+        return false;
+    }
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  /**
+   * Checks primary channel connectivity state and updates {@code state.useFallbackDueToState} if
+   * the primary has been not-ready long enough to warrant failover.
+   */
+  @GuardedBy("state")
+  private void checkAndUpdateStateFallback(ConnectivityState connectivityState) {
+    // gRPC's state machine only transitions to IDLE from READY. Hence, we treat both
+    // READY and IDLE as healthy states.
+    if (connectivityState == ConnectivityState.READY
+        || connectivityState == ConnectivityState.IDLE) {
+      state.primaryNotReadySinceNanos = -1;
+      return;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (state.primaryNotReadySinceNanos < 0) {
+      state.primaryNotReadySinceNanos = currentTimeNanos;
+    }
+    if (currentTimeNanos - state.primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+      if (!state.useFallbackDueToState) {
+        state.useFallbackDueToState = true;
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+    }
+  }
+
+  private void notifyCallDone(
+      Status status, boolean isFallback, String methodName, boolean receivedResponse) {
+    if (!status.isOk() && !isFallback && shouldFallbackBasedOnRPCStatus(status, receivedResponse)) {
+      synchronized (state) {
+        if (!state.useFallbackDueToRPC) {
+          state.useFallbackDueToRPC = true;
+          state.lastRPCFallbackTimeNanos = nanoClock.getAsLong();
+          LOG.warn(
+              "Primary connection failed for method: {}. Switching to secondary connection."
+                  + " Status: {}",
+              methodName,
+              status.getCode());
+        }
+      }
+    } else if (isFallback && !status.isOk()) {
+      LOG.warn(
+          "Secondary connection failed for method: {}. Status: {}", methodName, status.getCode());
+    }
+  }
+
+  private final class FailoverClientCall<ReqT, RespT>
+      extends SimpleForwardingClientCall<ReqT, RespT> {
+    private final boolean isFallback;
+    private final String methodName;
+    // Tracks whether any response message was received. Volatile ensures the write in onMessage
+    // is visible to the read in onClose even if they execute on different threads within gRPC's
+    // SerializingExecutor.
+    private volatile boolean receivedResponse = false;
+
+    /**
+     * @param delegate the underlying ClientCall (either primary or fallback)
+     * @param isFallback true if {@code delegate} is a fallback channel call, false if it is a
+     *     primary channel call. This flag is inspected by {@link #notifyCallDone} to determine
+     *     whether a failure should trigger switching to the fallback channel (only primary failures
+     *     do).
+     * @param methodName gRPC method name (for logging)
+     */
+    FailoverClientCall(ClientCall<ReqT, RespT> delegate, boolean isFallback, String methodName) {
+      super(delegate);
+      this.isFallback = isFallback;
+      this.methodName = methodName;
+    }
+
+    @Override
+    public void start(Listener<RespT> responseListener, Metadata headers) {
+      super.start(
+          new SimpleForwardingClientCallListener<RespT>(responseListener) {
+            @Override
+            public void onMessage(RespT message) {
+              receivedResponse = true;
+              super.onMessage(message);
+            }
+
+            @Override
+            public void onClose(Status status, Metadata trailers) {
+              notifyCallDone(status, isFallback, methodName, receivedResponse);
+              super.onClose(status, trailers);
+            }
+          },
+          headers);
+    }
+  }
+
+  /** Registers callback for primary channel state changes. */
+  private void registerPrimaryStateChangeListener() {

Review Comment:
   This isn't strictly required. Removed it to only rely on callback to for connectivity state. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2960282431


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period

Review Comment:
   unless channel goes through unhealthy->healthy connectivity transition?
   Want to make sure some race where we observe an rpc failure before we observe the connectivity failure doesn't cause us to stop using the primary channel if it reestablishes quickly.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:
+      case UNKNOWN:
+        return true;
+      default:
+        return false;
+    }
+  }
+
+  private boolean hasFallbackChannel() {
+    return fallback != null;
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  private boolean shouldFallBackDueToPrimaryState() {
+    ConnectivityState connectivityState = primary.getState(true);

Review Comment:
   passing true sounds like it might block attempting to connect if in the idle state.  How about passing false and treating IDLE as not something that needs to be falled back from.
   
   Or could we just remove this if we are anyway setting up a change listener to observe it's changes?



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:

Review Comment:
   I'm worried that DEADLINE_EXCEEDED might occur for other reasons too.
   
   One idea might be to see if the call had any responses, in that case we know that it was at some point connected to the backend and we could choose not to fallback.
   We could also perhaps wait for several continuously failed rpcs or failing rpcs for some elapsed time period before falling back.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.

Review Comment:
   how about removing this one then? The test can have a helper in itself that calls forTest below with default creds and time supplier



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,

Review Comment:
   can we just not support null here? It seems the caller could just use primary without creating a FailoverChannel if they don't want to support fallback, and then we don't have to complicate the code with it possibly being null.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);

Review Comment:
   can we move all the Atomics into a State object that we synchronize?  we have long-lived calls so I don't think we have to worry about the performance of synchronized block versus atomic in the call creation path as long as we are not doing any blocking stuff within it.
   I think it will help keep the code simpler and we don't have to worry about possible weird states races could put us in.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java:
##########
@@ -804,20 +809,37 @@ private static void validateWorkerOptions(DataflowWorkerHarnessOptions options)
   }
 
   private static ChannelCache createChannelCache(
-      DataflowWorkerHarnessOptions workerOptions, ComputationConfig.Fetcher configFetcher) {
+      DataflowWorkerHarnessOptions workerOptions,
+      ComputationConfig.Fetcher configFetcher,
+      GrpcDispatcherClient dispatcherClient) {
     ChannelCache channelCache =
         ChannelCache.create(
             (currentFlowControlSettings, serviceAddress) -> {
-              // IsolationChannel will create and manage separate RPC channels to the same
-              // serviceAddress.
-              return IsolationChannel.create(
-                  () ->
-                      remoteChannel(
-                          serviceAddress,
-                          workerOptions.getWindmillServiceRpcChannelAliveTimeoutSec(),
-                          currentFlowControlSettings),
-                  currentFlowControlSettings.getOnReadyThresholdBytes());
+              ManagedChannel primaryChannel =
+                  IsolationChannel.create(

Review Comment:
   since it's being setup this way IsolationChannel connectivity callbacks are going to be what is used. I'm not sure how that will work since it internally has multiple channels. Looking it seems just has the default ManagedChannel implementation which throws unimplemented exception.
   
   What about having IsolationChannel on top of fallback channels? That seems simpler to me since IsolationChannel just internally creates the separate channels and otherwise doesn't do much than forward things on.
   
   It would be good to have a unit test of whatever setup we do use so that we flush out the issues there instead of requiring an integration test.



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:
+      case UNKNOWN:
+        return true;
+      default:
+        return false;
+    }
+  }
+
+  private boolean hasFallbackChannel() {
+    return fallback != null;
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  private boolean shouldFallBackDueToPrimaryState() {
+    ConnectivityState connectivityState = primary.getState(true);
+    if (connectivityState == ConnectivityState.READY) {
+      primaryNotReadySinceNanos.set(-1);
+      return false;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (primaryNotReadySinceNanos.get() < 0) {
+      primaryNotReadySinceNanos.set(currentTimeNanos);
+    }
+    return currentTimeNanos - primaryNotReadySinceNanos.get() > PRIMARY_NOT_READY_WAIT_NANOS;
+  }
+
+  private void notifyFailure(Status status, boolean isFallback, String methodName) {
+    if (!status.isOk()
+        && !isFallback
+        && hasFallbackChannel()
+        && shouldFallbackBasedOnRPCStatus(status)) {
+      if (useFallbackDueToRPC.compareAndSet(false, true)) {
+        lastRPCFallbackTimeNanos.set(nanoClock.getAsLong());
+        LOG.warn(
+            "Primary connection failed for method: {}. Switching to secondary connection. Status: {}",
+            methodName,
+            status.getCode());
+      }
+    } else if (isFallback && !status.isOk()) {
+      LOG.warn(
+          "Secondary connection failed for method: {}. Status: {}", methodName, status.getCode());
+    }
+  }
+
+  private final class FailoverClientCall<ReqT, RespT>
+      extends SimpleForwardingClientCall<ReqT, RespT> {
+    private final boolean isFallback;
+    private final String methodName;
+
+    /**
+     * @param delegate the underlying ClientCall (either primary or fallback)
+     * @param isFallback true if {@code delegate} is a fallback channel call, false if it is a
+     *     primary channel call. This flag is inspected by {@link #notifyFailure} to determine
+     *     whether a failure should trigger switching to the fallback channel (only primary failures
+     *     do).
+     * @param methodName full gRPC method name (for logging)
+     */
+    FailoverClientCall(ClientCall<ReqT, RespT> delegate, boolean isFallback, String methodName) {
+      super(delegate);
+      this.isFallback = isFallback;
+      this.methodName = methodName;
+    }
+
+    @Override
+    public void start(Listener<RespT> responseListener, Metadata headers) {
+      super.start(
+          new SimpleForwardingClientCallListener<RespT>(responseListener) {
+            @Override
+            public void onClose(Status status, Metadata trailers) {

Review Comment:
   here is where I was wondering could we hook into onMessage or onHeaders to determine that the call did make some progress before possibly failing due to deadline or unavailable (which coudl possibly be from the backend status)



##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPC fails with transient errors ({@link
+ *       Status.Code#UNAVAILABLE}, {@link Status.Code#DEADLINE_EXCEEDED}, or {@link
+ *       Status.Code#UNKNOWN}), switches to fallback channel and waits for a 1-hour cooling period
+ *       before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  private final ManagedChannel primary;
+  @Nullable private final ManagedChannel fallback;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  // Set when primary's connection state has been unavailable for too long.
+  private final AtomicBoolean useFallbackDueToState = new AtomicBoolean(false);
+  // Set when an RPC on primary fails with a transient error.
+  private final AtomicBoolean useFallbackDueToRPC = new AtomicBoolean(false);
+  private final AtomicLong lastRPCFallbackTimeNanos = new AtomicLong(0);
+  private final AtomicLong primaryNotReadySinceNanos = new AtomicLong(-1);
+  private final LongSupplier nanoClock;
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      @Nullable ManagedChannel fallback,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    this.primary = primary;
+    this.fallback = fallback;
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  // Test-only.
+  public static FailoverChannel create(ManagedChannel primary, ManagedChannel fallback) {
+    return new FailoverChannel(primary, fallback, null, System::nanoTime);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, System::nanoTime);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return new FailoverChannel(primary, fallback, fallbackCallCredentials, nanoClock);
+  }
+
+  @Override
+  public String authority() {
+    return primary.authority();
+  }
+
+  @Override
+  public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
+      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
+    // Check if the RPC-based cooling period has elapsed.
+    if (useFallbackDueToRPC.get()) {
+      long timeSinceLastFallback = nanoClock.getAsLong() - lastRPCFallbackTimeNanos.get();
+      if (timeSinceLastFallback >= FALLBACK_COOLING_PERIOD_NANOS) {
+        if (useFallbackDueToRPC.compareAndSet(true, false)) {
+          LOG.info("Primary channel cooling period elapsed; switching back from fallback.");
+        }
+      }
+    }
+
+    if (fallback != null && (useFallbackDueToRPC.get() || useFallbackDueToState.get())) {
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    // If primary has not become ready for a sustained period, fail over to fallback.
+    if (fallback != null && shouldFallBackDueToPrimaryState()) {
+      if (useFallbackDueToState.compareAndSet(false, true)) {
+        LOG.warn("Primary connection unavailable. Switching to secondary connection.");
+      }
+      return new FailoverClientCall<>(
+          fallback.newCall(methodDescriptor, applyFallbackCredentials(callOptions)),
+          true,
+          methodDescriptor.getFullMethodName());
+    }
+
+    return new FailoverClientCall<>(
+        primary.newCall(methodDescriptor, callOptions),
+        false,
+        methodDescriptor.getFullMethodName());
+  }
+
+  @Override
+  public ManagedChannel shutdown() {
+    primary.shutdown();
+    if (fallback != null) {
+      fallback.shutdown();
+    }
+    return this;
+  }
+
+  @Override
+  public ManagedChannel shutdownNow() {
+    primary.shutdownNow();
+    if (fallback != null) {
+      fallback.shutdownNow();
+    }
+    return this;
+  }
+
+  @Override
+  public boolean isShutdown() {
+    return primary.isShutdown() && (fallback == null || fallback.isShutdown());
+  }
+
+  @Override
+  public boolean isTerminated() {
+    return primary.isTerminated() && (fallback == null || fallback.isTerminated());
+  }
+
+  @Override
+  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
+    long endTimeNanos = nanoClock.getAsLong() + unit.toNanos(timeout);
+    boolean primaryTerminated = primary.awaitTermination(timeout, unit);
+    if (fallback != null) {
+      long remainingNanos = Math.max(0, endTimeNanos - nanoClock.getAsLong());
+      return primaryTerminated && fallback.awaitTermination(remainingNanos, TimeUnit.NANOSECONDS);
+    }
+    return primaryTerminated;
+  }
+
+  private boolean shouldFallbackBasedOnRPCStatus(Status status) {
+    switch (status.getCode()) {
+      case UNAVAILABLE:
+      case DEADLINE_EXCEEDED:
+      case UNKNOWN:
+        return true;
+      default:
+        return false;
+    }
+  }
+
+  private boolean hasFallbackChannel() {
+    return fallback != null;
+  }
+
+  private CallOptions applyFallbackCredentials(CallOptions callOptions) {
+    if (fallbackCallCredentials != null && callOptions.getCredentials() == null) {
+      return callOptions.withCallCredentials(fallbackCallCredentials);
+    }
+    return callOptions;
+  }
+
+  private boolean shouldFallBackDueToPrimaryState() {
+    ConnectivityState connectivityState = primary.getState(true);
+    if (connectivityState == ConnectivityState.READY) {
+      primaryNotReadySinceNanos.set(-1);
+      return false;
+    }
+    long currentTimeNanos = nanoClock.getAsLong();
+    if (primaryNotReadySinceNanos.get() < 0) {
+      primaryNotReadySinceNanos.set(currentTimeNanos);
+    }
+    return currentTimeNanos - primaryNotReadySinceNanos.get() > PRIMARY_NOT_READY_WAIT_NANOS;
+  }
+
+  private void notifyFailure(Status status, boolean isFallback, String methodName) {

Review Comment:
   nit: notifyCallDone? we call it on success too



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "arunpandianp (via GitHub)" <gi...@apache.org>.
arunpandianp commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4065834060

   When looking for similar implementations, I came across GcpMultiEndpointChannel https://github.com/GoogleCloudPlatform/grpc-gcp-java/blob/master/grpc-gcp/src/main/java/com/google/cloud/grpc/GcpMultiEndpointChannel.java
   
   GcpMultiEndpointChannel uses the channel ConnectivityStatus to determine which channel to use. Will it be more robust, if FailoverChannel uses ConnectivityStatus instead if RPC status to failover?
   
   Thinking something like wait X seconds for primary to become ready the first time and failover to the fallback channel if it takes more than X minutes. We can let primary retry connections in the background and switch to it whenever it becomes ready. 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050338341

   R: @scwhittle


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050269994

   ## Summary of Changes
   
   Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
   
   This pull request significantly improves the robustness of gRPC communication within Dataflow workers by implementing a failover mechanism for channels. It allows the system to gracefully handle primary channel connectivity issues by switching to a fallback channel and periodically attempting to restore the primary connection, thereby enhancing the overall stability and reliability of the worker's interaction with the Windmill service.
   
   ### Highlights
   
   * **New FailoverChannel Implementation**: Introduced a new FailoverChannel class that wraps a primary and a fallback gRPC ManagedChannel, enabling automatic failover to the fallback channel if the primary becomes unavailable.
   * **Resilient Channel Management**: The FailoverChannel includes logic to retry the primary channel after a configurable cooling period (1 hour), enhancing the resilience of gRPC communication.
   * **Integration into StreamingDataflowWorker**: Modified StreamingDataflowWorker to conditionally create and use the FailoverChannel within the ChannelCache if isolated channels are enabled, leveraging dispatcher endpoints for fallback.
   * **gRPC Request Enhancements**: Updated the GetWorkRequest proto definition to include computation_id_filter and backend_worker_token fields, and integrated the backend_worker_token into the FanOutStreamingEngineWorkerHarness.
   * **Testing and Utilities**: Added comprehensive unit tests for FailoverChannel and refactored common test utility classes like NoopClientCall into a dedicated file for better organization.
   
   🧠 **New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   
   <details>
   <summary><b>Changelog</b></summary>
   
   * **runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/StreamingDataflowWorker.java**
       * Imported new classes for failover channel and credentials.
       * Modified createChannelCache to accept GrpcDispatcherClient and to construct a FailoverChannel when isolated channels are enabled, using primary and fallback IsolationChannel instances.
   * **runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/streaming/harness/FanOutStreamingEngineWorkerHarness.java**
       * Updated createAndStartWindmillStreamSender to include backendWorkerToken in the GetWorkRequest if available from the endpoint.
   * **runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/GrpcDispatcherClient.java**
       * Changed the visibility of getDispatcherEndpoints() method from package-private to public.
   * **runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java**
       * Added a new FailoverChannel class that implements ManagedChannel and provides failover logic between a primary and a fallback channel, with a cooling period for retrying the primary.
   * **runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/streaming/harness/FanOutStreamingEngineWorkerHarnessTest.java**
       * Modified getWorkRequest helper to accept a backendWorkerToken parameter.
       * Updated testStreamsStartCorrectly to verify createDirectGetWorkStream calls with specific worker tokens.
   * **runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannelTest.java**
       * Added a new test class FailoverChannelTest to verify the failover and retry mechanisms of the FailoverChannel, including credential handling.
   * **runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/IsolationChannelTest.java**
       * Removed the NoopClientCall and NoopClientCallListener inner classes, as they were moved to a dedicated file.
       * Changed NoopMarshaller to be public.
   * **runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/NoopClientCall.java**
       * Added a new NoopClientCall class and its inner NoopClientCallListener for use in gRPC client testing.
   * **runners/google-cloud-dataflow-java/worker/windmill/src/main/proto/windmill.proto**
       * Added computation_id_filter and backend_worker_token fields to the GetWorkRequest message.
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
   
   Feature | Command | Description
   --- | --- | ---
   Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
   Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
   Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
   Help | `/gemini help` | Displays a list of available commands.
   
   <b>Customization</b>
   
   To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   
   <b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4050413806

   stop reviewer notifications


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "parveensania (via GitHub)" <gi...@apache.org>.
parveensania commented on PR #37840:
URL: https://github.com/apache/beam/pull/37840#issuecomment-4165775618

   retest this please


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "arunpandianp (via GitHub)" <gi...@apache.org>.
arunpandianp commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r3020642570


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return create(primary, () -> fallback, fallbackCallCredentials);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return forTest(primary, fallback, fallbackCallCredentials, nanoClock, 0L);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    return new FailoverChannel(
+        primary, () -> fallback, fallbackCallCredentials, nanoClock, rpcFailureThresholdNanos);
+  }
+
+  /** Returns the fallback channel, creating it from the supplier at most once. */
+  private ManagedChannel getOrCreateFallback() {
+    fallback = fallbackSupplier.get();

Review Comment:
   ```suggestion
     private ManagedChannel getOrCreateFallback() {
       if (fallback != null) return fallback;
       fallback = fallbackSupplier.get();
   ```



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "arunpandianp (via GitHub)" <gi...@apache.org>.
arunpandianp commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r3024773653


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.dataflow.worker.windmill.client.grpc.stubs;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
+import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallCredentials;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.CallOptions;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ConnectivityState;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.ManagedChannel;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Metadata;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.MethodDescriptor;
+import org.apache.beam.vendor.grpc.v1p69p0.io.grpc.Status;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link ManagedChannel} that wraps a primary and a fallback channel.
+ *
+ * <p>Routes requests to either primary or fallback channel based on two independent failover modes:
+ *
+ * <ul>
+ *   <li><b>Connection Status Failover:</b> If the primary channel is not ready for 10+ seconds
+ *       (e.g., during network issues), routes to fallback channel. Switches back as soon as the
+ *       primary channel becomes READY again.
+ *   <li><b>RPC Failover:</b> If primary channel RPCs fail continuously with transient errors
+ *       ({@link Status.Code#UNAVAILABLE} or {@link Status.Code#UNKNOWN}), or with {@link
+ *       Status.Code#DEADLINE_EXCEEDED} before receiving any response (indicating the connection was
+ *       never established), for 30+ seconds without any successful response, switches to fallback
+ *       channel and waits for a 1-hour cooling period before retrying primary.
+ * </ul>
+ */
+@Internal
+public final class FailoverChannel extends ManagedChannel {
+  private static final Logger LOG = LoggerFactory.getLogger(FailoverChannel.class);
+  private static final AtomicInteger CHANNEL_ID_COUNTER = new AtomicInteger(0);
+  // Time to wait before retrying the primary channel after an RPC-based fallback.
+  private static final long FALLBACK_COOLING_PERIOD_NANOS = TimeUnit.HOURS.toNanos(1);
+  private static final long PRIMARY_NOT_READY_WAIT_NANOS = TimeUnit.SECONDS.toNanos(10);
+  // Minimum duration of continuous RPC failures required before switching to fallback.
+  private static final long RPC_FAILURE_THRESHOLD_NANOS = TimeUnit.SECONDS.toNanos(30);
+
+  private final ManagedChannel primary;
+  private final Supplier<ManagedChannel> fallbackSupplier;
+  // Non-null once the fallback channel has been created.
+  @Nullable private volatile ManagedChannel fallback;
+  private final int channelId;
+  @Nullable private final CallCredentials fallbackCallCredentials;
+  private final LongSupplier nanoClock;
+  // Held only during registration to prevent duplicate listener registration.
+  private final AtomicBoolean stateChangeListenerRegistered = new AtomicBoolean(false);
+  private final FailoverState state;
+
+  private static final class FailoverState {
+    // Set when primary's connection state has been unavailable for too long.
+    @GuardedBy("this")
+    boolean useFallbackDueToState;
+    // Set when an RPC on primary fails with an error.
+    @GuardedBy("this")
+    boolean useFallbackDueToRPC;
+    // Timestamp when RPC-based fallback was triggered. Only meaningful when useFallbackDueToRPC
+    // is true.
+    @GuardedBy("this")
+    long lastRPCFallbackTimeNanos;
+    // Time when primary first became not-ready. -1 when primary is currently READY.
+    @GuardedBy("this")
+    long primaryNotReadySinceNanos = -1;
+    // Time when the first consecutive RPC failure was observed. -1 when no failure streak.
+    @GuardedBy("this")
+    long firstRPCFailureSinceNanos = -1;
+
+    private final int channelId;
+    private final long rpcFailureThresholdNanos;
+
+    FailoverState(int channelId, long rpcFailureThresholdNanos) {
+      this.channelId = channelId;
+      this.rpcFailureThresholdNanos = rpcFailureThresholdNanos;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        firstRPCFailureSinceNanos = -1;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Clears all fallback state when the primary channel recovers (READY/IDLE callback). Returns
+     * true if any fallback state was actually cleared, so the caller can log the recovery.
+     */
+    synchronized boolean markPrimaryReady() {
+      boolean wasOnFallback = useFallbackDueToState || useFallbackDueToRPC;
+      useFallbackDueToState = false;
+      useFallbackDueToRPC = false;
+      primaryNotReadySinceNanos = -1;
+      firstRPCFailureSinceNanos = -1;
+      return wasOnFallback;
+    }
+
+    /**
+     * Records an RPC failure on the primary channel. Switches to RPC-based fallback only after
+     * failures have persisted for {@link FailoverChannel#RPC_FAILURE_THRESHOLD_NANOS}. Returns true
+     * if fallback was newly triggered so the caller can log the event.
+     */
+    synchronized boolean notePrimaryRpcFailure(long nowNanos) {
+      if (useFallbackDueToRPC) {
+        return false;
+      }
+      if (firstRPCFailureSinceNanos < 0) {
+        if (rpcFailureThresholdNanos <= 0) {
+          useFallbackDueToRPC = true;
+          lastRPCFallbackTimeNanos = nowNanos;
+          return true;
+        }
+        // This is the first failure. Start the timer.
+        firstRPCFailureSinceNanos = nowNanos;
+        return false;
+      }
+      if (nowNanos - firstRPCFailureSinceNanos >= rpcFailureThresholdNanos) {
+        // Failures have persisted long enough. Switch to fallback.
+        useFallbackDueToRPC = true;
+        lastRPCFallbackTimeNanos = nowNanos;
+        firstRPCFailureSinceNanos = -1;
+        return true;
+      }
+      return false;
+    }
+
+    /** Resets the RPC failure streak. Called when a primary RPC succeeds. */
+    synchronized void notePrimaryRpcSuccess() {
+      firstRPCFailureSinceNanos = -1;
+    }
+  }
+
+  private FailoverChannel(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      @Nullable CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    this.primary = primary;
+    this.fallbackSupplier = Suppliers.memoize(fallbackSupplier::get);
+    this.channelId = CHANNEL_ID_COUNTER.getAndIncrement();
+    this.state = new FailoverState(channelId, rpcFailureThresholdNanos);
+    this.fallbackCallCredentials = fallbackCallCredentials;
+    this.nanoClock = nanoClock;
+    // Register callback to monitor primary channel state changes
+    registerPrimaryStateChangeListener();
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary,
+      Supplier<ManagedChannel> fallbackSupplier,
+      CallCredentials fallbackCallCredentials) {
+    return new FailoverChannel(
+        primary,
+        fallbackSupplier,
+        fallbackCallCredentials,
+        System::nanoTime,
+        RPC_FAILURE_THRESHOLD_NANOS);
+  }
+
+  public static FailoverChannel create(
+      ManagedChannel primary, ManagedChannel fallback, CallCredentials fallbackCallCredentials) {
+    return create(primary, () -> fallback, fallbackCallCredentials);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock) {
+    return forTest(primary, fallback, fallbackCallCredentials, nanoClock, 0L);
+  }
+
+  static FailoverChannel forTest(
+      ManagedChannel primary,
+      ManagedChannel fallback,
+      CallCredentials fallbackCallCredentials,
+      LongSupplier nanoClock,
+      long rpcFailureThresholdNanos) {
+    return new FailoverChannel(
+        primary, () -> fallback, fallbackCallCredentials, nanoClock, rpcFailureThresholdNanos);
+  }
+
+  /** Returns the fallback channel, creating it from the supplier at most once. */
+  private ManagedChannel getOrCreateFallback() {
+    fallback = fallbackSupplier.get();

Review Comment:
   Yes, wanted to avoid writing to the volatile everytime.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add a FailoverChannel wrapper on top of IsolationChannel to maintain a set of primary and failover channel. [beam]

Posted by "scwhittle (via GitHub)" <gi...@apache.org>.
scwhittle commented on code in PR #37840:
URL: https://github.com/apache/beam/pull/37840#discussion_r2994461865


##########
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/client/grpc/stubs/FailoverChannel.java:
##########
@@ -82,6 +85,74 @@ private static final class FailoverState {
     // Time when primary first became not-ready. -1 when primary is currently READY.
     @GuardedBy("this")
     long primaryNotReadySinceNanos = -1;
+
+    private final int channelId;
+
+    FailoverState(int channelId) {
+      this.channelId = channelId;
+    }
+
+    /**
+     * Determines whether the next RPC should route to the fallback channel, updating internal state
+     * as needed.
+     */
+    synchronized boolean computeUseFallback(long nowNanos) {
+      // Clear RPC-based fallback if the cooling period has elapsed.
+      if (useFallbackDueToRPC
+          && nowNanos - lastRPCFallbackTimeNanos >= FALLBACK_COOLING_PERIOD_NANOS) {
+        useFallbackDueToRPC = false;
+        LOG.info(
+            "[channel-{}] Primary channel cooling period elapsed; switching back from fallback.",
+            channelId);
+      }
+      // Check if primary has been not-ready long enough to switch to fallback.
+      // primaryNotReadySinceNanos is set by the state-change callback when primary is not ready.
+      if (!useFallbackDueToRPC
+          && !useFallbackDueToState
+          && primaryNotReadySinceNanos >= 0
+          && nowNanos - primaryNotReadySinceNanos > PRIMARY_NOT_READY_WAIT_NANOS) {
+        useFallbackDueToState = true;
+        LOG.warn(
+            "[channel-{}] Primary connection unavailable. Switching to secondary connection.",
+            channelId);
+      }
+      return useFallbackDueToRPC || useFallbackDueToState;
+    }
+
+    /**
+     * Starts the not-ready grace period timer. Called by the state-change callback when primary
+     * transitions to a non-ready state. Has no effect if already tracking or already on fallback.
+     */
+    synchronized void markPrimaryNotReady(long nowNanos) {
+      if (!useFallbackDueToRPC && !useFallbackDueToState && primaryNotReadySinceNanos < 0) {
+        primaryNotReadySinceNanos = nowNanos;
+      }
+    }
+
+    /**
+     * Transitions the fallback state. When toFallback is true (RPC failure) it enables RPC-based
+     * fallback if not already active and returns true so the caller can log the failure details.
+     * When toFallback is false (primary recovered) it clears all fallback flags and returns true if
+     * recovery actually changed state, so the caller can log it.
+     */
+    synchronized boolean transitionFallback(boolean toFallback, long nowNanos) {

Review Comment:
   Oops dropped part of that comment, I think that we may also want to only transition to fallback after X continous seconds of rpc failures without any responses.  If the method is notePrimaryRpcStatus(bool success) you can keep track of the time and then only fallback if the most recent failure is X seconds past first continuous observed.
   
   Since we expect that requiring fallback to be very rare, it seems like we should be cautious to enable fallback.



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org