From e85afc8f4ea9f30ff606752c3c3c22e6a0509f43 Mon Sep 17 00:00:00 2001 From: Oryan Date: Wed, 4 Nov 2026 13:54:55 -0500 Subject: [PATCH] Run the bounded return value unwrapping check in mvn verify ReturnValueUnwrappingTest compiles the check from src/test/resources/returnvalue and fails the build when a resolver return type the schema build accepts doesn't reach graphql-java fully unwrapped. The verify-return-value-unwrapping skill's check.sh now runs that test, with its options passed as -Dunwrapping.args. --- .../verify-return-value-unwrapping/SKILL.md | 151 ++++ .../verify-return-value-unwrapping/check.sh | 23 + .../returnvalue/ReturnValueUnwrappingTest.kt | 59 ++ src/test/resources/returnvalue/Check.java | 655 ++++++++++++++++++ src/test/resources/returnvalue/Fixtures.java | 113 +++ .../resources/returnvalue/known-findings.txt | 0 6 files changed, 1001 insertions(+) create mode 100644 .claude/skills/verify-return-value-unwrapping/SKILL.md create mode 100755 .claude/skills/verify-return-value-unwrapping/check.sh create mode 100644 src/test/kotlin/graphql/kickstart/tools/returnvalue/ReturnValueUnwrappingTest.kt create mode 100644 src/test/resources/returnvalue/Check.java create mode 100644 src/test/resources/returnvalue/Fixtures.java create mode 100644 src/test/resources/returnvalue/known-findings.txt diff --git a/.claude/skills/verify-return-value-unwrapping/SKILL.md b/.claude/skills/verify-return-value-unwrapping/SKILL.md new file mode 100644 index 00000000..c9ed81c9 --- /dev/null +++ b/.claude/skills/verify-return-value-unwrapping/SKILL.md @@ -0,0 +1,151 @@ +--- +name: verify-return-value-unwrapping +description: Exhaustively check, up to a bound, that a resolver method's return value reaches graphql-java fully unwrapped. Futures are awaited, generic wrappers are transformed, Optional and DataFetcherResult are handled, and list order, nulls and failures are kept, for every return type nested up to 3 containers deep. Use it before pushing any change to ReturnValueUnwrapper, TypeClassMatcher's unwrapping, GenericTypeResolver.resolve, the data fetchers in MethodFieldResolver, or the GenericWrapper defaults, and whenever a bug report says graphql-java got a CompletableFuture, Optional or wrapper object as a field value. +--- + +# Verify return value unwrapping + +## The property + +A user writes a resolver method whose return type nests containers, such as +`CompletableFuture>>`. If the schema build accepts that method, then graphql-java must get +exactly the value the method returned, with every container removed. Futures are waited on and generic wrappers go +through their transformers. List order and nulls are kept. A failed future or a throwing transformer fails the field. +A `Future` that isn't a `CompletionStage` fails the field with the "can't wait on" error. + +When this breaks, a production query returns `CompletableFuture@1a2b[Completed normally]` as a string, or fails with +"Expected source object to be an instance of 'Payload' but instead got 'CompletableFuture'". It only happens for the +return types and values nobody wrote a test for. + +## How the check works + +`src/test/resources/returnvalue/Check.java` lists every return type built from up to `--depth` (default 3) of these containers around a leaf: + +| Container | Value variants (the first one is the default) | +|---|---| +| `List` | 2 elements, `null`, empty | +| `Page` (a `listCollectionWithTransformer` wrapper) | 2 elements, `null`, empty | +| `CompletableFuture` | completes with the value, `null`, fails | +| `Future` | a `CompletableFuture`, `null`, a completed `FutureTask` | +| `Later` (a `withCompletionStageTransformer` wrapper whose transformer returns its `CompletableFuture`, like `Mono::toFuture`) | holds a future of the value, `null`, holds a failing future | +| `Try` (a wrapper whose transformer returns the value or throws) | success, `null`, failure | +| `DataFetcherResult` | the value, `null`, the value plus an error | +| `Optional` | present, empty | + +The leaf is `Payload` (an object type), `String`, or `Object` for a union `Item = Payload | FutureItem`. `FutureItem` +implements `Future`, so only the declared type tells a leaf from a future. Each return type runs with an all-nullable +and an all-non-null GraphQL type. + +For each combination the check compiles a Java resolver class with that return type at runtime. It builds the schema +through the public `SchemaParser` API, which rejects about a quarter of the combinations, such as `Optional` below the top +level. For every accepted one it executes the query once for each value that makes at most `--budget` (default 2) +non-default choices. When the return type holds futures, it runs each value three ways: futures already completed, +and pending futures completed after the data fetcher returns, first-created first and last-created first. + +The expected result is what graphql-java returns when a plain data fetcher on the same schema returns the plain value, +or throws the failure. So graphql-java's own null handling and error format apply to both sides. When one value +holds several failures, any one of them failing the field counts as correct. + +`ReturnValueUnwrappingTest` compiles `Check.java` and `Fixtures.java` at test time and runs the check, so `mvn verify` +runs it at the default bounds on every build. About 172,000 executions run in about 15 seconds. + +## Run + +From the root of the checkout or worktree you want to check: + +```bash +.claude/skills/verify-return-value-unwrapping/check.sh +``` + +It prints the commit and the JDK, runs `mvn clean test -Dtest=ReturnValueUnwrappingTest` with the options below passed +as `-Dunwrapping.args`, and prints the report. On a failure it also prints the path of the Maven log. + +| Exit | Meaning | +|---|---| +| 0 | `PASS`, or `PASS apart from the known findings above` | +| 1 | `FAIL`: a return type that isn't a known finding breaks the property | +| 2 | `MODEL ERROR`: the checkout or the check didn't compile, or the build rejected a return type the check must exercise, so a pass would prove nothing | +| 3 | `STALE`: a known finding no longer fails. Delete its line from `known-findings.txt` | + +Options: `--depth N`, `--budget N`, `--show N` (counterexamples printed, default 15), and `--rejected`, which lists +every combination the schema build rejected, with the build's error. A depth below 3 can't build the `mustAccept` +return types, so it ends in `MODEL ERROR`. + +## Reading a counterexample + +``` +public List> field() for field: [Payload] (21 failing executions, first shown) + returns: List[CompletableFuture(Payload(v1)), FutureTask] + futures complete before the data fetcher returns + expected: {errors=[{message=Exception while fetching data (/field) : Resolver method '...' resolved to a java.util.concurrent.FutureTask, which graphql-java can't wait on. ... + got: {errors=[{message=Exception while fetching data (/field[1]/data) : Expected source object to be an instance of 'unwrapcheck.Fixtures$Payload' but instead got 'java.util.concurrent.FutureTask', ... +``` + +The first line is the resolver method and the field's GraphQL type. `returns` is the value the method returned. +`Later(CompletableFuture(x))` means a `Later` whose transformer returns a `CompletableFuture` of `x`. Only the first +failing value per return type is shown. Rerun with a higher `--show` to see more return types. + +A real bug versus a modeling error: + +- **Real bug.** `got` holds a container object (a future, `Optional`, `DataFetcherResult`, `Try`) as a value, an + "Expected source object" error, a lost or reordered element, a missing error, or a blocked data fetcher. Report it with + the counterexample. Don't change the check to make it pass. +- **Real bug in the schema build.** `expected` is itself nonsense, such as `Payload` bound to the `DataFetcherResult` + class, which returned `"unwrapcheck.Fixtures$Payload@5a77273c"` as `data`. The plain data fetcher runs on the same schema, so if the build bound the GraphQL + type to the wrong class, both sides go wrong. +- **Modeling error.** The check's own idea of the value is wrong. For example, a new container variant builds a value + that its declared type doesn't allow, or the error message the check expects for a `FutureTask` (in `build`, case + `FUTURE_TASK`) differs from a message the library changed on purpose. Confirm against the library's own tests in + `src/test/kotlin/graphql/kickstart/tools/NestedGenericWrapperTest.kt` before you edit the check. +- **`MODEL ERROR` about rejected return types.** A change made the build reject a return type in `mustAccept` in + `Check.java`. That's either a regression in the build, which you report, or an intended change, after which you swap in + another accepted return type of the same kind. + +## Known findings + +`src/test/resources/returnvalue/known-findings.txt` lists the return types that break the property at the sync commit, one per line as +` # `. They still +print as `KNOWN` with a counterexample on every run, and the check passes apart from them. A new break inside a known +pattern is hidden, so after a change to the code a known finding covers, read its counterexample. + +At the sync commit there are none. The check found two bugs when it was written, and both are fixed. One was a +`DataFetcherResult` inside an `Optional` (#939). The other was a wrapper whose transformer returns a future, directly around +a declared future (#938). A `withTransformer` registration keeps that #938 behavior, which is why `Later` is registered +through `withCompletionStageTransformer`. + +When a fix lands, the check exits 3. Delete the line then, so that a regression shows up as `FAIL`. + +## What this does not cover + +- Suspend functions, subscriptions and `Publisher`, arrays, and Kotlin-declared resolver methods. The generated resolvers + are Java methods without parameters, so only `LightMethodFieldResolverDataFetcher` runs, not + `MethodFieldResolverDataFetcher`. +- Wrappers picked by a subclass of the value (`Box` and `SpecialBox` in `NestedGenericWrapperTest`), wrappers with a type + argument index other than 0, custom `schemaWrapper`s other than the list one, transformers that return a `FutureTask`, + and DataLoader futures. +- Lists of more than 2 elements, more than 2 non-default choices per value, more than 3 containers, and completion + orders other than the two listed. A pass says nothing beyond those bounds. +- Which return types the schema build should reject. The check only exercises what the build accepts. + +## Coverage and sync + +Last confirmed to describe the code at commit `cd3233ca` (master, 2026-10-30). It covers: + +| File | What | +|---|---| +| `src/main/kotlin/graphql/kickstart/tools/resolver/ReturnValueUnwrapper.kt` | all of it | +| `src/main/kotlin/graphql/kickstart/tools/TypeClassMatcher.kt` | `PotentialMatch.unwrap`, `Unwrapped` | +| `src/main/kotlin/graphql/kickstart/tools/GenericTypeResolver.kt` | `resolve`, `resolveTypeVariables` | +| `src/main/kotlin/graphql/kickstart/tools/resolver/MethodFieldResolver.kt` | `createDataFetcher` (`valueClass`, the unwrapper), `returnType`, `returnValueMatch`, `LightMethodFieldResolverDataFetcher` | +| `src/main/kotlin/graphql/kickstart/tools/SchemaParserOptions.kt` | `GenericWrapper` and the default wrappers in `build()` | + +To see whether a change needs another look: + +```bash +git log --oneline cd3233ca..HEAD -- src/main/kotlin/graphql/kickstart/tools/resolver/ReturnValueUnwrapper.kt src/main/kotlin/graphql/kickstart/tools/TypeClassMatcher.kt src/main/kotlin/graphql/kickstart/tools/GenericTypeResolver.kt src/main/kotlin/graphql/kickstart/tools/resolver/MethodFieldResolver.kt src/main/kotlin/graphql/kickstart/tools/SchemaParserOptions.kt +``` + +Move the sync commit forward only after you've read those changes and confirmed that the containers, variants and +expected values in `Check.java` still describe them. For example, a new default wrapper or a new kind of unwrapping +step needs a new `Container` with its variants and its plain value in `build`. After an intended change, rerun the check, +and break the new code on purpose once in a scratch worktree to see the check fail before you trust its pass. diff --git a/.claude/skills/verify-return-value-unwrapping/check.sh b/.claude/skills/verify-return-value-unwrapping/check.sh new file mode 100755 index 00000000..6f57e1b0 --- /dev/null +++ b/.claude/skills/verify-return-value-unwrapping/check.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +checkout=$(git rev-parse --show-toplevel) +log=$(mktemp "${TMPDIR:-/tmp}/verify-return-value-unwrapping.XXXXXX") + +echo "checkout $checkout at $(git -C "$checkout" rev-parse --short HEAD)$(git -C "$checkout" diff --quiet HEAD -- src || echo ' plus uncommitted src changes')" +java -version 2>&1 | head -1 + +if (cd "$checkout" && mvn -B -ntp clean test -Dtest=ReturnValueUnwrappingTest "-Dunwrapping.args=$*") > "$log" 2>&1; then + sed -n '/Running .*ReturnValueUnwrappingTest/,/Tests run:/p' "$log" | sed -e '1d' -e '$d' + rm "$log" + exit 0 +fi + +sed -n '/AssertionError: /,/^\tat /p' "$log" | sed -e '1s/.*AssertionError: //' -e '$d' +echo "Maven log: $log" +grep -q '^FAIL:' "$log" && exit 1 +grep -q 'MODEL ERROR:' "$log" && exit 2 +grep -q '^STALE:' "$log" && exit 3 +tail -40 "$log" +echo "MODEL ERROR: the checkout didn't build" +exit 2 diff --git a/src/test/kotlin/graphql/kickstart/tools/returnvalue/ReturnValueUnwrappingTest.kt b/src/test/kotlin/graphql/kickstart/tools/returnvalue/ReturnValueUnwrappingTest.kt new file mode 100644 index 00000000..aeedf198 --- /dev/null +++ b/src/test/kotlin/graphql/kickstart/tools/returnvalue/ReturnValueUnwrappingTest.kt @@ -0,0 +1,59 @@ +package graphql.kickstart.tools.returnvalue + +import org.junit.Assert.fail +import org.junit.Test +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.PrintStream +import java.net.URLClassLoader +import java.nio.file.Files +import java.nio.file.Path +import java.util.spi.ToolProvider + +class ReturnValueUnwrappingTest { + + @Test + fun `every return type the schema build accepts reaches graphql-java unwrapped`() { + val dir = Files.createTempDirectory("return-value-unwrapping") + try { + val classpath = listOfNotNull(System.getProperty("jdk.module.path"), System.getProperty("java.class.path")) + .joinToString(File.pathSeparator) + compile(classpath, dir, copy("Check.java", dir), copy("Fixtures.java", dir)) + + val args = System.getProperty("unwrapping.args", "").split(" ").filter { it.isNotBlank() } + + listOf("--known", copy("known-findings.txt", dir).toString()) + val report = ByteArrayOutputStream() + val passed = URLClassLoader(arrayOf(dir.toUri().toURL()), javaClass.classLoader).use { loader -> + PrintStream(report, true, Charsets.UTF_8).use { out -> + loader.loadClass("unwrapcheck.Check") + .getMethod("check", Array::class.java, String::class.java, PrintStream::class.java) + .invoke(null, args.toTypedArray(), classpath + File.pathSeparator + dir, out) as Boolean + } + } + if (!passed) { + fail(report.toString(Charsets.UTF_8)) + } + print(report.toString(Charsets.UTF_8)) + } finally { + dir.toFile().deleteRecursively() + } + } + + private fun copy(resource: String, dir: Path): Path { + val target = dir.resolve(resource) + javaClass.getResourceAsStream("/returnvalue/$resource")!!.use { Files.copy(it, target) } + return target + } + + // java.util.spi.ToolProvider is in java.base, so this module needs no access to java.compiler + private fun compile(classpath: String, dir: Path, vararg sources: Path) { + val output = ByteArrayOutputStream() + val javac = ToolProvider.findFirst("javac").orElseThrow() + val status = PrintStream(output, true, Charsets.UTF_8).use { out -> + javac.run(out, out, "-d", dir.toString(), "-classpath", classpath, "-nowarn", "-proc:none", *sources.map { it.toString() }.toTypedArray()) + } + if (status != 0) { + fail("MODEL ERROR: the check doesn't compile against this checkout:\n" + output.toString(Charsets.UTF_8)) + } + } +} diff --git a/src/test/resources/returnvalue/Check.java b/src/test/resources/returnvalue/Check.java new file mode 100644 index 00000000..c801ac13 --- /dev/null +++ b/src/test/resources/returnvalue/Check.java @@ -0,0 +1,655 @@ +package unwrapcheck; + +import graphql.ExecutionInput; +import graphql.ExecutionResult; +import graphql.GraphQL; +import graphql.GraphqlErrorBuilder; +import graphql.execution.DataFetcherResult; +import graphql.kickstart.tools.GraphQLResolver; +import graphql.kickstart.tools.SchemaParser; +import graphql.kickstart.tools.SchemaParserBuilder; +import graphql.kickstart.tools.SchemaParserOptions; +import graphql.kickstart.tools.SchemaParserOptions.GenericWrapper; +import graphql.schema.DataFetcher; +import graphql.schema.FieldCoordinates; +import graphql.schema.GraphQLSchema; +import unwrapcheck.Fixtures.FutureItem; +import unwrapcheck.Fixtures.Later; +import unwrapcheck.Fixtures.Page; +import unwrapcheck.Fixtures.Payload; +import unwrapcheck.Fixtures.Try; + +import javax.tools.DiagnosticCollector; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public final class Check { + + enum Container { + LIST("java.util.List", Variant.VALUE, Variant.NULL, Variant.EMPTY), + PAGE("unwrapcheck.Fixtures.Page", Variant.VALUE, Variant.NULL, Variant.EMPTY), + COMPLETABLE_FUTURE("java.util.concurrent.CompletableFuture", Variant.VALUE, Variant.NULL, Variant.FAILED), + FUTURE("java.util.concurrent.Future", Variant.VALUE, Variant.NULL, Variant.FUTURE_TASK), + LATER("unwrapcheck.Fixtures.Later", Variant.VALUE, Variant.NULL, Variant.FAILED), + TRY("unwrapcheck.Fixtures.Try", Variant.VALUE, Variant.NULL, Variant.FAILED), + DATA_FETCHER_RESULT("graphql.execution.DataFetcherResult", Variant.VALUE, Variant.NULL, Variant.WITH_ERROR), + OPTIONAL("java.util.Optional", Variant.VALUE, Variant.EMPTY); + + final String javaName; + final List variants; + + Container(String javaName, Variant... variants) { + this.javaName = javaName; + this.variants = List.of(variants); + } + + boolean isList() { + return this == LIST || this == PAGE; + } + + boolean isFuture() { + return this == COMPLETABLE_FUTURE || this == FUTURE || this == LATER; + } + } + + enum Leaf { + PAYLOAD("unwrapcheck.Fixtures.Payload", "Payload", " { data }"), + STRING("java.lang.String", "String", ""), + OBJECT("java.lang.Object", "Item", " { __typename ... on Payload { data } ... on FutureItem { data } }"); + + final String javaName; + final String graphQLName; + final String selection; + + Leaf(String javaName, String graphQLName, String selection) { + this.javaName = javaName; + this.graphQLName = graphQLName; + this.selection = selection; + } + } + + enum Nullability {NULLABLE, NON_NULL} + + enum Variant {VALUE, NULL, EMPTY, FAILED, FUTURE_TASK, WITH_ERROR, FUTURE_ITEM} + + enum Timing { + DONE("before the data fetcher returns"), + PENDING_IN_ORDER("after the data fetcher returns, first created first"), + PENDING_REVERSED("after the data fetcher returns, last created first"); + + final String description; + + Timing(String description) { + this.description = description; + } + } + + static final class Case { + final List shape; + final Leaf leaf; + final Nullability nullability; + final String className; + + Case(List shape, Leaf leaf, Nullability nullability, String className) { + this.shape = shape; + this.leaf = leaf; + this.nullability = nullability; + this.className = className; + } + + String javaType() { + String type = leaf.javaName; + for (int i = shape.size() - 1; i >= 0; i--) { + type = shape.get(i).javaName + "<" + type + ">"; + } + return type; + } + + String graphQLType() { + boolean nonNull = nullability == Nullability.NON_NULL; + String type = leaf.graphQLName + (nonNull ? "!" : ""); + long lists = shape.stream().filter(Container::isList).count(); + for (long i = 0; i < lists; i++) { + type = "[" + type + "]" + (nonNull ? "!" : ""); + } + return type; + } + + String shortJavaType() { + return javaType().replace("unwrapcheck.Fixtures.", "").replaceAll("[a-z.]+\\.(?=[A-Z])", ""); + } + + String describe() { + return "public " + shortJavaType() + " field() for field: " + graphQLType(); + } + } + + static final class Plan { + final Variant variant; + final List children; + final int cost; + + Plan(Variant variant, List children, int cost) { + this.variant = variant; + this.children = children; + this.cost = cost; + } + } + + static final class Built { + final Object returned; + final Object expected; + final String text; + + Built(Object returned, Object expected, String text) { + this.returned = returned; + this.expected = expected; + this.text = text; + } + } + + static final class Context { + final Timing timing; + final String method; + final List completions = new ArrayList<>(); + final Set failures = new LinkedHashSet<>(); + int nextId = 1; + + Context(Timing timing, String method) { + this.timing = timing; + this.method = method; + } + + CompletableFuture future(Object value, String failure) { + if (timing == Timing.DONE) { + return failure == null ? CompletableFuture.completedFuture(value) : CompletableFuture.failedFuture(new IllegalStateException(failure)); + } + CompletableFuture future = new CompletableFuture<>(); + completions.add(() -> { + if (failure == null) { + future.complete(value); + } else { + future.completeExceptionally(new IllegalStateException(failure)); + } + }); + return future; + } + } + + static final class Violation { + final Case testCase; + final String value; + final Timing timing; + final String expected; + final String actual; + + Violation(Case testCase, String value, Timing timing, String expected, String actual) { + this.testCase = testCase; + this.value = value; + this.timing = timing; + this.expected = expected; + this.actual = actual; + } + } + + private static final String BLOCKED = "the data fetcher blocked until they completed"; + + private static volatile Object oracleValue; + private static volatile String oracleFailure; + + private static final ExecutorService fetching = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "fetch"); + thread.setDaemon(true); + return thread; + }); + + private static final SchemaParserOptions options = SchemaParserOptions.newOptions() + .genericWrappers( + GenericWrapper.withTransformer(Try.class, 0, (Try t) -> t.get(), type -> type), + GenericWrapper.listCollectionWithTransformer(Page.class, 0, (Page p) -> p.getContent()), + GenericWrapper.withCompletionStageTransformer(Later.class, 0, (Later l) -> l.toFuture())) + .build(); + + private static final List mustAccept = List.of( + "java.util.List> [Payload]", + "java.util.concurrent.CompletableFuture>> [Payload]", + "graphql.execution.DataFetcherResult>> [String]", + "java.util.Optional>> [Item]", + "java.util.List>> [Item!]!" + ); + + public static boolean check(String[] args, String classpath, PrintStream out) throws Exception { + int depth = intArg(args, "--depth", 3); + int budget = intArg(args, "--budget", 2); + long started = System.nanoTime(); + + List cases = cases(depth); + Map> resolvers = compile(cases, classpath); + + int rejected = 0; + int runs = 0; + boolean blocked = false; + Set accepted = new LinkedHashSet<>(); + Map> violations = new LinkedHashMap<>(); + for (Case testCase : cases) { + GraphQLSchema schema; + try { + schema = schema(testCase, resolvers.get(testCase.className).getDeclaredConstructor().newInstance()); + } catch (RuntimeException e) { + rejected++; + if (flag(args, "--rejected")) { + out.println("rejected " + testCase.describe() + ": " + e.getMessage().lines().findFirst().orElse("")); + } + continue; + } + accepted.add(testCase.javaType() + " " + testCase.graphQLType()); + GraphQL actual = GraphQL.newGraphQL(schema).build(); + GraphQL oracle = GraphQL.newGraphQL(oracleSchema(schema)).build(); + String query = "query { field" + testCase.leaf.selection + " }"; + List timings = testCase.shape.stream().anyMatch(Container::isFuture) && !blocked ? List.of(Timing.values()) : List.of(Timing.DONE); + plans: + for (Plan plan : plansWithinBudget(testCase, 0, budget)) { + for (Timing timing : timings) { + runs++; + Violation violation = run(testCase, plan, timing, actual, oracle, query); + if (violation != null) { + violations.computeIfAbsent(testCase, c -> new ArrayList<>()).add(violation); + if (violation.actual.equals(BLOCKED)) { + blocked = true; + break plans; + } + } + } + } + } + + List missing = mustAccept.stream().filter(it -> !accepted.contains(it)).collect(Collectors.toList()); + out.printf("depth %d, budget %d: %d return types, %d rejected by the schema build, %d accepted, %d executions, %.1fs%n", + depth, budget, cases.size(), rejected, accepted.size(), runs, (System.nanoTime() - started) / 1e9); + if (blocked) { + out.println("A data fetcher blocked on a pending future, so later return types ran with completed futures only."); + } + + Map known = knownFindings(stringArg(args, "--known")); + Map> knownFailing = new LinkedHashMap<>(); + known.keySet().forEach(pattern -> knownFailing.put(pattern, new ArrayList<>())); + List> unknown = new ArrayList<>(); + violations.forEach((testCase, list) -> { + String pattern = known.keySet().stream().filter(it -> Pattern.compile(it).matcher(testCase.shortJavaType()).find()).findFirst().orElse(null); + if (pattern == null) { + unknown.add(list); + } else { + knownFailing.get(pattern).add(testCase); + } + }); + + knownFailing.forEach((pattern, failing) -> { + if (!failing.isEmpty()) { + out.printf("%nKNOWN (%s): %d return types still fail, e.g.%n", known.get(pattern), failing.size()); + print(out, violations.get(failing.get(0)).get(0), violations.get(failing.get(0)).size()); + } + }); + if (!unknown.isEmpty()) { + int total = unknown.stream().mapToInt(List::size).sum(); + out.printf("%nFAIL: %d executions in %d return types gave graphql-java something other than the value the resolver returned.%n", total, unknown.size()); + unknown.stream().limit(intArg(args, "--show", 15)).forEach(list -> print(out, list.get(0), list.size())); + return false; + } + if (!missing.isEmpty() || runs == 0) { + out.println("\nMODEL ERROR: the schema build rejected return types the check must exercise, so a pass would prove nothing:"); + missing.forEach(it -> out.println(" " + it)); + return false; + } + List fixed = knownFailing.entrySet().stream().filter(it -> it.getValue().isEmpty()).map(it -> known.get(it.getKey())).collect(Collectors.toList()); + if (!fixed.isEmpty()) { + out.println("\nSTALE: these known findings no longer fail. Delete their lines from src/test/resources/returnvalue/known-findings.txt so a regression shows up as FAIL:"); + fixed.forEach(it -> out.println(" " + it)); + return false; + } + out.println(violations.isEmpty() ? "PASS" : "\nPASS apart from the known findings above"); + return true; + } + + private static Map knownFindings(String path) throws Exception { + Map known = new LinkedHashMap<>(); + for (String line : Files.readAllLines(Path.of(path))) { + if (!line.isBlank() && !line.startsWith("#")) { + int separator = line.indexOf(" # "); + if (separator < 0) { + throw new IllegalArgumentException("A known finding is \" # \", not: " + line); + } + known.put(line.substring(0, separator).trim(), line.substring(separator + 3).trim()); + } + } + return known; + } + + private static void print(PrintStream out, Violation v, int count) { + out.println(); + out.println(v.testCase.describe() + (count > 1 ? " (" + count + " failing executions, first shown)" : "")); + out.println(" returns: " + v.value); + if (v.testCase.shape.stream().anyMatch(Container::isFuture)) { + out.println(" futures complete " + v.timing.description); + } + out.println(" expected: " + v.expected); + out.println(" got: " + v.actual); + } + + static List cases(int depth) { + List> shapes = new ArrayList<>(); + shapes.add(List.of()); + for (int start = 0, size = 0; size < depth; size++) { + int end = shapes.size(); + for (int i = start; i < end; i++) { + for (Container container : Container.values()) { + List shape = new ArrayList<>(); + shape.add(container); + shape.addAll(shapes.get(i)); + shapes.add(List.copyOf(shape)); + } + } + start = end; + } + List cases = new ArrayList<>(); + for (int i = 0; i < shapes.size(); i++) { + for (Leaf leaf : Leaf.values()) { + String className = "unwrapcheck.gen.R" + i + "_" + leaf.ordinal(); + for (Nullability nullability : Nullability.values()) { + cases.add(new Case(shapes.get(i), leaf, nullability, className)); + } + } + } + return cases; + } + + static List plansWithinBudget(Case testCase, int level, int budget) { + List plans = new ArrayList<>(); + if (level == testCase.shape.size()) { + plans.add(new Plan(Variant.VALUE, List.of(), 0)); + if (budget > 0) { + plans.add(new Plan(Variant.NULL, List.of(), 1)); + if (testCase.leaf == Leaf.OBJECT) { + plans.add(new Plan(Variant.FUTURE_ITEM, List.of(), 1)); + } + } + return plans; + } + Container container = testCase.shape.get(level); + for (Variant variant : container.variants) { + int cost = variant == Variant.VALUE ? 0 : 1; + if (cost > budget) { + continue; + } + boolean hasInner = variant == Variant.VALUE || variant == Variant.WITH_ERROR; + if (!hasInner) { + plans.add(new Plan(variant, List.of(), cost)); + } else if (container.isList()) { + for (Plan first : plansWithinBudget(testCase, level + 1, budget - cost)) { + for (Plan second : plansWithinBudget(testCase, level + 1, budget - cost - first.cost)) { + plans.add(new Plan(variant, List.of(first, second), cost + first.cost + second.cost)); + } + } + } else { + for (Plan inner : plansWithinBudget(testCase, level + 1, budget - cost)) { + plans.add(new Plan(variant, List.of(inner), cost + inner.cost)); + } + } + } + return plans; + } + + static Built build(Case testCase, Plan plan, int level, Context context) { + if (level == testCase.shape.size()) { + if (plan.variant == Variant.NULL) { + return new Built(null, null, "null"); + } + String id = "v" + context.nextId++; + if (plan.variant == Variant.FUTURE_ITEM) { + return new Built(new FutureItem(id), new FutureItem(id), "FutureItem(" + id + ")"); + } + if (testCase.leaf == Leaf.STRING) { + return new Built(id, id, "\"" + id + "\""); + } + return new Built(new Payload(id), new Payload(id), "Payload(" + id + ")"); + } + Container container = testCase.shape.get(level); + switch (plan.variant) { + case NULL: + return new Built(null, null, "null"); + case EMPTY: + switch (container) { + case LIST: + return new Built(List.of(), List.of(), "List[]"); + case PAGE: + return new Built(new Page<>(List.of()), List.of(), "Page[]"); + default: + return new Built(Optional.empty(), null, "Optional.empty()"); + } + case FAILED: { + String failure = "failed " + container.name().toLowerCase() + " v" + context.nextId++; + context.failures.add(failure); + switch (container) { + case TRY: + return new Built(Try.failure(failure), null, "Try.failure(\"" + failure + "\")"); + case LATER: + return new Built(new Later<>(context.future(null, failure)), null, "Later(failed CompletableFuture \"" + failure + "\")"); + default: + return new Built(context.future(null, failure), null, "failed CompletableFuture(\"" + failure + "\")"); + } + } + case FUTURE_TASK: { + context.failures.add("Resolver method '" + context.method + "' resolved to a " + FutureTask.class.getName() + ", which graphql-java can't wait on. " + + "Return a CompletionStage, such as a CompletableFuture, from the method or its generic wrapper transformer instead."); + FutureTask task = new FutureTask<>(() -> null); + task.run(); + return new Built(task, null, "FutureTask"); + } + default: + break; + } + List inner = new ArrayList<>(); + for (Plan child : plan.children) { + inner.add(build(testCase, child, level + 1, context)); + } + Built first = inner.get(0); + switch (container) { + case LIST: + case PAGE: { + List returned = inner.stream().map(it -> it.returned).collect(Collectors.toCollection(ArrayList::new)); + List expected = inner.stream().map(it -> it.expected).collect(Collectors.toCollection(ArrayList::new)); + String text = inner.stream().map(it -> it.text).collect(Collectors.joining(", ", "[", "]")); + return container == Container.LIST ? new Built(returned, expected, "List" + text) : new Built(new Page<>(returned), expected, "Page" + text); + } + case COMPLETABLE_FUTURE: + case FUTURE: + return new Built(context.future(first.returned, null), first.expected, "CompletableFuture(" + first.text + ")"); + case LATER: + return new Built(new Later<>(context.future(first.returned, null)), first.expected, "Later(CompletableFuture(" + first.text + "))"); + case TRY: + return new Built(Try.success(first.returned), first.expected, "Try.success(" + first.text + ")"); + case OPTIONAL: + return new Built(Optional.ofNullable(first.returned), first.expected, "Optional.ofNullable(" + first.text + ")"); + default: { + boolean withError = plan.variant == Variant.WITH_ERROR; + String error = "error beside " + first.text; + return new Built(result(first.returned, withError ? error : null), result(first.expected, withError ? error : null), + "DataFetcherResult(" + first.text + (withError ? ", error)" : ")")); + } + } + } + + private static DataFetcherResult result(Object data, String error) { + DataFetcherResult.Builder builder = DataFetcherResult.newResult().data(data); + if (error != null) { + builder.error(GraphqlErrorBuilder.newError().message(error).build()); + } + return builder.build(); + } + + static Violation run(Case testCase, Plan plan, Timing timing, GraphQL actual, GraphQL oracle, String query) { + Context context = new Context(timing, testCase.className + ".field"); + Built built = build(testCase, plan, 0, context); + if (timing == Timing.PENDING_REVERSED) { + Collections.reverse(context.completions); + } + + String got; + Fixtures.nextReturnValue = built.returned; + java.util.concurrent.Future> fetch = fetching.submit(() -> actual.executeAsync(ExecutionInput.newExecutionInput().query(query).build())); + CompletableFuture result; + try { + try { + result = fetch.get(1, TimeUnit.SECONDS); + } catch (TimeoutException e) { + context.completions.forEach(Runnable::run); + return new Violation(testCase, built.text, timing, "the data fetcher returns before its futures complete", BLOCKED); + } + context.completions.forEach(Runnable::run); + got = result.get(2, TimeUnit.SECONDS).toSpecification().toString(); + } catch (TimeoutException e) { + return new Violation(testCase, built.text, timing, "a result once every future completed", "no result after 2 seconds"); + } catch (Exception e) { + return new Violation(testCase, built.text, timing, "a result", "execute threw " + e); + } + + List acceptable = new ArrayList<>(); + if (context.failures.isEmpty()) { + oracleValue = built.expected; + oracleFailure = null; + acceptable.add(oracle.execute(query).toSpecification().toString()); + } else { + for (String failure : context.failures) { + oracleValue = null; + oracleFailure = failure; + acceptable.add(oracle.execute(query).toSpecification().toString()); + } + } + return acceptable.contains(got) ? null : new Violation(testCase, built.text, timing, String.join("\n or ", acceptable), got); + } + + static GraphQLSchema schema(Case testCase, Object resolver) { + String sdl = "type Query { field: " + testCase.graphQLType() + " }\n"; + SchemaParserBuilder parser = SchemaParser.newParser().resolvers((GraphQLResolver) resolver).options(options); + if (testCase.leaf != Leaf.STRING) { + sdl += "type Payload { data: String }\n"; + } + if (testCase.leaf == Leaf.OBJECT) { + sdl += "type FutureItem { data: String }\nunion Item = Payload | FutureItem\n"; + parser.dictionary(Payload.class, FutureItem.class); + } + return parser.schemaString(sdl).build().makeExecutableSchema(); + } + + static GraphQLSchema oracleSchema(GraphQLSchema schema) { + DataFetcher plain = environment -> { + if (oracleFailure != null) { + throw new IllegalStateException(oracleFailure); + } + return oracleValue; + }; + return schema.transform(builder -> builder.codeRegistry( + schema.getCodeRegistry().transform(registry -> registry.dataFetcher(FieldCoordinates.coordinates("Query", "field"), plain)))); + } + + static Map> compile(List cases, String classpath) throws Exception { + Map sources = new LinkedHashMap<>(); + for (Case testCase : cases) { + String simpleName = testCase.className.substring(testCase.className.lastIndexOf('.') + 1); + sources.putIfAbsent(testCase.className, + "package unwrapcheck.gen;\n" + + "public class " + simpleName + " implements graphql.kickstart.tools.GraphQLQueryResolver {\n" + + " @SuppressWarnings(\"unchecked\")\n" + + " public " + testCase.javaType() + " field() { return (" + testCase.javaType() + ") unwrapcheck.Fixtures.nextReturnValue; }\n" + + "}\n"); + } + + JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); + Map output = new HashMap<>(); + StandardJavaFileManager files = javac.getStandardFileManager(null, null, null); + ForwardingJavaFileManager memory = new ForwardingJavaFileManager<>(files) { + @Override + public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) { + return new SimpleJavaFileObject(URI.create("mem:///" + className.replace('.', '/') + kind.extension), kind) { + @Override + public OutputStream openOutputStream() { + return output.computeIfAbsent(className, name -> new ByteArrayOutputStream()); + } + }; + } + }; + List units = sources.entrySet().stream().map(source -> + new SimpleJavaFileObject(URI.create("string:///" + source.getKey().replace('.', '/') + ".java"), JavaFileObject.Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return source.getValue(); + } + }).collect(Collectors.toList()); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + List javacOptions = List.of("-classpath", classpath, "-nowarn", "-proc:none"); + if (!javac.getTask(null, memory, diagnostics, javacOptions, null, units).call()) { + throw new IllegalStateException("generated resolvers don't compile: " + diagnostics.getDiagnostics()); + } + + ClassLoader loader = new ClassLoader(Check.class.getClassLoader()) { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + ByteArrayOutputStream bytes = output.get(name); + if (bytes == null) { + throw new ClassNotFoundException(name); + } + return defineClass(name, bytes.toByteArray(), 0, bytes.size()); + } + }; + Map> classes = new HashMap<>(); + for (String name : sources.keySet()) { + classes.put(name, loader.loadClass(name)); + } + return classes; + } + + private static String stringArg(String[] args, String name) { + int i = List.of(args).indexOf(name); + return i >= 0 && i < args.length - 1 ? args[i + 1] : null; + } + + private static boolean flag(String[] args, String name) { + return List.of(args).contains(name); + } + + private static int intArg(String[] args, String name, int fallback) { + for (int i = 0; i < args.length - 1; i++) { + if (args[i].equals(name)) { + return Integer.parseInt(args[i + 1]); + } + } + return fallback; + } +} diff --git a/src/test/resources/returnvalue/Fixtures.java b/src/test/resources/returnvalue/Fixtures.java new file mode 100644 index 00000000..aea82b7d --- /dev/null +++ b/src/test/resources/returnvalue/Fixtures.java @@ -0,0 +1,113 @@ +package unwrapcheck; + +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +public final class Fixtures { + + public static volatile Object nextReturnValue; + + private Fixtures() { + } + + public static final class Payload { + private final String data; + + public Payload(String data) { + this.data = data; + } + + public String getData() { + return data; + } + } + + public static final class FutureItem implements Future { + private final String data; + + public FutureItem(String data) { + this.data = data; + } + + public String getData() { + return data; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public String get() { + return data; + } + + @Override + public String get(long timeout, TimeUnit unit) { + return data; + } + } + + public static final class Try { + private final T value; + private final String failure; + + private Try(T value, String failure) { + this.value = value; + this.failure = failure; + } + + public static Try success(T value) { + return new Try<>(value, null); + } + + public static Try failure(String message) { + return new Try<>(null, Objects.requireNonNull(message)); + } + + public T get() { + if (failure != null) { + throw new IllegalStateException(failure); + } + return value; + } + } + + public static final class Page { + private final List content; + + public Page(List content) { + this.content = content; + } + + public List getContent() { + return content; + } + } + + public static final class Later { + private final CompletableFuture future; + + public Later(CompletableFuture future) { + this.future = future; + } + + public CompletableFuture toFuture() { + return future; + } + } +} diff --git a/src/test/resources/returnvalue/known-findings.txt b/src/test/resources/returnvalue/known-findings.txt new file mode 100644 index 00000000..e69de29b