Skip to content

Fix ClassCastException in mvnd when extension ClassRealm is reloaded - #308

Merged
cstamas merged 2 commits into
maveniverse:mainfrom
findepi:findepi/fix-classcastexception-in-mvnd-when-extension-classrealm-is-reloaded-a8c7c3
Jun 12, 2026
Merged

cstamas merged 2 commits into
maveniverse:mainfrom
findepi:findepi/fix-classcastexception-in-mvnd-when-extension-classrealm-is-reloaded-a8c7c3

Conversation

@findepi

@findepi findepi commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

mvnd (Maven Daemon) caches extension ClassRealms across builds. When the njord extension JAR is updated mid-session (e.g. parent POM upgrade bumps the version), mvnd creates a fresh ClassRealm for the new JAR but leaves Plexus singletons from the stale ClassRealm registered in the container. The stale NjordRepositoryConnectorFactory then tries to cast a Session object that was created by the new ClassRealm's lifecycle participant into its own ClassRealm's Session type, throwing:

ClassCastException: DefaultSession (loader ClassRealm @A)
    cannot be cast to Session (loader ClassRealm @B)

Root cause: both ClassRealms key their session data entry with the same String "eu.maveniverse.maven.njord.shared.Session", so the stale realm finds — and attempts to cast — the other realm's object.

Fix: use Session.class (the Class object) as the session data key instead of Session.class.getName() (a String). Class objects are ClassRealm-local: each realm has its own Session.class instance, so realms have independent, non-interfering session data slots. The instanceof guard makes both methods safe even if the entry was somehow populated by a foreign object.

Summary by CodeRabbit

  • Refactor

    • Improved internal session caching so stored session instances are handled more robustly and isolated, reducing accidental reuse of invalid cached values.
  • Bug Fix

    • Ensure session state is always cleared when a lifecycle ends (including on errors) to prevent stale session data from lingering in repository state.

mvnd (Maven Daemon) caches extension ClassRealms across builds.  When
the njord extension JAR is updated mid-session (e.g. parent POM upgrade
bumps the version), mvnd creates a fresh ClassRealm for the new JAR but
leaves Plexus singletons from the stale ClassRealm registered in the
container.  The stale NjordRepositoryConnectorFactory then tries to cast
a Session object that was created by the new ClassRealm's lifecycle
participant into its own ClassRealm's Session type, throwing:

  ClassCastException: DefaultSession (loader ClassRealm @A)
      cannot be cast to Session (loader ClassRealm @b)

Root cause: both ClassRealms key their session data entry with the same
String "eu.maveniverse.maven.njord.shared.Session", so the stale realm
finds — and attempts to cast — the other realm's object.

Fix: use Session.class (the Class *object*) as the session data key
instead of Session.class.getName() (a String).  Class objects are
ClassRealm-local: each realm has its own Session.class instance, so
realms have independent, non-interfering session data slots.
The instanceof guard makes both methods safe even if the entry was
somehow populated by a foreign object.
@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 01868b40-1af3-4516-854d-a99c07198ed9

📥 Commits

Reviewing files that changed from the base of the PR and between 334b214 and 0ba5e71.

📒 Files selected for processing (2)
  • core/src/main/java/eu/maveniverse/maven/njord/shared/NjordUtils.java
  • extension3/src/main/java/eu/maveniverse/maven/njord/extension3/NjordSessionLifecycleParticipant.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • extension3/src/main/java/eu/maveniverse/maven/njord/extension3/NjordSessionLifecycleParticipant.java
  • core/src/main/java/eu/maveniverse/maven/njord/shared/NjordUtils.java

📝 Walkthrough

Walkthrough

Update Njord session caching to use the class object Session.class as the RepositorySystemSession data key, adjust retrieval/removal to validate the stored type, and ensure the lifecycle participant clears the cached entry at session end.

Changes

Session Cache Key Migration

Layer / File(s) Summary
lazyInit: store using Session.class
core/src/main/java/eu/maveniverse/maven/njord/shared/NjordUtils.java
lazyInit checks and stores the Njord Session in RepositorySystemSession.getData() using Session.class as the key and only reuses the cached value if it is an actual Session instance.
mayGetNjordSession / removeNjordSession
core/src/main/java/eu/maveniverse/maven/njord/shared/NjordUtils.java
Retrieval reads RepositorySystemSession.getData() with Session.class and returns Optional only for Session instances; removal clears the same Session.class entry by setting it to null.
NjordSessionLifecycleParticipant cleanup
extension3/src/main/java/eu/maveniverse/maven/njord/extension3/NjordSessionLifecycleParticipant.java
afterSessionEnd now stores session.getRepositorySession() in a local variable, uses it to obtain the optional Njord session, and always calls NjordUtils.removeNjordSession(repositorySession) in a finally block.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit nudges keys with care,
From stringy names to classed affair,
It tucks each Session in a safe, typed bed,
And leaves a tidy trail when the lifecycle's fed. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically identifies the main problem being fixed: a ClassCastException that occurs in mvnd when extension ClassRealms are reloaded, which directly corresponds to the core changes in both modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cstamas

cstamas commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

Nice finding!
But what if on session close, we also remove the mapping from data?
Also, given I did same pattern in other places (ex mimir), this may need to be fixed there as well....
Thanks!

@cstamas

cstamas commented Jun 12, 2026

Copy link
Copy Markdown
Member

Hm, or make connector not singleton but a prototype?

@findepi

findepi commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

thank you @cstamas for your feedback!

But what if on session close, we also remove the mapping from data?

done

Hm, or make connector not singleton but a prototype?

i understand this is meant to be alternative solution to the same problem?
i really can't comment on that, i prefer to leave it up to your judgement.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@extension3/src/main/java/eu/maveniverse/maven/njord/extension3/NjordSessionLifecycleParticipant.java`:
- Line 117: The Njord session cache removal call
(NjordUtils.removeNjordSession(session.getRepositorySession())) must be executed
unconditionally in a finally block inside NjordSessionLifecycleParticipant so
cleanup runs even if publish/close throws; modify the method surrounding the
Optional<...> ns handling and the publish/close logic to move the
removeNjordSession(...) call into a finally block that always runs (regardless
of ns.isPresent()), ensuring stale Session instances cannot be reused by
lazyInit.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0b8adab4-0b61-4035-9d2f-8f44994db048

📥 Commits

Reviewing files that changed from the base of the PR and between c3d4992 and 334b214.

📒 Files selected for processing (2)
  • core/src/main/java/eu/maveniverse/maven/njord/shared/NjordUtils.java
  • extension3/src/main/java/eu/maveniverse/maven/njord/extension3/NjordSessionLifecycleParticipant.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/src/main/java/eu/maveniverse/maven/njord/shared/NjordUtils.java

@findepi
findepi force-pushed the findepi/fix-classcastexception-in-mvnd-when-extension-classrealm-is-reloaded-a8c7c3 branch from 334b214 to 0ba5e71 Compare June 12, 2026 14:26
@cstamas
cstamas merged commit dd97bff into maveniverse:main Jun 12, 2026
26 checks passed
@findepi
findepi deleted the findepi/fix-classcastexception-in-mvnd-when-extension-classrealm-is-reloaded-a8c7c3 branch June 12, 2026 17:00
@findepi

findepi commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for your review and merge, @cstamas !

@findepi

findepi commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

thanks for a quick release @cstamas !

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants