From 03dda2c7e0a404fd28f2b3e48e46fa1aa83e79fc Mon Sep 17 00:00:00 2001 From: Abhinand Sundararajan Date: Thu, 26 Nov 2026 14:37:13 +0000 Subject: [PATCH 1/4] fix(taskqueue): prevent real CloudTasksClient from replacing test stubs CloudTasksClientWrapperTest swaps the static sharedClient between a stub (setUp) and null (tearDown). Fire-and-forget dispatches from the queue.add() fast path keep running on IO_EXECUTOR after a test ends. If one calls getClient() while sharedClient is null, it starts a slow real CloudTasksClient.create(); the next test's setUp installs its stub without taking CLIENT_INIT_LOCK, and create() then overwrites it. The rest of that test talks to cloudtasks.googleapis.com and fails with UNAUTHENTICATED. This shows up most often on the JDK 28-ea CI job. - Take CLIENT_INIT_LOCK in setSharedClientForTesting and setSharedV2Beta3ClientForTesting so an injected client is never overwritten by an in-flight lazy init. - In the test tearDown, wait (bounded) for IO_EXECUTOR to go idle before resetting the static clients. --- .../taskqueue/CloudTasksClientWrapper.java | 17 +++++++++++++++-- .../CloudTasksClientWrapperTest.java | 19 ++++++++++++++++++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java b/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java index c21c7404..4c63a881 100644 --- a/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java +++ b/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java @@ -292,13 +292,26 @@ static void setEnabledForTesting(@Nullable Boolean enabled) { QueueImpl.setCloudTaskEnabledForTesting(enabled); } + // The testing setters take CLIENT_INIT_LOCK so that a lazy getClient()/getV2Beta3Client() call + // already inside a slow create() (e.g. from an async task left over from a previous test) cannot + // overwrite the injected client after it has been set. static void setSharedClientForTesting(CloudTasksClient client) { - sharedClient = client; + CLIENT_INIT_LOCK.lock(); + try { + sharedClient = client; + } finally { + CLIENT_INIT_LOCK.unlock(); + } } static void setSharedV2Beta3ClientForTesting( com.google.cloud.tasks.v2beta3.CloudTasksClient client) { - sharedV2Beta3Client = client; + CLIENT_INIT_LOCK.lock(); + try { + sharedV2Beta3Client = client; + } finally { + CLIENT_INIT_LOCK.unlock(); + } } static void setMetadataBaseUrlForTesting(String baseUrl) { diff --git a/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java b/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java index 833619c2..f5a43932 100644 --- a/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java +++ b/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java @@ -75,6 +75,7 @@ import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -355,7 +356,11 @@ public boolean awaitTermination(long duration, TimeUnit unit) { } @After - public void tearDown() { + public void tearDown() throws InterruptedException { + // Fire-and-forget dispatches (e.g. the queue.add() fast path) run on the shared static + // IO_EXECUTOR. Let them finish while the stub clients are still installed; otherwise they can + // lazily build a real CloudTasksClient and leak into the next test. + awaitIoExecutorIdle(Duration.ofSeconds(10)); CloudTasksClientWrapper.setEnabledForTesting(null); CloudTasksClientWrapper.setSharedClientForTesting(null); CloudTasksClientWrapper.setSharedV2Beta3ClientForTesting(null); @@ -371,6 +376,18 @@ public void tearDown() { helper.tearDown(); } + private static void awaitIoExecutorIdle(Duration timeout) throws InterruptedException { + if (!(CloudTasksClientWrapper.IO_EXECUTOR instanceof ThreadPoolExecutor)) { + return; + } + ThreadPoolExecutor pool = (ThreadPoolExecutor) CloudTasksClientWrapper.IO_EXECUTOR; + long deadline = System.nanoTime() + timeout.toNanos(); + while ((pool.getActiveCount() > 0 || !pool.getQueue().isEmpty()) + && System.nanoTime() < deadline) { + Thread.sleep(10); + } + } + @Test public void testAddSinglePushTask_encodesParamsHostRoutingAndRetryConfig() throws Exception { Queue queue = QueueFactory.getDefaultQueue(); From ca5714cba385b54957b9822007cf031b0e8b03d6 Mon Sep 17 00:00:00 2001 From: Abhinand Sundararajan Date: Thu, 26 Nov 2026 15:09:31 +0000 Subject: [PATCH 2/4] fix(e2etests): drop mockito-all 2.0.2-beta so tests run on JDK 28 stagingtests and devappservertests pinned mockito-all 2.0.2-beta (2015), whose cglib/objenesis mock maker calls sun.reflect.ReflectionFactory.newConstructorForSerialization. JDK 28 disables that for non-serializable classes, so every DevAppServerModulesFilterTest case failed with UnsupportedOperationException (Run with -Djdk.reflect.allowNonSerializableConstruction=true ...). Remove the pin; both modules inherit mockito-core from the parent POM (mockito-bom 5.24.0), which uses ByteBuddy and still provides the APIs used here (@Mock, MockitoAnnotations.initMocks, when, verify, atLeast). devappservertests did not use Mockito at all. --- e2etests/devappservertests/pom.xml | 6 ------ e2etests/stagingtests/pom.xml | 6 ------ 2 files changed, 12 deletions(-) diff --git a/e2etests/devappservertests/pom.xml b/e2etests/devappservertests/pom.xml index 4e1d3c67..342ca036 100644 --- a/e2etests/devappservertests/pom.xml +++ b/e2etests/devappservertests/pom.xml @@ -44,12 +44,6 @@ junit test - - org.mockito - mockito-all - 2.0.2-beta - test - com.google.appengine appengine-utils diff --git a/e2etests/stagingtests/pom.xml b/e2etests/stagingtests/pom.xml index cd2b77d0..d2b08f72 100644 --- a/e2etests/stagingtests/pom.xml +++ b/e2etests/stagingtests/pom.xml @@ -70,12 +70,6 @@ appengine-tools-sdk test - - org.mockito - mockito-all - 2.0.2-beta - test - com.google.appengine appengine-apis-dev From 82fe3220ac2b7b0de2034e99ebf9603581e19f0b Mon Sep 17 00:00:00 2001 From: Abhinand Sundararajan Date: Fri, 27 Nov 2026 07:54:43 +0000 Subject: [PATCH 3/4] fix(taskqueue): close displaced clients and read shared clients once Address review feedback on the CloudTasks client setters/getters: - setSharedClientForTesting / setSharedV2Beta3ClientForTesting now swap the client under CLIENT_INIT_LOCK and close the displaced instance outside the lock, so a real client created by the race does not leak its channel/threads and stray holders fail locally instead of reaching cloudtasks.googleapis.com. Parameters are marked @Nullable. - getClient() / getV2Beta3Client() read the volatile field once into a local (double-checked locking), so a concurrent reset to null can no longer make them return null. Client construction (direct create with custom-credentials fallback) is moved unchanged into createCloudTasksClient() / createV2Beta3Client(). --- .../taskqueue/CloudTasksClientWrapper.java | 181 ++++++++++-------- 1 file changed, 101 insertions(+), 80 deletions(-) diff --git a/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java b/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java index 4c63a881..d7ffdd9b 100644 --- a/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java +++ b/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java @@ -294,24 +294,36 @@ static void setEnabledForTesting(@Nullable Boolean enabled) { // The testing setters take CLIENT_INIT_LOCK so that a lazy getClient()/getV2Beta3Client() call // already inside a slow create() (e.g. from an async task left over from a previous test) cannot - // overwrite the injected client after it has been set. - static void setSharedClientForTesting(CloudTasksClient client) { + // overwrite the injected client after it has been set. A displaced client is closed outside the + // lock so it does not leak its channel and threads, and stray callers still holding it fail + // locally instead of reaching the real service. + static void setSharedClientForTesting(@Nullable CloudTasksClient client) { + CloudTasksClient previous; CLIENT_INIT_LOCK.lock(); try { + previous = sharedClient; sharedClient = client; } finally { CLIENT_INIT_LOCK.unlock(); } + if (previous != null && previous != client) { + previous.close(); + } } static void setSharedV2Beta3ClientForTesting( - com.google.cloud.tasks.v2beta3.CloudTasksClient client) { + com.google.cloud.tasks.v2beta3.@Nullable CloudTasksClient client) { + com.google.cloud.tasks.v2beta3.CloudTasksClient previous; CLIENT_INIT_LOCK.lock(); try { + previous = sharedV2Beta3Client; sharedV2Beta3Client = client; } finally { CLIENT_INIT_LOCK.unlock(); } + if (previous != null && previous != client) { + previous.close(); + } } static void setMetadataBaseUrlForTesting(String baseUrl) { @@ -641,101 +653,110 @@ static String getValidAccessToken() throws IOException { static CloudTasksClient getClient() { // NOMUTANTS -- production gRPC client initialization requires live credentials - if (sharedClient == null) { + // Read the volatile field once so a concurrent reset cannot make this return null. + CloudTasksClient client = sharedClient; + if (client == null) { CLIENT_INIT_LOCK.lock(); try { - if (sharedClient == null) { - try { - sharedClient = CloudTasksClient.create(); - } catch (Exception directEx) { - logger.log( - Level.FINE, - "CloudTasksClient.create() failed, attempting custom credentials", - directEx); - try { - CredentialsProvider credentialsProvider = - () -> { - try { - String token = getValidAccessToken(); - // AccessToken's constructor only accepts java.util.Date (not Instant), - // and ErrorProne's JavaUtilDate check requires Date.from(Instant). - return GoogleCredentials.create( - new AccessToken(token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry)))); - } catch (Exception e) { - throw new IOException("Failed to refresh access token", e); - } - }; - CloudTasksSettings settings = - CloudTasksSettings.newBuilder() - .setCredentialsProvider(credentialsProvider) - .build(); - sharedClient = CloudTasksClient.create(settings); - } catch (Exception fallbackEx) { - logger.log(Level.SEVERE, "Failed to initialize CloudTasksClient", fallbackEx); - throw new IllegalStateException( - "Failed to initialize CloudTasksClient: direct=" - + directEx.getMessage() - + ", fallback=" - + fallbackEx.getMessage(), - fallbackEx); - } - } + client = sharedClient; + if (client == null) { + client = createCloudTasksClient(); + sharedClient = client; } } finally { CLIENT_INIT_LOCK.unlock(); } } - return sharedClient; + return client; + } + + private static CloudTasksClient createCloudTasksClient() { + try { + return CloudTasksClient.create(); + } catch (Exception directEx) { + logger.log( + Level.FINE, "CloudTasksClient.create() failed, attempting custom credentials", directEx); + try { + CredentialsProvider credentialsProvider = + () -> { + try { + String token = getValidAccessToken(); + // AccessToken's constructor only accepts java.util.Date (not Instant), + // and ErrorProne's JavaUtilDate check requires Date.from(Instant). + return GoogleCredentials.create( + new AccessToken(token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry)))); + } catch (Exception e) { + throw new IOException("Failed to refresh access token", e); + } + }; + CloudTasksSettings settings = + CloudTasksSettings.newBuilder().setCredentialsProvider(credentialsProvider).build(); + return CloudTasksClient.create(settings); + } catch (Exception fallbackEx) { + logger.log(Level.SEVERE, "Failed to initialize CloudTasksClient", fallbackEx); + throw new IllegalStateException( + "Failed to initialize CloudTasksClient: direct=" + + directEx.getMessage() + + ", fallback=" + + fallbackEx.getMessage(), + fallbackEx); + } + } } static com.google.cloud.tasks.v2beta3.CloudTasksClient getV2Beta3Client() { // NOMUTANTS -- production gRPC client initialization requires live credentials - if (sharedV2Beta3Client == null) { + // Read the volatile field once so a concurrent reset cannot make this return null. + com.google.cloud.tasks.v2beta3.CloudTasksClient client = sharedV2Beta3Client; + if (client == null) { CLIENT_INIT_LOCK.lock(); try { - if (sharedV2Beta3Client == null) { - try { - sharedV2Beta3Client = com.google.cloud.tasks.v2beta3.CloudTasksClient.create(); - } catch (Exception directEx) { - logger.log( - Level.FINE, - "v2beta3 CloudTasksClient.create() failed, attempting custom credentials", - directEx); - try { - CredentialsProvider credentialsProvider = - () -> { - try { - String token = getValidAccessToken(); - return GoogleCredentials.create( - new AccessToken( - token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry)))); - } catch (Exception e) { - throw new IOException("Failed to refresh access token", e); - } - }; - com.google.cloud.tasks.v2beta3.CloudTasksSettings settings = - com.google.cloud.tasks.v2beta3.CloudTasksSettings.newBuilder() - .setCredentialsProvider(credentialsProvider) - .build(); - sharedV2Beta3Client = - com.google.cloud.tasks.v2beta3.CloudTasksClient.create(settings); - } catch (Exception fallbackEx) { - logger.log( - Level.SEVERE, "Failed to initialize v2beta3 CloudTasksClient", fallbackEx); - throw new IllegalStateException( - "Failed to initialize v2beta3 CloudTasksClient: direct=" - + directEx.getMessage() - + ", fallback=" - + fallbackEx.getMessage(), - fallbackEx); - } - } + client = sharedV2Beta3Client; + if (client == null) { + client = createV2Beta3Client(); + sharedV2Beta3Client = client; } } finally { CLIENT_INIT_LOCK.unlock(); } } - return sharedV2Beta3Client; + return client; + } + + private static com.google.cloud.tasks.v2beta3.CloudTasksClient createV2Beta3Client() { + try { + return com.google.cloud.tasks.v2beta3.CloudTasksClient.create(); + } catch (Exception directEx) { + logger.log( + Level.FINE, + "v2beta3 CloudTasksClient.create() failed, attempting custom credentials", + directEx); + try { + CredentialsProvider credentialsProvider = + () -> { + try { + String token = getValidAccessToken(); + return GoogleCredentials.create( + new AccessToken(token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry)))); + } catch (Exception e) { + throw new IOException("Failed to refresh access token", e); + } + }; + com.google.cloud.tasks.v2beta3.CloudTasksSettings settings = + com.google.cloud.tasks.v2beta3.CloudTasksSettings.newBuilder() + .setCredentialsProvider(credentialsProvider) + .build(); + return com.google.cloud.tasks.v2beta3.CloudTasksClient.create(settings); + } catch (Exception fallbackEx) { + logger.log(Level.SEVERE, "Failed to initialize v2beta3 CloudTasksClient", fallbackEx); + throw new IllegalStateException( + "Failed to initialize v2beta3 CloudTasksClient: direct=" + + directEx.getMessage() + + ", fallback=" + + fallbackEx.getMessage(), + fallbackEx); + } + } } /** From c686537c01f3f0b4ecf678a23273ea99d0860f87 Mon Sep 17 00:00:00 2001 From: Abhinand Sundararajan Date: Fri, 27 Nov 2026 09:37:39 +0000 Subject: [PATCH 4/4] fix(taskqueue): cancel in-flight calls on displaced clients; harden tearDown Address optional review nits: - The testing setters now call shutdownNow() instead of close() on a displaced client. close() only shuts the channel down gracefully, so a call already in flight ran to its deadline; shutdownNow() cancels it immediately. The comment is updated to match. - CloudTasksClientWrapperTest.tearDown() runs all state cleanup in a finally block, restores the interrupt flag if the idle wait is interrupted, and awaitIoExecutorIdle() logs a warning with the active and queued counts when it times out instead of returning silently. --- .../taskqueue/CloudTasksClientWrapper.java | 10 ++-- .../CloudTasksClientWrapperTest.java | 50 +++++++++++++------ 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java b/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java index d7ffdd9b..5aa06215 100644 --- a/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java +++ b/api/src/main/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapper.java @@ -294,9 +294,9 @@ static void setEnabledForTesting(@Nullable Boolean enabled) { // The testing setters take CLIENT_INIT_LOCK so that a lazy getClient()/getV2Beta3Client() call // already inside a slow create() (e.g. from an async task left over from a previous test) cannot - // overwrite the injected client after it has been set. A displaced client is closed outside the - // lock so it does not leak its channel and threads, and stray callers still holding it fail - // locally instead of reaching the real service. + // overwrite the injected client after it has been set. A displaced client is shut down outside + // the lock with shutdownNow(), which releases its channel and threads and cancels any calls still + // in flight on it (close() would let them run to their deadline). static void setSharedClientForTesting(@Nullable CloudTasksClient client) { CloudTasksClient previous; CLIENT_INIT_LOCK.lock(); @@ -307,7 +307,7 @@ static void setSharedClientForTesting(@Nullable CloudTasksClient client) { CLIENT_INIT_LOCK.unlock(); } if (previous != null && previous != client) { - previous.close(); + previous.shutdownNow(); } } @@ -322,7 +322,7 @@ static void setSharedV2Beta3ClientForTesting( CLIENT_INIT_LOCK.unlock(); } if (previous != null && previous != client) { - previous.close(); + previous.shutdownNow(); } } diff --git a/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java b/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java index f5a43932..0ef976c0 100644 --- a/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java +++ b/api_dev/src/test/java/com/google/appengine/api/taskqueue/CloudTasksClientWrapperTest.java @@ -95,6 +95,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -104,6 +106,8 @@ /** Unit tests for {@link CloudTasksClientWrapper} and {@link TaskProcessor} v2 gRPC paths. */ @RunWith(JUnit4.class) public class CloudTasksClientWrapperTest { + private static final Logger logger = + Logger.getLogger(CloudTasksClientWrapperTest.class.getName()); private static final String TEST_PROJECT = "test-proj"; private static final String TEST_LOCATION = "us-central1"; private static final String TEST_TOKEN = "fake-oauth-token"; @@ -356,24 +360,30 @@ public boolean awaitTermination(long duration, TimeUnit unit) { } @After - public void tearDown() throws InterruptedException { + public void tearDown() { // Fire-and-forget dispatches (e.g. the queue.add() fast path) run on the shared static // IO_EXECUTOR. Let them finish while the stub clients are still installed; otherwise they can // lazily build a real CloudTasksClient and leak into the next test. - awaitIoExecutorIdle(Duration.ofSeconds(10)); - CloudTasksClientWrapper.setEnabledForTesting(null); - CloudTasksClientWrapper.setSharedClientForTesting(null); - CloudTasksClientWrapper.setSharedV2Beta3ClientForTesting(null); - CloudTasksClientWrapper.setProjectIdForTesting(null); - CloudTasksClientWrapper.setLocationForTesting(null); - CloudTasksClientWrapper.setAccessTokenForTesting(null, 0); - CloudTasksClientWrapper.setMetadataBaseUrlForTesting(null); - CloudTasksClientWrapper.setCredentialsTokenForTesting(null); + try { + awaitIoExecutorIdle(Duration.ofSeconds(10)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.log(Level.WARNING, "Interrupted while waiting for IO_EXECUTOR to go idle", e); + } finally { + CloudTasksClientWrapper.setEnabledForTesting(null); + CloudTasksClientWrapper.setSharedClientForTesting(null); + CloudTasksClientWrapper.setSharedV2Beta3ClientForTesting(null); + CloudTasksClientWrapper.setProjectIdForTesting(null); + CloudTasksClientWrapper.setLocationForTesting(null); + CloudTasksClientWrapper.setAccessTokenForTesting(null, 0); + CloudTasksClientWrapper.setMetadataBaseUrlForTesting(null); + CloudTasksClientWrapper.setCredentialsTokenForTesting(null); - if (server != null) { - server.stop(0); + if (server != null) { + server.stop(0); + } + helper.tearDown(); } - helper.tearDown(); } private static void awaitIoExecutorIdle(Duration timeout) throws InterruptedException { @@ -382,8 +392,18 @@ private static void awaitIoExecutorIdle(Duration timeout) throws InterruptedExce } ThreadPoolExecutor pool = (ThreadPoolExecutor) CloudTasksClientWrapper.IO_EXECUTOR; long deadline = System.nanoTime() + timeout.toNanos(); - while ((pool.getActiveCount() > 0 || !pool.getQueue().isEmpty()) - && System.nanoTime() < deadline) { + while (pool.getActiveCount() > 0 || !pool.getQueue().isEmpty()) { + if (System.nanoTime() >= deadline) { + logger.warning( + "IO_EXECUTOR still busy after " + + timeout + + " (active=" + + pool.getActiveCount() + + ", queued=" + + pool.getQueue().size() + + "); resetting CloudTasksClientWrapper state anyway"); + return; + } Thread.sleep(10); } }