Skip to content

Commit 1bc988b

Browse files
authored
Merge pull request #946 from graphql-java-kickstart/agent-friendly-p5-return-value-test
Run the bounded return value unwrapping check in mvn verify
2 parents 851ffae + e85afc8 commit 1bc988b

6 files changed

Lines changed: 1001 additions & 0 deletions

File tree

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
---
2+
name: verify-return-value-unwrapping
3+
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.
4+
---
5+
6+
# Verify return value unwrapping
7+
8+
## The property
9+
10+
A user writes a resolver method whose return type nests containers, such as
11+
`CompletableFuture<List<Try<Payload>>>`. If the schema build accepts that method, then graphql-java must get
12+
exactly the value the method returned, with every container removed. Futures are waited on and generic wrappers go
13+
through their transformers. List order and nulls are kept. A failed future or a throwing transformer fails the field.
14+
A `Future` that isn't a `CompletionStage` fails the field with the "can't wait on" error.
15+
16+
When this breaks, a production query returns `CompletableFuture@1a2b[Completed normally]` as a string, or fails with
17+
"Expected source object to be an instance of 'Payload' but instead got 'CompletableFuture'". It only happens for the
18+
return types and values nobody wrote a test for.
19+
20+
## How the check works
21+
22+
`src/test/resources/returnvalue/Check.java` lists every return type built from up to `--depth` (default 3) of these containers around a leaf:
23+
24+
| Container | Value variants (the first one is the default) |
25+
|---|---|
26+
| `List` | 2 elements, `null`, empty |
27+
| `Page` (a `listCollectionWithTransformer` wrapper) | 2 elements, `null`, empty |
28+
| `CompletableFuture` | completes with the value, `null`, fails |
29+
| `Future` | a `CompletableFuture`, `null`, a completed `FutureTask` |
30+
| `Later` (a `withCompletionStageTransformer` wrapper whose transformer returns its `CompletableFuture`, like `Mono::toFuture`) | holds a future of the value, `null`, holds a failing future |
31+
| `Try` (a wrapper whose transformer returns the value or throws) | success, `null`, failure |
32+
| `DataFetcherResult` | the value, `null`, the value plus an error |
33+
| `Optional` | present, empty |
34+
35+
The leaf is `Payload` (an object type), `String`, or `Object` for a union `Item = Payload | FutureItem`. `FutureItem`
36+
implements `Future`, so only the declared type tells a leaf from a future. Each return type runs with an all-nullable
37+
and an all-non-null GraphQL type.
38+
39+
For each combination the check compiles a Java resolver class with that return type at runtime. It builds the schema
40+
through the public `SchemaParser` API, which rejects about a quarter of the combinations, such as `Optional` below the top
41+
level. For every accepted one it executes the query once for each value that makes at most `--budget` (default 2)
42+
non-default choices. When the return type holds futures, it runs each value three ways: futures already completed,
43+
and pending futures completed after the data fetcher returns, first-created first and last-created first.
44+
45+
The expected result is what graphql-java returns when a plain data fetcher on the same schema returns the plain value,
46+
or throws the failure. So graphql-java's own null handling and error format apply to both sides. When one value
47+
holds several failures, any one of them failing the field counts as correct.
48+
49+
`ReturnValueUnwrappingTest` compiles `Check.java` and `Fixtures.java` at test time and runs the check, so `mvn verify`
50+
runs it at the default bounds on every build. About 172,000 executions run in about 15 seconds.
51+
52+
## Run
53+
54+
From the root of the checkout or worktree you want to check:
55+
56+
```bash
57+
.claude/skills/verify-return-value-unwrapping/check.sh
58+
```
59+
60+
It prints the commit and the JDK, runs `mvn clean test -Dtest=ReturnValueUnwrappingTest` with the options below passed
61+
as `-Dunwrapping.args`, and prints the report. On a failure it also prints the path of the Maven log.
62+
63+
| Exit | Meaning |
64+
|---|---|
65+
| 0 | `PASS`, or `PASS apart from the known findings above` |
66+
| 1 | `FAIL`: a return type that isn't a known finding breaks the property |
67+
| 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 |
68+
| 3 | `STALE`: a known finding no longer fails. Delete its line from `known-findings.txt` |
69+
70+
Options: `--depth N`, `--budget N`, `--show N` (counterexamples printed, default 15), and `--rejected`, which lists
71+
every combination the schema build rejected, with the build's error. A depth below 3 can't build the `mustAccept`
72+
return types, so it ends in `MODEL ERROR`.
73+
74+
## Reading a counterexample
75+
76+
```
77+
public List<Future<Payload>> field() for field: [Payload] (21 failing executions, first shown)
78+
returns: List[CompletableFuture(Payload(v1)), FutureTask]
79+
futures complete before the data fetcher returns
80+
expected: {errors=[{message=Exception while fetching data (/field) : Resolver method '...' resolved to a java.util.concurrent.FutureTask, which graphql-java can't wait on. ...
81+
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', ...
82+
```
83+
84+
The first line is the resolver method and the field's GraphQL type. `returns` is the value the method returned.
85+
`Later(CompletableFuture(x))` means a `Later` whose transformer returns a `CompletableFuture` of `x`. Only the first
86+
failing value per return type is shown. Rerun with a higher `--show` to see more return types.
87+
88+
A real bug versus a modeling error:
89+
90+
- **Real bug.** `got` holds a container object (a future, `Optional`, `DataFetcherResult`, `Try`) as a value, an
91+
"Expected source object" error, a lost or reordered element, a missing error, or a blocked data fetcher. Report it with
92+
the counterexample. Don't change the check to make it pass.
93+
- **Real bug in the schema build.** `expected` is itself nonsense, such as `Payload` bound to the `DataFetcherResult`
94+
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
95+
type to the wrong class, both sides go wrong.
96+
- **Modeling error.** The check's own idea of the value is wrong. For example, a new container variant builds a value
97+
that its declared type doesn't allow, or the error message the check expects for a `FutureTask` (in `build`, case
98+
`FUTURE_TASK`) differs from a message the library changed on purpose. Confirm against the library's own tests in
99+
`src/test/kotlin/graphql/kickstart/tools/NestedGenericWrapperTest.kt` before you edit the check.
100+
- **`MODEL ERROR` about rejected return types.** A change made the build reject a return type in `mustAccept` in
101+
`Check.java`. That's either a regression in the build, which you report, or an intended change, after which you swap in
102+
another accepted return type of the same kind.
103+
104+
## Known findings
105+
106+
`src/test/resources/returnvalue/known-findings.txt` lists the return types that break the property at the sync commit, one per line as
107+
`<regex over the return type as the check prints it> # <what goes wrong>`. They still
108+
print as `KNOWN` with a counterexample on every run, and the check passes apart from them. A new break inside a known
109+
pattern is hidden, so after a change to the code a known finding covers, read its counterexample.
110+
111+
At the sync commit there are none. The check found two bugs when it was written, and both are fixed. One was a
112+
`DataFetcherResult` inside an `Optional` (#939). The other was a wrapper whose transformer returns a future, directly around
113+
a declared future (#938). A `withTransformer` registration keeps that #938 behavior, which is why `Later` is registered
114+
through `withCompletionStageTransformer`.
115+
116+
When a fix lands, the check exits 3. Delete the line then, so that a regression shows up as `FAIL`.
117+
118+
## What this does not cover
119+
120+
- Suspend functions, subscriptions and `Publisher`, arrays, and Kotlin-declared resolver methods. The generated resolvers
121+
are Java methods without parameters, so only `LightMethodFieldResolverDataFetcher` runs, not
122+
`MethodFieldResolverDataFetcher`.
123+
- Wrappers picked by a subclass of the value (`Box` and `SpecialBox` in `NestedGenericWrapperTest`), wrappers with a type
124+
argument index other than 0, custom `schemaWrapper`s other than the list one, transformers that return a `FutureTask`,
125+
and DataLoader futures.
126+
- Lists of more than 2 elements, more than 2 non-default choices per value, more than 3 containers, and completion
127+
orders other than the two listed. A pass says nothing beyond those bounds.
128+
- Which return types the schema build should reject. The check only exercises what the build accepts.
129+
130+
## Coverage and sync
131+
132+
Last confirmed to describe the code at commit `cd3233ca` (master, 2026-10-30). It covers:
133+
134+
| File | What |
135+
|---|---|
136+
| `src/main/kotlin/graphql/kickstart/tools/resolver/ReturnValueUnwrapper.kt` | all of it |
137+
| `src/main/kotlin/graphql/kickstart/tools/TypeClassMatcher.kt` | `PotentialMatch.unwrap`, `Unwrapped` |
138+
| `src/main/kotlin/graphql/kickstart/tools/GenericTypeResolver.kt` | `resolve`, `resolveTypeVariables` |
139+
| `src/main/kotlin/graphql/kickstart/tools/resolver/MethodFieldResolver.kt` | `createDataFetcher` (`valueClass`, the unwrapper), `returnType`, `returnValueMatch`, `LightMethodFieldResolverDataFetcher` |
140+
| `src/main/kotlin/graphql/kickstart/tools/SchemaParserOptions.kt` | `GenericWrapper` and the default wrappers in `build()` |
141+
142+
To see whether a change needs another look:
143+
144+
```bash
145+
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
146+
```
147+
148+
Move the sync commit forward only after you've read those changes and confirmed that the containers, variants and
149+
expected values in `Check.java` still describe them. For example, a new default wrapper or a new kind of unwrapping
150+
step needs a new `Container` with its variants and its plain value in `build`. After an intended change, rerun the check,
151+
and break the new code on purpose once in a scratch worktree to see the check fail before you trust its pass.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
checkout=$(git rev-parse --show-toplevel)
5+
log=$(mktemp "${TMPDIR:-/tmp}/verify-return-value-unwrapping.XXXXXX")
6+
7+
echo "checkout $checkout at $(git -C "$checkout" rev-parse --short HEAD)$(git -C "$checkout" diff --quiet HEAD -- src || echo ' plus uncommitted src changes')"
8+
java -version 2>&1 | head -1
9+
10+
if (cd "$checkout" && mvn -B -ntp clean test -Dtest=ReturnValueUnwrappingTest "-Dunwrapping.args=$*") > "$log" 2>&1; then
11+
sed -n '/Running .*ReturnValueUnwrappingTest/,/Tests run:/p' "$log" | sed -e '1d' -e '$d'
12+
rm "$log"
13+
exit 0
14+
fi
15+
16+
sed -n '/AssertionError: /,/^\tat /p' "$log" | sed -e '1s/.*AssertionError: //' -e '$d'
17+
echo "Maven log: $log"
18+
grep -q '^FAIL:' "$log" && exit 1
19+
grep -q 'MODEL ERROR:' "$log" && exit 2
20+
grep -q '^STALE:' "$log" && exit 3
21+
tail -40 "$log"
22+
echo "MODEL ERROR: the checkout didn't build"
23+
exit 2
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package graphql.kickstart.tools.returnvalue
2+
3+
import org.junit.Assert.fail
4+
import org.junit.Test
5+
import java.io.ByteArrayOutputStream
6+
import java.io.File
7+
import java.io.PrintStream
8+
import java.net.URLClassLoader
9+
import java.nio.file.Files
10+
import java.nio.file.Path
11+
import java.util.spi.ToolProvider
12+
13+
class ReturnValueUnwrappingTest {
14+
15+
@Test
16+
fun `every return type the schema build accepts reaches graphql-java unwrapped`() {
17+
val dir = Files.createTempDirectory("return-value-unwrapping")
18+
try {
19+
val classpath = listOfNotNull(System.getProperty("jdk.module.path"), System.getProperty("java.class.path"))
20+
.joinToString(File.pathSeparator)
21+
compile(classpath, dir, copy("Check.java", dir), copy("Fixtures.java", dir))
22+
23+
val args = System.getProperty("unwrapping.args", "").split(" ").filter { it.isNotBlank() } +
24+
listOf("--known", copy("known-findings.txt", dir).toString())
25+
val report = ByteArrayOutputStream()
26+
val passed = URLClassLoader(arrayOf(dir.toUri().toURL()), javaClass.classLoader).use { loader ->
27+
PrintStream(report, true, Charsets.UTF_8).use { out ->
28+
loader.loadClass("unwrapcheck.Check")
29+
.getMethod("check", Array<String>::class.java, String::class.java, PrintStream::class.java)
30+
.invoke(null, args.toTypedArray(), classpath + File.pathSeparator + dir, out) as Boolean
31+
}
32+
}
33+
if (!passed) {
34+
fail(report.toString(Charsets.UTF_8))
35+
}
36+
print(report.toString(Charsets.UTF_8))
37+
} finally {
38+
dir.toFile().deleteRecursively()
39+
}
40+
}
41+
42+
private fun copy(resource: String, dir: Path): Path {
43+
val target = dir.resolve(resource)
44+
javaClass.getResourceAsStream("/returnvalue/$resource")!!.use { Files.copy(it, target) }
45+
return target
46+
}
47+
48+
// java.util.spi.ToolProvider is in java.base, so this module needs no access to java.compiler
49+
private fun compile(classpath: String, dir: Path, vararg sources: Path) {
50+
val output = ByteArrayOutputStream()
51+
val javac = ToolProvider.findFirst("javac").orElseThrow()
52+
val status = PrintStream(output, true, Charsets.UTF_8).use { out ->
53+
javac.run(out, out, "-d", dir.toString(), "-classpath", classpath, "-nowarn", "-proc:none", *sources.map { it.toString() }.toTypedArray())
54+
}
55+
if (status != 0) {
56+
fail("MODEL ERROR: the check doesn't compile against this checkout:\n" + output.toString(Charsets.UTF_8))
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)