Skip to content

Reuse the active web request during async dispatch - #16226

Closed
codeconsole wants to merge 7 commits into
apache:8.0.xfrom
codeconsole:fix/async-request-lifecycle
Closed

codeconsole wants to merge 7 commits into
apache:8.0.xfrom
codeconsole:fix/async-request-lifecycle

Conversation

@codeconsole

Copy link
Copy Markdown
Contributor

A callback attached while the container is dispatching an async result must not start a second async cycle. Reuse the active AsyncGrailsWebRequest instead, preserving request decoration and leaving completed or inconsistent requests as visible failures.

Always clear the thread-bound GrailsWebRequest when a container has recycled the servlet request, and log the failed attribute cleanup at warning level.

Cover both paths through WebPromises and WebUtils public APIs.

A callback attached while the container is dispatching an async result must not start a second async cycle. Reuse the active AsyncGrailsWebRequest instead, preserving request decoration and leaving completed or inconsistent requests as visible failures.

Always clear the thread-bound GrailsWebRequest when a container has recycled the servlet request, and log the failed attribute cleanup at warning level.

Cover both paths through WebPromises and WebUtils public APIs.
Some classes here pollute static state that the rest of the fork would inherit,
so each is given a Test task of its own and excluded from `test`. A Test task
that is registered rather than the one the java plugin creates has neither
testClassesDirs nor classpath, which makes it NO-SOURCE: it reports success
having run nothing. Since `test` excludes those same classes, all forty ran in
no task at all.

This is older than it looks. b156214 rewrote `task x(type: Test)` as
`tasks.register(x, Test)` in November 2023, but both forms are NO-SOURCE -- the
java plugin wires source onto its own `test` task only -- so that commit
inherited the problem rather than causing it. The sharding plugin picks these
tasks up through tasks.withType(Test) and has been distributing empty tasks
across shards ever since.

Two things kept it quiet, and both are fixed here. The tasks ran nothing, and
grails-test-report matches phases by task name, so their results were invisible
to the aggregate reports even when they did run.

What ran for the first time in years mostly passed. Four did not:
RestfulControllerSpec and ResourceAnnotationRestfulControllerSpec assert that
save, update and patch render the create or edit view again for an instance with
errors, and built that instance with an empty title. Binding an empty string
stores null, and a persistent property is nullable by default in Grails 8, so
the instance was valid and the controller redirected instead. Their domains say
`title blank: false`, which meant required under the old default; it now says
`nullable: false` as well, which is what it always meant.
Same defect as the uber suite, and the same fifty tests' worth of consequence.
execIsolatedTests is registered rather than being the task the java plugin
creates, so it had neither testClassesDirs nor classpath and was NO-SOURCE:
success, having run nothing. `test` excludes those same classes, so they ran
nowhere.

There is a third reason here, on top of the two the uber suite had. Nothing
declared this task as work: `build` runs `check`, `check` ran `test`, and
execIsolatedTests was reachable only by naming it. The shard plugin collects it
through tasks.withType(Test), which is why the joint workflow reached it at all
and gradle.yml never did. `check` now depends on it.

All fifty pass.

JSONBindingTests and AutoParams*MarshallingTests are dropped from the list.
1e38f1b deleted all three of those classes in June 2013 and added nothing:
the feature went, so the tests went with it, and naming them here selects
nothing and excludes nothing. Every other entry that matches no class in this
project is left alone, because those tests were moved rather than deleted --
GSPResponseWriterSpec and pages/ext/jsp to grails-gsp, GroovyPageAttributesTests
to grails-taglib -- and whether their successors still need isolating is a
question about those projects, not this list.
apache#16192 added ~/.embedmongo to all seventeen dependency-jar cache steps across the
two workflows. Only two jobs ever run a mongod, and neither of them can write
that cache:

  - gradle.yml `build` is the only writer of the gradle-deps key, and it runs
    -PonlyCoreTests, which is in the onlyIf of mongodb-test-config.gradle: no
    MongoDB test task runs there, so it saved a directory that was never created.
  - mongodbFunctional and the joint workflow do download a mongod, but they reach
    the same key, and it exists by then, so their post-job save is skipped and
    the binary is discarded every run.

Meanwhile the other thirteen jobs restored up to 250MB of mongod they have no
use for, and the key -- hashFiles on dependencies.gradle -- threw the download
away on any dependency bump, which has nothing to do with what MongoDB ships.

~/.embedmongo now has its own step in the two jobs that run a server, keyed by
runner and MongoDB version and nothing else. It holds an immutable download from
fastdl.mongodb.org, the archive and the binary extracted out of it, and no
database: flapdoodle keeps data under a temp path it deletes on shutdown unless
embedded.mongodb.database-dir is set, and the only specifications that set it
point it at a @tempdir. So it belongs to no branch and survives a version bump.

The version in the key also settles the matrix: mongodb-version is ['7.0','8.0'],
and under one key the entry that missed first won and the other restored a
binary it could not use. There are no restore-keys, for the same reason.
The build_grails job served the test-example applications from a mongo:8 service
container on 27017, but named no version to the build, so the specifications that
bring their own server took the default in AbstractMongoGrailsExtension instead:
testcontainers started mongo:7.0.19 and the embedded server started V7_0. One job
was testing three MongoDB releases at once, and which one a failure belonged to
was not apparent from the job.

The service container is gone rather than aligned, because nothing needs it.
StartMongoGrailsIntegrationExtension probes localhost:27017 and starts a
container of its own when nothing answers, so the service was only ever an
optimisation; mongodbFunctional in gradle.yml runs the whole MongoDB suite with
`check -PonlyMongodbTests` and no service container, and is a required upstream
of publish. What is left brings its own server: a container for most
specifications, an embedded replica set for the four that need transactions.

-PmongodbContainerVersion=8.0 keeps those two on one release. This workflow
validates Grails against a Groovy snapshot rather than against a range of
MongoDB releases -- that coverage is the mongodb-version matrix in gradle.yml,
which runs 7.0 and 8.0 -- so the latest supported line is the one to run here.
jdaugherty added a commit that referenced this pull request Aug 25, 2026
Takes the decorator fix from Scott's #16226. A callback attached while the
container is dispatching an async result must not ask for a second async cycle;
AsyncWebRequestPromiseDecorator now looks the in-flight AsyncGrailsWebRequest up
unconditionally and reuses its context, so the promise is still decorated. A
request that is genuinely complete, or one whose async processing has started
without a web request to find, throws rather than being quietly tolerated.

This is what the revert on its own does not do. Reverting the lookup strategy
removes the silent skip but restores the failure the skip was hiding: the
refusal escaped and took down the response being delivered. Fixing the decorator
addresses the cause, so the strategy can stay as it was.

WebUtils.clearGrailsWebRequest is not taken from #16226 and still has no catch.
That disagreement is separate and narrower - whether a mid-request caller such
as UrlMappingUtils, which passes the same request to dispatcher.include on the
next line, should carry on after a logged warning or stop.

Also restores AsyncWebRequestPromiseDecoratorLookupStrategySpec, in Scott's
revised form: it now asserts the refusal is reported rather than swallowed.

Co-authored-by: Scott Murphy Heiberg <scott@alwaysvip.com>
jdaugherty added a commit that referenced this pull request Aug 25, 2026
The decorator fix taken from #16226 loosened the guard on running a task from
request.isAsyncStarted() to !asyncRequest.isAsyncComplete(), for every task.
The loosening is what lets a task join a cycle the container is delivering --
isAsyncStarted() is already false in that window although the request is still
live -- but applying it to the path that starts its own cycle widened when
those tasks run: between dispatch() or complete() and the container's
onComplete, a task that would previously have refused now binds a request the
container may be recycling.

The guard is now split by how the decorator got its cycle, recorded at
construction. A cycle started here must still be running, exactly as before; a
joined cycle is exempt for the delivery window joining exists for. The
completion check also moves ahead of touching the AsyncContext, whose
getRequest() throws its own message once the cycle has completed.

A task can still lose its cycle between the guard and the closure body -- that
race predates all of this and cannot be closed from here; the guard's job is
only not to widen it.

AsyncWebRequestPromiseDecoratorSpec pins all four corners: started-and-running
runs, started-and-dispatched refuses (this one fails against the single loosened
guard), joined-in-delivery runs, joined-then-completed refuses.
Restores the half of apache#16192's change to clearGrailsWebRequest that was right.
Removing the attribute and resetting RequestContextHolder were two sequential
statements, so a throw from the first skipped the second and left a finished
request bound to a pooled thread. The reset belongs in a finally: it is an
unconditional postcondition, and it must not depend on a servlet request still
being usable.

The catch is not restored. Its argument was that a recycled request has no
attribute left worth removing, which is true of exactly one of this method's
callers. GrailsAsyncContext clears a request that has completed;
UrlMappingUtils.includeForUrl calls clearGrailsWebRequest and then passes the
same request straight to dispatcher.include, GrailsWebRequestFilter clears
inside its own finally before the container recycles anything, and
spring-security's AnnotationFilterInvocationDefinition clears mid-chain. For
those three, and for anyone outside this repository calling a public static
method, an IllegalStateException means something is actually wrong.

Catching it would also make this method infer lifecycle state it has no
authority over -- reading one exception type as proof of a specific container
state -- and then decide that state is unremarkable. The finally makes no such
inference. It guarantees the thread is unbound and lets the failure travel.
The decorator fix taken from apache#16226 loosened the guard on running a task from
request.isAsyncStarted() to !asyncRequest.isAsyncComplete(), for every task.
The loosening is what lets a task join a cycle the container is delivering --
isAsyncStarted() is already false in that window although the request is still
live -- but applying it to the path that starts its own cycle widened when
those tasks run: between dispatch() or complete() and the container's
onComplete, a task that would previously have refused now binds a request the
container may be recycling.

The guard is now split by how the decorator got its cycle, recorded at
construction. A cycle started here must still be running, exactly as before; a
joined cycle is exempt for the delivery window joining exists for. The
completion check also moves ahead of touching the AsyncContext, whose
getRequest() throws its own message once the cycle has completed.

A task can still lose its cycle between the guard and the closure body -- that
race predates all of this and cannot be closed from here; the guard's job is
only not to widen it.

AsyncWebRequestPromiseDecoratorSpec pins all four corners: started-and-running
runs, started-and-dispatched refuses (this one fails against the single loosened
guard), joined-in-delivery runs, joined-then-completed refuses.
@codeconsole
codeconsole requested a review from jdaugherty August 25, 2026 20:40
@jdaugherty

Copy link
Copy Markdown
Contributor

@codeconsole since the original PR is what is referenced on the mailing list, I'd rather keep it in case people look for it later. Can we work off the original one?

@codecov

codecov Bot commented Aug 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.35294% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 54.1525%. Comparing base (27b6097) to head (e7d24d8).

Files with missing lines Patch % Lines
...s/web/async/AsyncWebRequestPromiseDecorator.groovy 81.2500% 1 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16226        +/-   ##
==================================================
+ Coverage     54.1129%   54.1525%   +0.0397%     
- Complexity      20301      20311        +10     
==================================================
  Files            2107       2107                
  Lines          101146     101131        -15     
  Branches        17922      17920         -2     
==================================================
+ Hits            54733      54765        +32     
+ Misses          38605      38555        -50     
- Partials         7808       7811         +3     
Files with missing lines Coverage Δ
...yncWebRequestPromiseDecoratorLookupStrategy.groovy 100.0000% <100.0000%> (+25.0000%) ⬆️
.../src/main/groovy/org/grails/web/util/WebUtils.java 33.7423% <ø> (+0.2057%) ⬆️
...s/web/async/AsyncWebRequestPromiseDecorator.groovy 75.6098% <81.2500%> (+55.6098%) ⬆️

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@testlens-app

testlens-app Bot commented Aug 25, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: e7d24d8
▶️ Tests: 80379 executed
⚪️ Checks: 92/92 completed


Learn more about TestLens at testlens.app/docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants