Skip to content

Improve hot path virtual-thread and codec performance - #15828

Merged
jdaugherty merged 4 commits into
8.0.xfrom
perf/vthread-static-compile-8.0.x
Sep 23, 2026
Merged

jdaugherty merged 4 commits into
8.0.xfrom
perf/vthread-static-compile-8.0.x

Conversation

@jamesfredley

@jamesfredley jamesfredley commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR makes two Grails 8 hot paths friendlier to the JDK 21 runtime without changing the public API surface:

  • Replaces GrailsHttpSession wrapper monitor synchronization with a private ReentrantLock.
  • Static-compiles grails-codecs-core codec extension helpers and removes dynamic self-dispatch inside the codec implementations.
  • Keeps existing Groovy extension method binary descriptors intact by preserving Object return types and the existing mutable HEXDIGITS property shape.

Motivation

Virtual-thread friendliness

GrailsHttpSession previously serialized wrapper access with synchronized (this). That object monitor can pin a virtual-thread carrier if the servlet container or request/session access blocks while the monitor is held. A private ReentrantLock preserves the wrapper-level serialization semantics while avoiding monitor pinning, and it also makes lazy session creation occur under the same lock as subsequent session access.

Codec hot-path static compilation

The codec extension methods are small, frequently used helpers. Static compilation removes runtime Groovy dispatch inside MD5, SHA-1, SHA-256, Base64, Hex, and shared digest conversion paths. The implementation still keeps the extension methods compatible for existing compiled callers by preserving the original public method descriptors.

Compatibility notes

  • decodeHex keeps the previous Groovy truth behavior for falsy targets by using Groovy's runtime truth conversion helper under @CompileStatic.
  • String, primitive byte arrays, wrapper byte arrays, number lists, and null/NullObject cases remain covered.
  • No new dependencies or user-facing configuration changes are introduced.

Review feedback addressed

  • Restored the old decodeHex Groovy truth guard behavior for falsy inputs after Copilot review feedback.
  • Added regression coverage for falsy values against the static extension implementation.

Verification

  • ./gradlew :grails-codecs-core:test --tests "org.grails.web.codecs.HexCodecTests" :grails-codecs-core:codeStyle --rerun-tasks
  • ./gradlew :grails-codecs-core:test :grails-codecs-core:codeStyle --rerun-tasks
  • ./gradlew :grails-codecs-core:test :grails-web-common:test --tests "grails.web.servlet.mvc.GrailsHttpSessionSpec" :grails-codecs-core:codeStyle :grails-web-common:codeStyle --rerun-tasks
  • ./gradlew clean aggregateViolations :grails-test-report:check --continue
    • Violation reports were clean: Checkstyle, CodeNarc, PMD, SpotBugs.
    • The full gate still hits pre-existing unrelated failures on clean origin/8.0.x: grails-validation:compileGroovy, grails-data-graphql-core:compileGroovy, and MongoDB/Testcontainers environment failures. The two compile failures reproduce in a separate clean origin/8.0.x worktree.

Review gate

  • Current full branch review gate passed for diff hash 8102545e609fd576dfc616e73c59e4c7da847dbf with both Oracle and Codex reviewers green.
  • Copilot follow-up commit review gate passed for staged diff hash fcb2c9b25edffd17c4910e79aa23047e3169e608 with both Oracle and Codex reviewers green.

Copilot AI review requested due to automatic review settings July 5, 2026 02:28

Copilot AI 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.

Pull request overview

This PR optimizes two hot paths in Grails 8: (1) GrailsHttpSession synchronization to be more virtual-thread friendly, and (2) common codec extension methods to reduce Groovy dynamic-dispatch overhead while keeping the public extension surface stable.

Changes:

  • Replace synchronized (this) session wrapper serialization with a private ReentrantLock and lock-protected lazy session creation.
  • Add a new spec asserting lazy servlet-session creation and correct delegation for attribute operations.
  • Static-compile and refactor codecs (Hex, Base64, MD5, SHA-1, SHA-256) to use direct helper calls and shared byte-conversion logic.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsHttpSession.java Switch wrapper synchronization to ReentrantLock and lock-protect lazy session creation/access.
grails-web-common/src/test/groovy/grails/web/servlet/mvc/GrailsHttpSessionSpec.groovy Add coverage for lazy session creation + delegation for attribute operations.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/DigestUtils.groovy Static-compile and centralize Object→byte[] conversion to support codec hot paths.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/HexCodecExtensionMethods.groovy Static-compile + rewrite encode/decode loops for performance; preserve HEXDIGITS shape.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/Base64CodecExtensionMethods.groovy Static-compile and route Byte[]/byte[] paths through shared byte conversion.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/MD5CodecExtensionMethods.groovy Static-compile and replace dynamic chaining with direct helper calls.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/MD5BytesCodecExtensionMethods.groovy Static-compile and keep digest behavior via DigestUtils.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1CodecExtensionMethods.groovy Static-compile and replace dynamic chaining with direct helper calls.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA1BytesCodecExtensionMethods.groovy Static-compile and keep digest behavior via DigestUtils.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256CodecExtensionMethods.groovy Static-compile and replace dynamic chaining with direct helper calls.
grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/SHA256BytesCodecExtensionMethods.groovy Static-compile and keep digest behavior via DigestUtils.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@bito-code-review

Copy link
Copy Markdown

The current implementation of decodeHex uses a restrictive guard (theTarget == null || theTarget instanceof NullObject || theTarget.toString().length() == 0) which deviates from the previous Groovy-truthiness check (if (!theTarget) return null). This change can cause exceptions or unexpected behavior for inputs that were previously considered falsy in Groovy, such as 0 or empty collections. To restore the original contract and ensure compatibility with Groovy-truthiness, the guard should be updated to use the !theTarget check.

grails-codecs-core/src/main/groovy/org/grails/plugins/codecs/HexCodecExtensionMethods.groovy

static Object decodeHex(Object theTarget) {
        if (!theTarget) return null

@jdaugherty jdaugherty 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.

I don't see anything major with this at first glance. I asked Fabled to take a look and the results are attached to the review.

The GrailsHttpSession lock conversion looks correct — the remaining synchronized (this) blocks are all in commented-out dead code, lazy session creation now happens under the same lock as access (an improvement over the old racy pattern), and the new spec covers the lazy-create/delegate path. The codec static compilation is a nice win too; my comments are mostly about a few places where the rewrite narrows the accepted input types compared to the old dynamic coercion, plus some test-convention and hot-loop nits.

@codecov

codecov Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.36937% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.4112%. Comparing base (3549462) to head (1cce663).
⚠️ Report is 24 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
...oovy/grails/web/servlet/mvc/GrailsHttpSession.java 58.8235% 21 Missing ⚠️
...ils/plugins/codecs/HexCodecExtensionMethods.groovy 35.2941% 8 Missing and 3 partials ⚠️
.../plugins/codecs/Base64CodecExtensionMethods.groovy 66.6667% 1 Missing ⚠️
...roovy/org/grails/plugins/codecs/DigestUtils.groovy 97.2222% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #15828        +/-   ##
==================================================
+ Coverage     57.3794%   57.4112%   +0.0318%     
- Complexity      22498      22539        +41     
==================================================
  Files            2129       2129                
  Lines          103776     103816        +40     
  Branches        18625      18638        +13     
==================================================
+ Hits            59546      59602        +56     
+ Misses          35967      35954        -13     
+ Partials         8263       8260         -3     
Files with missing lines Coverage Δ
...lugins/codecs/MD5BytesCodecExtensionMethods.groovy 75.0000% <ø> (ø)
...ils/plugins/codecs/MD5CodecExtensionMethods.groovy 100.0000% <100.0000%> (ø)
...ugins/codecs/SHA1BytesCodecExtensionMethods.groovy 75.0000% <ø> (ø)
...ls/plugins/codecs/SHA1CodecExtensionMethods.groovy 75.0000% <100.0000%> (ø)
...ins/codecs/SHA256BytesCodecExtensionMethods.groovy 75.0000% <ø> (ø)
.../plugins/codecs/SHA256CodecExtensionMethods.groovy 75.0000% <100.0000%> (ø)
.../plugins/codecs/Base64CodecExtensionMethods.groovy 60.0000% <66.6667%> (ø)
...roovy/org/grails/plugins/codecs/DigestUtils.groovy 92.1053% <97.2222%> (+33.7719%) ⬆️
...ils/plugins/codecs/HexCodecExtensionMethods.groovy 36.3636% <35.2941%> (+1.5810%) ⬆️
...oovy/grails/web/servlet/mvc/GrailsHttpSession.java 64.0625% <58.8235%> (+32.8125%) ⬆️

... and 7 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.

@jamesfredley

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed pass (and the Fabled review). These read as review-then-commit nits rather than blockers, and they're all reasonable - I'll take them:

  1. Narrowed element types in DigestUtils - restore the old Character / char[] tolerance with DefaultTypeTransformation.castToNumber(value).byteValue() (keeps the coercion while staying statically compiled). If we decide the narrowing is intentional instead, I'll add a line to the compatibility notes.
  2. protected vs @PackageScope - switch to @PackageScope so the package-access intent (for Base64CodecExtensionMethods / HexCodecExtensionMethods) is explicit rather than relying on protected's side effect.
  3. Iterable-target behavior change - handle Collection / Iterable in DigestUtils.toByteArray so a Set<Integer> / Iterator hex-encodes its elements instead of silently falling through to toString().getBytes(UTF_8) (the silent-wrong-output failure mode you flagged).
  4. Hot-loop nits - i >> 1 and str.length() >> 1 instead of intdiv (avoids boxing), plain str.length(), and drop the redundant null/NullObject checks (castToBoolean already returns false).
  5. MD5/SHA static dispatch - confirmed intentional (that's the point of removing dynamic dispatch); I'll note in the compatibility section that a runtime metaclass override of encodeAsMD5Bytes/SHA variants no longer changes the result.
  6. HexCodecTests - move to the extension-method form (''.decodeHex(), 0.decodeHex(), ...) per the test-via-public-API rule.
  7. testRoundtrip - enable it (add @Test) with byte-typed expectations so assertIterableEquals compares Byte to Byte.
  8. UTF_8 - make it an added method argument defaulted to StandardCharsets.UTF_8 in the Base64 methods.

I'll push these fixes. On the GrailsHttpSession lock conversion - glad that read correctly. Since this is COMMENTED (not blocked), let me know if you'd prefer I split the pure compatibility-note items from the code fixes.

@testlens-app

This comment has been minimized.

Use a ReentrantLock inside GrailsHttpSession so wrapper-level session access no longer pins virtual-thread carrier threads on the object monitor.

Static-compile the codecs-core extension helpers while preserving existing Groovy extension method descriptors.

Assisted-by: Hephaestus:openai/gpt-5.5 codex-review
Preserve the pre-existing Groovy truth guard under static compilation by using Groovy's runtime truth conversion helper.

Add Hex codec regression coverage for falsy inputs.

Assisted-by: Hephaestus:openai/gpt-5.5 codex-review
Fix Base64 charset handling, empty hex decoding, preserve DigestUtils
visibility, and document codec notes.

Assisted-by: Sisyphus:xai/grok-4.5 [gpt-coding]
Completes the review items accepted on the codec/virtual-thread pass and
documents the behavior changes that shipped with it.

- Drop the charset parameter from decodeBase64. It was declared but never
  read, so the overload silently ignored its argument. Base64 text is
  always ASCII, so the decode side has nothing to apply a charset to.
- Mark DigestUtils.toByteArray @PackageScope instead of protected, so the
  package-access intent is explicit rather than a side effect of protected
  on a public abstract class.
- Document that an empty CharSequence decodes to an empty byte array while
  other Groovy-falsy values decode to null, and cover the Grails code path
  with StringBuilder and GString receivers. A String receiver binds to
  Groovy's own String.decodeHex(), so the previous '' assertion never
  exercised this class.
- Document that the hexadecimal digest codecs no longer route through the
  metaclass, so replacing encodeAsMD5Bytes and friends at runtime does not
  change what they return.
- Cover the Iterator and primitive-array branches of toByteArray.
@jdaugherty
jdaugherty force-pushed the perf/vthread-static-compile-8.0.x branch from ad5d5c5 to 1cce663 Compare September 23, 2026 23:15
@jdaugherty
jdaugherty merged commit b49a48e into 8.0.x Sep 23, 2026
79 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in Apache Grails Sep 23, 2026
@jdaugherty
jdaugherty deleted the perf/vthread-static-compile-8.0.x branch September 23, 2026 23:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Grails 8 grails-core: Invoke Dynamic (Indy) Optimization Opportunities

4 participants