Skip to content

Revert 16192 async changes, fix mongo cache, and fix tests that weren't running - #16223

Merged
jdaugherty merged 10 commits into
8.0.xfrom
revert/16192-async-changes
Aug 25, 2026
Merged

jdaugherty merged 10 commits into
8.0.xfrom
revert/16192-async-changes

Conversation

@jdaugherty

Copy link
Copy Markdown
Contributor

Per https://lists.apache.org/thread/y8f8oc3nvdjs2d67ytbs4717l4rk5lmw I'm reverting the async changes. While doing so, I also discovered that tests weren't running in the uber suite (and were broken due to the nullable default changes). Finally, I've fixed the mongo cache to be separate / based on the mongo version.

Restores AsyncWebRequestPromiseDecoratorLookupStrategy and
WebUtils.clearGrailsWebRequest to their state before #16192, and drops the
specification added with them.

The changes treated a symptom. A promise callback attached to a request the
container will not start a second asynchronous cycle on was failing the
response, and the fix caught that refusal, returned no decorators and logged at
debug. The request that reached that point is one whose data was not cleaned up
correctly; the contract now says a promise may silently run undecorated, with
nothing in the response or at any visible log level to say it happened. The
tests pass because the failure is quiet, not because the cause is gone.

The IllegalStateException swallowed in clearGrailsWebRequest is the same
symptom on the teardown side: a task cleaning up after a request the container
has already recycled.

The embedded MongoDB replica set work from #16192 is kept.
#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.
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.
@jdaugherty
jdaugherty force-pushed the revert/16192-async-changes branch from 2ce5fad to d9d9d64 Compare August 25, 2026 15:33
@jdaugherty

Copy link
Copy Markdown
Contributor Author

Here are my notes on this change:

Why the async changes are a -1

AsyncWebRequestPromiseDecoratorLookupStrategy caught the IllegalStateException the container
throws when asked to start a second async cycle, returned no decorators, and logged at debug.
WebUtils.clearGrailsWebRequest swallowed the same exception on the teardown side. Both are the
same symptom: an async task operating on a request the container has already recycled — i.e. data
that was not cleaned up correctly.

The result is a changed contract. A promise may now run undecorated with nothing in the response and
nothing at any visible log level to say so. The tests pass because the failure is quiet, not because
the cause is gone. Reverted: the two classes and the spec added with them, restored byte-for-byte to
their pre-merge state.

Two CI problems in the same PR

The ~/.embedmongo cache never worked. It was added to all 17 dependency-jar cache steps across
both workflows, but nothing that can write that cache ever downloads a mongod. gradle.yml's
build job is the only actions/cache/save writer, and it runs -PonlyCoreTests, which is in the
onlyIf of mongodb-test-config.gradle — no MongoDB task runs there. mongodbFunctional and the
joint workflow do download a mongod, but they use plain actions/cache@v4, which only saves on a
primary-key miss; the key already exists by then, so the binary was discarded every run. Meanwhile
13 unrelated jobs restored up to 250MB they have no use for, and the hashFiles(dependencies.gradle)
key threw the download away on every dependency bump.

Now it has its own step in only the two jobs that run a server, keyed embedmongo-<os>-<version>,
no branch and no hash. The version in the key also settles the matrix — under one key the entry that
missed first won and the other restored a binary it couldn't use.

The joint workflow was testing three MongoDB releases at once. It served the example apps from a
mongo:8 service container but named no version to the build, so testcontainers used the 7.0.19
default and the embedded server used V7_0. The service container is now gone rather than aligned:
StartMongoGrailsIntegrationExtension probes localhost:27017 and starts its own container when
nothing answers, so it was only ever an optimisation — and mongodbFunctional already runs the whole
MongoDB suite with no service container at all, as a required upstream of publish.
-PmongodbContainerVersion=8.0 now pins testcontainers and the embedded server to one release.

90 tests were running in no task at all

Reviving this turned up something bigger. Classes that pollute static state get a Test task of
their own and are excluded from test. A Test task that is registered has neither
testClassesDirs nor classpath — the java plugin wires those onto its own test task only — so
it is NO-SOURCE: it reports success having run nothing. Combined with the test exclusion, the
classes ran nowhere.

Affected: the five isolatedTestPatterns tasks in grails-test-suite-uber (40 tests) and
execIsolatedTests in grails-test-suite-web (50 tests).

This is older than it looks. b156214b99 (Nov 2023) rewrote task x(type: Test) as
tasks.register(x, Test), but both forms are NO-SOURCE — I verified them side by side in a
throwaway project — and Gradle was 7.6.3 on both sides of that commit. It inherited the problem
rather than causing it. TestTaskShardingPlugin collects these through tasks.withType(Test), so
CI has been distributing empty tasks across shards.

Three things kept it quiet, all fixed:

  1. the tasks ran nothing;
  2. grails-test-report matches phases by exact task name, so results were invisible to the aggregate
    reports even when they did run;
  3. in the web suite, nothing declared execIsolatedTests as work — build → check → test only,
    so it was reachable just by naming it. check now depends on it.

The fix is additive in both modules: two properties per task, one check dependency, and the task
names registered in the report. No task is removed.

What the revived tests found

34 of 40 in the uber suite passed. Four failed, in RestfulControllerSpec and
ResourceAnnotationRestfulControllerSpec: both assert that save/update/patch re-render the
create or edit view for an instance with errors, and both build that instance with an empty
title.

This is fallout from our intentional Grails 8 change making persistent properties nullable by
default (DefaultConstraintEvaluator.applyDefaultNullableConstraint). Binding an empty string
stores null, blank never fires on a null, so the instance was valid and the controller
redirected. The domains said title blank: false, which meant required under the old default; they
now say nullable: false as well, which is what they always meant. These tests were never updated
when we changed the default because they were dark — nothing flagged them.

Dead entries: only the ones that were deleted, not the ones that moved

Several isolated-test patterns name classes this repo no longer has. They fall into two groups, and
only the first is touched.

Deleted outright. JSONBindingTests and AutoParams*MarshallingTests are dropped from the web
suite's list. 1e38f1b5ea (June 2013) removed all three of those classes — 335 deletions, zero
additions — because the params auto-marshalling feature went away. There is no successor, so naming
them selects nothing and excludes nothing.

Moved, and rewritten under new names. Everything else stays exactly as it is, patterns and tasks
alike:

  • GSPResponseWriterSpec and **/pages/ext/jsp/* moved out in 6b0cf3817a (Apr 2017). The JSP
    tests are back in the monorepo as org.grails.gsp.jsp.* (8 classes) in grails-gsp/plugin.
  • GroovyPageAttributesTests now lives in grails-gsp/grails-taglib.
  • GrailsDomainBinderTests, ComponentValidationTests and HibernateMappingUniqueConstraintTests
    moved out in ac96f5d5a0 (Mar 2013) and were rewritten as the
    org.grails.orm.hibernate.cfg.domainbinding.** *BinderSpec suite plus the UniqueConstraint* /
    EmbeddedWithValidationException specs in grails-data-hibernate5/7.
  • DefaultGrailsControllerClassSpec lives in grails-core, where it runs and passes today.

grails-test-suite-persistence is therefore untouched, including testGrailsDomainBinder and
testIsolatedPersistentOne.

Deliberately left alone: GSP and Hibernate

Those moved tests came back into the monorepo when their repos were merged in, but without the
isolation they had here
— grails-gsp/plugin and grails-data-hibernate5/7 have no isolated test
tasks at all.

I have not touched either. Whether the original pollution concern still applies is a separate
question — the Hibernate binder has been decomposed since, and those specs pass today in a shared
fork — and it shouldn't ride along on a revert. Raising it here so it isn't lost.

@jdaugherty

Copy link
Copy Markdown
Contributor Author

Note: there are ~90 tests that haven't run since 2023 now as a result of these changes. Also, one o fthe reasons the groovy jointworkflow was flaky is because it was running tests that no other project was. @jamesfredley @matrei if we can get this merged, we can restage the M6

@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.1594%. Comparing base (27b6097) to head (cd1988f).
⚠️ Report is 2 commits behind head on 8.0.x.

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     #16223        +/-   ##
==================================================
+ Coverage     54.1129%   54.1594%   +0.0465%     
- Complexity      20301      20318        +17     
==================================================
  Files            2107       2107                
  Lines          101146     101133        -13     
  Branches        17922      17920         -2     
==================================================
+ Hits            54733      54773        +40     
+ Misses          38605      38553        -52     
+ Partials         7808       7807         -1     
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.

@codeconsole
codeconsole self-requested a review August 25, 2026 18:48

@codeconsole codeconsole left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WebUtils.clearGrailsWebRequest: fundamentally correct

Before #16192, this method did:

  1. Remove an attribute from the servlet request.
  2. Reset the thread-local RequestContextHolder.

If step 1 threw because the container had recycled the request, step 2 never ran. That left a completed request attached to a pooled thread.

Putting RequestContextHolder.resetRequestAttributes() in a finally block is correct defensive cleanup. Even if an earlier lifecycle bug caused the timing, cleanup of a thread-local must not depend on successful access to a potentially expired servlet request.

Catching the failure from removeAttribute is also reasonable: once the request is recycled, there is no meaningful attribute left for Grails to remove. This change prevents real thread-local contamination rather than merely hiding an error.

@codeconsole
codeconsole force-pushed the revert/16192-async-changes branch from 154b816 to d9d9d64 Compare August 25, 2026 19:17
Restores the half of #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.
@jdaugherty

Copy link
Copy Markdown
Contributor Author

Putting RequestContextHolder.resetRequestAttributes() in a finally block is correct defensive cleanup. Even if an earlier lifecycle bug caused the timing, cleanup of a thread-local must not depend on successful access to a potentially expired servlet request.

Agreed, and you've convinced me — that half is now kept. 49b0bc9 puts the reset back in a finally. You're right that it's an unconditional postcondition and must not depend on the servlet request still being reachable.

Catching the failure from removeAttribute is also reasonable: once the request is recycled, there is no meaningful attribute left for Grails to remove.

This is the half I still disagree with, for two reasons.

It generalises from one call site. "Once the request is recycled" describes exactly one of this method's four callers:

Caller State of the request when it is called
GrailsAsyncContext:71 completed — the case the change was written for
UrlMappingUtils:398 alive — clears, then immediately dispatcher.include(request, …)
GrailsWebRequestFilter:92 alive — inside its own finally, before the container recycles
spring-security AnnotationFilterInvocationDefinition:141 alive — mid filter chain

UrlMappingUtils is the clearest: it clears the web request and hands that same request to dispatcher.include on the very next line. An IllegalStateException there isn't a recycled request, it's a bug — and the catch swallows it immediately before the request gets used again. clearGrailsWebRequest is public API, so this extends to callers outside the repo as well.

It puts state inference in a method with no authority over that state. clearGrailsWebRequest is a static utility told to clear two locations. With the catch it reads one exception type as proof of a particular container lifecycle state, then decides that state is unremarkable. IllegalStateException out of getRequest()/removeAttribute isn't a unique signal for "recycled" — anything else throwing it in that path gets reclassified as expected. The finally makes no inference at all, which is exactly why it's the right half and the catch isn't.

So the method is now try/finally with no catch: the thread is unbound either way, and a request that can't be reached is reported to the caller that owns the lifecycle instead of being absorbed here. Two tests in WebUtilsTests cover both halves — the thread is unbound when the request can't be reached, and the failure still propagates. Removing the finally fails the first.

On the promise decorator, I'd still like it reverted. Worth noting your own analysis in #16219 rules it out as the cause of the AsyncPromiseSpec timeouts — two of the four occurrences predate it by three and a half weeks, one of them on 8.0.x. So the catch there isn't fixing that flake; it's making a promise run undecorated with nothing at any visible log level to say so. If there's a case it does fix, I'd rather see it fixed at the lifecycle that leaves a request in that state.

jdaugherty and others added 2 commits August 25, 2026 16:13
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>
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.
@jdaugherty

Copy link
Copy Markdown
Contributor Author

Update: I've taken the decorator fix from #16226 into this PR rather than leaving the plain revert — it addresses the cause (a callback attached during dispatch reuses the active AsyncGrailsWebRequest instead of asking for a second cycle), which is what the revert alone couldn't do. 2be110a, credited to @codeconsole, including both of the new WebPromisesSpec features and the revised lookup-strategy spec asserting the refusal is reported rather than swallowed.

One adjustment on top, in bc41fa9. The fix changed the guard on running a decorated task from request.isAsyncStarted() to !asyncRequest.isAsyncComplete() — for every task. Those two differ in a real window: isAsyncStarted() goes false the moment the cycle is dispatched or completed, while isAsyncComplete() only flips when the container's onComplete listener fires. The loosening is exactly what the reuse path needs — during delivery, isAsyncStarted() is already false although the request is still live — but applied to the path that starts its own cycle, it widened when tasks run: between dispatch()/complete() and onComplete, a task that would previously have refused now bound a request the container may be recycling.

So the guard is now split by how the decorator got its cycle, recorded at construction:

The completion check also moved ahead of asyncContext.request: a completed AsyncContext throws its own message from getRequest(), which would have preempted the intended one.

AsyncWebRequestPromiseDecoratorSpec pins all four corners — started-and-running runs, started-and-dispatched refuses, joined-in-delivery runs, joined-then-completed refuses. The started-and-dispatched feature fails against the single loosened guard (verified by removing the split and re-running), so the restored semantics are load-bearing, not decorative. Both #16226 WebPromisesSpec features still pass, so the reuse behaviour is intact.

One honest caveat: a joined cycle can still complete while the task body is executing. That race predates #16192 — the original code had the same check-then-run shape — and can't be closed from the decorator; the guard's job here is only not to widen it.

With this, the only remaining difference from #16226 is WebUtils.clearGrailsWebRequest — try/finally with the failure propagating, versus WARN-and-continue — per the discussion above.

@matrei matrei mentioned this pull request Aug 25, 2026

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did some optional test cleanup in #16228

@testlens-app

testlens-app Bot commented Aug 25, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: cd1988f
▶️ Tests: 80396 executed
⚪️ Checks: 92/92 completed


Learn more about TestLens at testlens.app/docs.

@jdaugherty
jdaugherty merged commit c985acb into 8.0.x Aug 25, 2026
94 of 95 checks passed
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.

4 participants