From 8fafa5c01a572344db7e859db5cc211e26331aca Mon Sep 17 00:00:00 2001 From: Josh Gordineer Date: Sat, 24 Oct 2026 19:00:35 -0700 Subject: [PATCH] Wrap CompletionStage results directly in ContextDataFetcherDecorator For every data fetcher that returns a CompletionStage, updateValue converted the stage through Reactor (toMonoIfReactive + contextWrite + toFuture), allocating a Mono chain per field per request, and restoring ThreadLocals around completion only when Reactor's automatic context propagation was enabled globally. The decorator now wraps a CompletionStage directly: a CompletableFuture whose completion callback installs the ContextSnapshot scope while completing normally or exceptionally. Publisher results keep the Reactor path; subscription results are unchanged. Already-completed futures are returned as-is, since their dependents run inline on the current thread. Also skip the duplicate captureFrom source when the local context is the same GraphQLContext instance as the execution context. Semantics preserved from the Reactor path (verified against reactor-core 3.8.8): cancellation of the returned future propagates to the source stage, as Mono.fromCompletionStage did through its subscription; CompletionException is unwrapped before completing exceptionally, as MonoCompletionStage did before onError, so exception resolvers observe the original exception types. A snapshot scope failure keeps the stage's original failure primary (scope error suppressed); a scope failure after completion is logged instead of dropped silently. Tests cover: cross-thread ThreadLocal propagation observed from an undecorated (TrivialDataFetcher) child of the completed value; the unwrapped exception type reaching a DataFetcherExceptionResolver; cancellation propagating to the source future; CompletionException unwrapping on the in-flight and already-failed paths; scope-failure handling; already-completed futures returned as-is. Mutation checks confirm these tests fail when the wrapper (or the cancel link) is reverted. See gh-1548 Generated by Josh-Bot 9000 Signed-off-by: Josh Gordineer --- .../ContextDataFetcherDecorator.java | 72 +++++- .../ContextDataFetcherDecoratorTests.java | 238 ++++++++++++++++++ 2 files changed, 309 insertions(+), 1 deletion(-) diff --git a/spring-graphql/src/main/java/org/springframework/graphql/execution/ContextDataFetcherDecorator.java b/spring-graphql/src/main/java/org/springframework/graphql/execution/ContextDataFetcherDecorator.java index 58fc1abbb..442b6a99b 100644 --- a/spring-graphql/src/main/java/org/springframework/graphql/execution/ContextDataFetcherDecorator.java +++ b/spring-graphql/src/main/java/org/springframework/graphql/execution/ContextDataFetcherDecorator.java @@ -19,6 +19,10 @@ import java.lang.reflect.Method; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Future; import graphql.ExecutionInput; import graphql.GraphQLContext; @@ -37,6 +41,8 @@ import graphql.util.TraverserContext; import io.micrometer.context.ContextSnapshot; import io.micrometer.context.ContextSnapshotFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.jspecify.annotations.Nullable; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; @@ -60,6 +66,8 @@ */ class ContextDataFetcherDecorator implements DataFetcher { + private static final Log logger = LogFactory.getLog(ContextDataFetcherDecorator.class); + private final DataFetcher delegate; private final boolean subscription; @@ -85,7 +93,8 @@ private ContextDataFetcherDecorator( GraphQLContext graphQlContext = env.getGraphQlContext(); ContextSnapshotFactory snapshotFactory = ContextPropagationHelper.getInstance(graphQlContext); - ContextSnapshot snapshot = (env.getLocalContext() instanceof GraphQLContext localContext) ? + ContextSnapshot snapshot = (env.getLocalContext() instanceof GraphQLContext localContext && + localContext != graphQlContext) ? snapshotFactory.captureFrom(graphQlContext, localContext) : snapshotFactory.captureFrom(graphQlContext); @@ -122,6 +131,15 @@ private ContextDataFetcherDecorator( return subscriptionResult.contextWrite(snapshot::updateContext); } + if (value instanceof CompletionStage stage) { + // Wrap the CompletionStage directly instead of converting it through + // Mono (toMonoIfReactive + contextWrite + toFuture). The Reactor path + // allocated several objects per field and restored ThreadLocals only when + // Reactor's automatic context propagation was enabled; the direct wrapper + // installs the snapshot scope explicitly, independent of the Hooks state. + return wrapCompletionStage(stage, snapshot); + } + value = ReactiveAdapterRegistryHelper.toMonoIfReactive(value); if (value instanceof Mono mono) { @@ -131,6 +149,58 @@ private ContextDataFetcherDecorator( return value; } + @SuppressWarnings({"unchecked", "try"}) + private static CompletableFuture<@Nullable Object> wrapCompletionStage( + CompletionStage stage, ContextSnapshot snapshot) { + + if (stage instanceof CompletableFuture future && future.isDone() + && !future.isCompletedExceptionally()) { + // Dependents of an already-completed future run inline on the current thread, + // which holds its own context; no propagation wrapper is needed. Only normally + // completed futures take this path: a failed one must still be unwrapped below. + return (CompletableFuture<@Nullable Object>) future; + } + + CompletableFuture<@Nullable Object> result = new CompletableFuture<>(); + + // Mono.fromCompletionStage propagated cancellation of the returned future back + // to the source; preserve that by cancelling the source when the result is cancelled. + result.whenComplete((value, throwable) -> { + if (result.isCancelled() && stage instanceof Future future) { + future.cancel(true); + } + }); + + stage.whenComplete((value, throwable) -> { + if (throwable instanceof CompletionException exception && exception.getCause() != null) { + // MonoCompletionStage unwraps CompletionException before onError; match that. + throwable = exception.getCause(); + } + try (ContextSnapshot.Scope scope = snapshot.setThreadLocals()) { + if (throwable != null) { + result.completeExceptionally(throwable); + } + else { + result.complete(value); + } + } + catch (Throwable ex) { + if (throwable != null) { + // Keep the original failure primary. Note addSuppressed mutates the + // stage's throwable: a shared failed future accumulates one suppressed + // entry per scope failure. Accepted, since scope failure here requires + // a failing ThreadLocalAccessor, which is a bug of its own. + throwable.addSuppressed(ex); + result.completeExceptionally(throwable); + } + else if (!result.completeExceptionally(ex)) { + logger.warn("ContextSnapshot scope failure after the future completed", ex); + } + } + }); + return result; + } + /** * Static factory method to create {@link GraphQLTypeVisitor} that wraps diff --git a/spring-graphql/src/test/java/org/springframework/graphql/execution/ContextDataFetcherDecoratorTests.java b/spring-graphql/src/test/java/org/springframework/graphql/execution/ContextDataFetcherDecoratorTests.java index eac9b771d..baa4e830c 100644 --- a/spring-graphql/src/test/java/org/springframework/graphql/execution/ContextDataFetcherDecoratorTests.java +++ b/spring-graphql/src/test/java/org/springframework/graphql/execution/ContextDataFetcherDecoratorTests.java @@ -16,17 +16,24 @@ package org.springframework.graphql.execution; +import java.lang.reflect.Constructor; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; +import java.util.function.Predicate; import graphql.ExecutionInput; import graphql.ExecutionResult; import graphql.GraphQL; +import graphql.GraphQLContext; import graphql.GraphQLError; import graphql.GraphqlErrorBuilder; import graphql.TrivialDataFetcher; @@ -34,6 +41,8 @@ import graphql.execution.DataFetcherResult; import graphql.schema.DataFetcher; import graphql.schema.DataFetcherFactories; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.DataFetchingEnvironmentImpl; import graphql.schema.FieldCoordinates; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLSchema; @@ -73,6 +82,14 @@ class ContextDataFetcherDecoratorTests { greetings: String \ }"""; + private static final String CONTAINER_SCHEMA = """ + type Query { \ + container: Container \ + } \ + type Container { \ + value: String \ + }"""; + @Test void monoDataFetcher() throws Exception { @@ -276,6 +293,91 @@ else if (value instanceof Mono) { tester.accept(directiveWiring, env -> Mono.just("hello")); } + + @Test + void completableFutureCompletedOnAnotherThread() throws Exception { + ThreadLocal threadLocal = new ThreadLocal<>(); + threadLocal.set("007"); + ContextRegistry.getInstance().registerThreadLocalAccessor(new TestThreadLocalAccessor<>(threadLocal)); + try { + CountDownLatch fetcherReturned = new CountDownLatch(1); + CompletableFuture future = new CompletableFuture<>(); + + // TrivialDataFetcher is not decorated (see gh-980), so it observes ThreadLocals + // only if completion of the parent field's future propagated them. + DataFetcher childFetcher = (TrivialDataFetcher) (env) -> threadLocal.get(); + + GraphQL graphQl = GraphQlSetup.schemaContent(CONTAINER_SCHEMA) + .queryFetcher("container", (env) -> { + fetcherReturned.countDown(); + return future; + }) + .runtimeWiring(builder -> builder.type("Container", + type -> type.dataFetcher("value", childFetcher))) + .toGraphQl(); + + ExecutionInput input = ExecutionInput.newExecutionInput() + .query("{ container { value } }").build(); + ContextSnapshot snapshot = ContextSnapshotFactory.builder().build().captureAll(); + snapshot.updateContext(input.getGraphQLContext()); + + Mono resultMono = Mono.delay(Duration.ofMillis(10)) + .flatMap((aLong) -> Mono.fromFuture(graphQl.executeAsync(input))); + + // Complete only after the fetcher has returned the future, so the completion + // really happens on a different thread while execution is suspended + Thread completer = new Thread(() -> { + try { + // Wait until the fetcher returned the future, then let the execution + // strategy register its continuation on the wrapped future, so the + // completion (and its dependents) run on this thread + fetcherReturned.await(); + Thread.sleep(200); + } + catch (InterruptedException ex) { + throw new IllegalStateException(ex); + } + future.complete(new Container("ignored")); + }); + completer.start(); + + String value = ResponseHelper.forResult(resultMono).toEntity("container.value", String.class); + assertThat(value).isEqualTo("007"); + } + finally { + threadLocal.remove(); + } + } + + @Test + void completableFutureCompletedExceptionallyReachesResolver() throws Exception { + CompletableFuture gate = new CompletableFuture<>(); + CompletableFuture future = gate.thenApply((value) -> { + throw new IllegalStateException("boom"); + }); + AtomicReference resolved = new AtomicReference<>(); + GraphQL graphQl = GraphQlSetup.schemaContent(SCHEMA_CONTENT) + .queryFetcher("greeting", (env) -> future) + .exceptionResolver((exception, environment) -> { + resolved.set(exception); + return Mono.empty(); + }) + .toGraphQl(); + + ExecutionInput input = ExecutionInput.newExecutionInput().query("{ greeting }").build(); + Mono resultMono = Mono.fromFuture(graphQl.executeAsync(input)); + + // Failing the dependent stage produces a CompletionException, which must be + // unwrapped before it reaches a resolver, as MonoCompletionStage unwrapped it + Thread completer = new Thread(() -> gate.complete("go")); + completer.start(); + + ExecutionResult result = resultMono.toFuture().get(10, TimeUnit.SECONDS); + assertThat(result.getErrors()).hasSize(1); + await().untilAsserted(() -> assertThat(resolved.get()) + .isInstanceOf(IllegalStateException.class).hasMessage("boom")); + } + @Test // gh-980 void trivialDataFetcherIsNotDecorated() { GraphQL graphQl = GraphQlSetup.schemaContent(SCHEMA_CONTENT) @@ -341,4 +443,140 @@ void testExtensionsAreRetained() throws Exception { assertThat(executionResult.getExtensions()).containsEntry("foo", "bar"); } + + @Test + void completableFutureCancellationPropagatesToSource() throws Exception { + CompletableFuture source = new CompletableFuture<>(); + Object wrapped = newDecorator((env) -> source).get(environment(GraphQLContext.getDefault())); + + assertThat(wrapped).isInstanceOf(CompletableFuture.class); + ((CompletableFuture) wrapped).cancel(true); + + assertThat(source).isCancelled(); + } + + @Test + void completableFutureUnwrapsCompletionException() throws Exception { + CompletableFuture gate = new CompletableFuture<>(); + CompletableFuture source = gate.thenApply((value) -> { + throw new IllegalStateException("boom"); + }); + Object wrapped = newDecorator((env) -> source).get(environment(GraphQLContext.getDefault())); + + gate.complete("go"); + + Throwable failure = ((CompletableFuture) wrapped).handle((value, throwable) -> throwable).join(); + assertThat(failure).isInstanceOf(IllegalStateException.class).hasMessage("boom"); + } + + @Test + void alreadyFailedFutureIsUnwrapped() throws Exception { + CompletableFuture source = CompletableFuture.supplyAsync(() -> { + throw new IllegalStateException("boom"); + }); + // Ensure the source has already failed before the decorator sees it; the failed + // fast path must still unwrap rather than return the stage as-is + try { + source.join(); + } + catch (Exception ignored) { + } + Object wrapped = newDecorator((env) -> source).get(environment(GraphQLContext.getDefault())); + + Throwable failure = ((CompletableFuture) wrapped).handle((value, throwable) -> throwable).join(); + assertThat(failure).isInstanceOf(IllegalStateException.class).hasMessage("boom"); + } + + @Test + void originalFailureIsPrimaryWhenScopeFails() throws Exception { + IllegalStateException original = new IllegalStateException("original"); + CompletableFuture source = new CompletableFuture<>(); + GraphQLContext graphQlContext = GraphQLContext.getDefault(); + ContextPropagationHelper.saveInstance(failingSnapshotFactory(), graphQlContext); + + Object wrapped = newDecorator((env) -> source).get(environment(graphQlContext)); + source.completeExceptionally(original); + + Throwable failure = ((CompletableFuture) wrapped).handle((value, throwable) -> throwable).join(); + + assertThat(failure).isSameAs(original); + assertThat(failure.getSuppressed()).hasSize(1); + } + + @Test + void alreadyCompletedFutureIsReturnedAsIs() throws Exception { + CompletableFuture source = CompletableFuture.completedFuture("hello"); + Object wrapped = newDecorator((env) -> source).get(environment(GraphQLContext.getDefault())); + + assertThat(wrapped).isSameAs(source); + } + + private static DataFetchingEnvironment environment(GraphQLContext graphQlContext) { + return DataFetchingEnvironmentImpl.newDataFetchingEnvironment() + .graphQLContext(graphQlContext) + .build(); + } + + private static ContextDataFetcherDecorator newDecorator(DataFetcher delegate) { + try { + Constructor constructor = + ContextDataFetcherDecorator.class.getDeclaredConstructor( + DataFetcher.class, boolean.class, SubscriptionExceptionResolver.class); + constructor.setAccessible(true); + return constructor.newInstance(delegate, false, new CompositeSubscriptionExceptionResolver(List.of())); + } + catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + /** Factory whose snapshots fail in {@code setThreadLocals}. */ + private static ContextSnapshotFactory failingSnapshotFactory() { + ContextSnapshot snapshot = new ContextSnapshot() { + @Override + public C updateContext(C context) { + return context; + } + + @Override + public C updateContext(C context, Predicate predicate) { + return context; + } + + @Override + public Scope setThreadLocals() { + throw new IllegalStateException("scope failure"); + } + + @Override + public Scope setThreadLocals(Predicate predicate) { + throw new IllegalStateException("scope failure"); + } + + @Override + public Callable wrap(Callable callable) { + return callable; + } + }; + return new ContextSnapshotFactory() { + @Override + public ContextSnapshot captureAll(Object... values) { + return snapshot; + } + + @Override + public ContextSnapshot captureFrom(Object... values) { + return snapshot; + } + + @Override + public ContextSnapshot.Scope setThreadLocalsFrom(Object context, String... keys) { + throw new UnsupportedOperationException(); + } + }; + } + + private record Container(String value) { + } + }