Skip to content

[#154] Unregister the published customizer class on release() - #155

Merged
vharseko merged 3 commits into
OpenIdentityPlatform:masterfrom
vharseko:issue-154-release-unregisters-customizer
Oct 7, 2026
Merged

vharseko merged 3 commits into
OpenIdentityPlatform:masterfrom
vharseko:issue-154-release-unregisters-customizer

Conversation

@vharseko

@vharseko vharseko commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Fixes #154

ScriptedConfiguration.release() dropped the published engine but left the class of its customizer script registered. The REST, CREST and SSH configurations register an ExpandoMetaClass on that class in createCustomizerScript (customizerClass.metaClass.customize << {…}). On Groovy 2.4.21 a registered metaclass keeps the class reachable, and with it the configuration's own GroovyClassLoader, every script it compiled, and the released configuration that owns the customize closure. So every facade dispose or configuration change of a REST, CREST or SSH connector leaked one loader. #132 covers only a customizer that fails.

Where Change
ScriptedConfiguration.initializeCustomizer() returns the customizer class (or null when there is none)
ScriptedConfiguration.getGroovyScriptEngine() keeps that class in publishedCustomizerClass, guarded by the configuration's monitor and set together with the published engine
ScriptedConfiguration.release() after the release closure has run, calls InvokerHelper.removeClass(publishedCustomizerClass) and clears the field. This happens in a finally, so it also runs when the release closure throws: OperationalContext.dispose() only logs that failure and never calls release() again. The REST, CREST and SQL overrides of release() all call super.release()

Tests (ScriptedConfigurationTest):

  • testReleaseUnregistersThePublishedCustomizerClass uses the stand-in from testFailedCustomizerClassIsUnregistered (now the shared helper registeringMetaClassOnCustomizer) with a customizer that succeeds. It checks that the metaclass is registered after getGroovyScriptEngine(), then calls release() and checks that ClassInfo.getClassInfo(clazz).getStrongMetaClass() is null. A second release() must leave a metaclass registered again by hand untouched, which pins the clearing of publishedCustomizerClass.
  • testThrowingReleaseClosureStillUnregistersTheCustomizerClass: a release closure that throws. The exception reaches the caller, and the class is still unregistered. A second release() must then leave a metaclass registered again by hand untouched, which pins the clearing of publishedCustomizerClass on the throw path.
  • testThrowingReleaseClosureStillDropsThePublishedEngine: after a release closure that throws, getGroovyScriptEngine() must return a new engine, which pins groovyScriptEngine = null on the throw path.
  • testCRESTReleaseUnregistersTheCustomizeMetaClass and testRESTReleaseUnregistersTheCustomizeMetaClass run the real customize {} DSL and the real release() overrides, which pins their super.release() call.

Mutation check: each mutant was run on its own against ScriptedConfigurationTest, and each was killed by its own test. The mutants were: no finally in release(); super.release() dropped from the CREST override; super.release() dropped from the REST override; publishedCustomizerClass = null deleted; publishedCustomizerClass = null moved out of the finally; groovyScriptEngine = null moved out of the finally.

Local run: mvn -pl OpenICF-groovy-connector,OpenICF-ssh-connector -am package. groovy-connector: 135 run, 0 failed, 42 skipped. ssh-connector: 97 run, 0 failed, 82 skipped. The skipped tests are the samples that need external systems (SQL/REST/CREST/Azure/ARM, Linux/Kerberos). SSHConfigurationCustomizerTest passed.

@vharseko
vharseko requested a review from maximthomas October 5, 2026 13:39
@vharseko vharseko added bug Something isn't working java Pull requests that update java code connector:groovy Groovy connector connector:ssh SSH connector resource-leak Memory, class-loader, thread or handle leaks tests Test additions or fixes labels Oct 5, 2026

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

praise: The unregistration is in the one place every REST, CREST and SSH dispose goes through.

  • publishedCustomizerClass is assigned under the monitor, next to groovyScriptEngine = engine, and only after initializeCustomizer() returned (ScriptedConfiguration.java:833), so a failed customizer never leaves a class for release() to remove.
  • The REST, CREST and SQL overrides reach it through super.release() (ScriptedRESTConfiguration.groovy:241, ScriptedCRESTConfiguration.groovy:146, ScriptedSQLConfiguration.groovy:165), and SSH inherits release() unchanged.
  • The new test asserts that the metaclass is registered before release() (ScriptedConfigurationTest.java:150-151), so its final assertion cannot pass vacuously.

issue (non-blocking): release() unregisters the customizer class only when the release closure returns normally.

OpenICF-groovy-connector/src/main/java/org/forgerock/openicf/misc/scriptedcommon/ScriptedConfiguration.java:665-675

clone.call() (:665) runs with no try/finally around it, so a release {} that throws (for example, closing a connection that is already broken) leaves release() before InvokerHelper.removeClass at :672. OperationalContext.dispose() (connector-framework-internal, OperationalContext.java:118-124) catches the exception, logs a WARN and does no other cleanup. On that path the ExpandoMetaClass stays registered, and the engine's loader, its scripts and the configuration stay pinned once per dispose, the #154 leak. This is not a regression: base also skipped groovyScriptEngine = null on a throw. Moving the cleanup into a finally keeps the order the PR describes.

            Closure c = getReleaseClosure();
            try {
                if (null != c) {
                    Closure clone = c.rehydrate(this, this, this);
                    clone.setResolveStrategy(Closure.DELEGATE_FIRST);
                    clone.call();
                    releaseClosure = null;
                }
            } finally {
                if (null != publishedCustomizerClass) {
                    // Drops the metaclass createCustomizerScript() may have put on the class,
                    // which would otherwise keep this engine's loader alive.
                    InvokerHelper.removeClass(publishedCustomizerClass);
                    publishedCustomizerClass = null;
                }
                groovyScriptEngine = null;
            }
            propertyBag.clear();
            loggerCache.clear();

Pin (not run): this test is red at head and green with the finally. It needs import groovy.lang.Closure;.

    @Test
    public void testThrowingReleaseClosureStillUnregistersTheCustomizerClass() {
        customizer = () -> {
        };
        final AtomicReference<Class> customizerClass = new AtomicReference<>();
        configuration = registeringMetaClassOnCustomizer(customizerClass);
        assertThat(configuration.getGroovyScriptEngine()).isNotNull();
        configuration.setReleaseClosure(new Closure<Void>(this) {
            public Void doCall() {
                throw new IllegalStateException("release failed");
            }
        });

        try {
            configuration.release();
            fail("The release closure failure must reach the caller");
        } catch (RuntimeException expected) {
            // the closure's failure
        }
        assertThat(ClassInfo.getClassInfo(customizerClass.get()).getStrongMetaClass()).isNull();
    }

suggestion (non-blocking): No test runs a real REST, CREST or SQL release() override, so the super.release() call that now does the unregistration is unpinned.

OpenICF-groovy-connector/src/test/java/org/forgerock/openicf/misc/scriptedcommon/ScriptedConfigurationTest.java:141-176, :190-203

testReleaseUnregistersThePublishedCustomizerClass calls release() only on the anonymous base-class stand-in. The one subclass test, testRetriedCRESTCustomizerDropsTheReleaseClosureOfTheFailedAttempt, asserts releaseClosureRan is false, and that holds with or without super.release(). If super.release() is dropped from ScriptedCRESTConfiguration.release() (:146), REST (:241) or SQL (:165), that connector's leak comes back and every test stays green. A sweep probe with the real ScriptedCRESTConfiguration and ScriptedRESTConfiguration and customize {} showed the strong metaclass set before release() and null after, so the code at head is right.

    @Test
    public void testCRESTReleaseUnregistersTheCustomizeMetaClass() throws Exception {
        Files.write(new File(scriptRoot, "Customizer.groovy").toPath(),
                "customize {\n}\n".getBytes(StandardCharsets.UTF_8));
        final AtomicReference<Class> customizerClass = new AtomicReference<>();
        configuration = new ScriptedCRESTConfiguration() {
            @Override
            protected Script createCustomizerScript(Class clazz, Binding binding) {
                customizerClass.set(clazz);
                return super.createCustomizerScript(clazz, binding);
            }
        };
        configuration.setScriptRoots(new String[] { scriptRoot.getAbsolutePath() });
        configuration.setCustomizerScriptFileName("Customizer.groovy");

        assertThat(configuration.getGroovyScriptEngine()).isNotNull();
        assertThat(ClassInfo.getClassInfo(customizerClass.get()).getStrongMetaClass()).isNotNull();
        configuration.release();
        assertThat(ClassInfo.getClassInfo(customizerClass.get()).getStrongMetaClass()).isNull();
    }

Pin (not run): it kills a mutant that drops super.release() from ScriptedCRESTConfiguration.release(). It also runs CREST's real customizerClass.metaClass.customize << registration instead of the stand-in.


suggestion (non-blocking): The publishedCustomizerClass = null clear in release() is not pinned.

OpenICF-groovy-connector/src/main/java/org/forgerock/openicf/misc/scriptedcommon/ScriptedConfiguration.java:673, test at ScriptedConfigurationTest.java:154

The only assertion after release() checks the registry slot, and removeClass at :672 empties it whether or not :673 runs. A mutant that deletes :673 passes ScriptedConfigurationTest (survives, 1/1 run). The impact is small: OperationalContext.dispose() drops its configuration reference before release(), so the line matters only while a released configuration stays reachable.

        configuration.release();
        assertThat(ClassInfo.getClassInfo(customizerClass.get()).getStrongMetaClass()).isNull();

        // A released configuration must not touch a class it no longer publishes.
        ExpandoMetaClass again = new ExpandoMetaClass(customizerClass.get(), false, true);
        again.initialize();
        GroovySystem.getMetaClassRegistry().setMetaClass(customizerClass.get(), again);
        configuration.release();
        assertThat(ClassInfo.getClassInfo(customizerClass.get()).getStrongMetaClass()).isNotNull();
        InvokerHelper.removeClass(customizerClass.get());

Pin (not run): with :673 deleted, the second release() unregisters the class again and the isNotNull() assertion fails. It needs import org.codehaus.groovy.runtime.InvokerHelper;.

@vharseko

vharseko commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

I took all three points in one commit, 3f79808.

issue: a release closure that throws skips the unregistration. In ScriptedConfiguration.release(), InvokerHelper.removeClass(publishedCustomizerClass), the field clear and groovyScriptEngine = null now run in a finally around the release closure. The order is the same as before: the closure runs first, then the class is unregistered. propertyBag.clear() and loggerCache.clear() stay after the block, as on base. testThrowingReleaseClosureStillUnregistersTheCustomizerClass is your pin. It also asserts that the metaclass is registered before release(), and that the closure's own exception reaches the caller.

suggestion: the real super.release() calls are unpinned. I added your CREST test, plus the same check for REST: testCRESTReleaseUnregistersTheCustomizeMetaClass and testRESTReleaseUnregistersTheCustomizeMetaClass, which share a helper. Both run the real customize {} DSL. I left SQL out, because its customizer registers no metaclass, so a test there would not cover #154. SSH inherits the base release(), which testReleaseUnregistersThePublishedCustomizerClass already covers.

suggestion: the publishedCustomizerClass = null clear is unpinned. Your second release() is now at the end of testReleaseUnregistersThePublishedCustomizerClass. I put its assertion in a try/finally that unregisters the hand-made metaclass, so it is not left in the global registry for the following tests.

Mutation check: each mutant was applied on its own, and ScriptedConfigurationTest was run against it.

Mutant Killed by
release() without the finally (previous head) testThrowingReleaseClosureStillUnregistersTheCustomizerClass
super.release() dropped from ScriptedCRESTConfiguration.release() testCRESTReleaseUnregistersTheCustomizeMetaClass
super.release() dropped from ScriptedRESTConfiguration.release() testRESTReleaseUnregistersTheCustomizeMetaClass
publishedCustomizerClass = null deleted from release() testReleaseUnregistersThePublishedCustomizerClass

Local run: mvn -pl OpenICF-groovy-connector,OpenICF-ssh-connector -am package. groovy-connector: 134 run, 0 failed, 42 skipped. ssh-connector: 97 run, 0 failed, 82 skipped. The skipped tests are the samples that need external systems.

Out of scope here, noted for a separate issue: when super.release() throws, the REST and CREST overrides also skip httpClient.close(), and SQL skips dataSource.close(), because their own cleanup runs after super.release() with no finally. That is not the metaclass leak, and base behaves the same.

@vharseko
vharseko requested a review from maximthomas October 6, 2026 12:31
release() dropped the engine but left the class of its customizer
registered. The REST, CREST and SSH configurations put an
ExpandoMetaClass on that class, which on Groovy 2.4.21 keeps the
class, its GroovyClassLoader with every compiled script, and the
released configuration alive: one loader leaked per facade dispose
or configuration change.

getGroovyScriptEngine() now keeps the customizer class of the
published engine, and release() removes it with
InvokerHelper.removeClass after the release closure has run.

Fixes OpenIdentityPlatform#154
release() ran the release closure with no try/finally around it, so a
release {} that throws skipped InvokerHelper.removeClass. The caller,
OperationalContext.dispose(), logs the failure and never calls release()
again, which left the loader pinned on that path. The unregistration and
groovyScriptEngine = null now run in a finally block.

New tests pin the closure that throws, the super.release() call in the
real CREST and REST release() overrides, and the clearing of
publishedCustomizerClass.
@vharseko
vharseko force-pushed the issue-154-release-unregisters-customizer branch from 3f79808 to ff4d1db Compare October 6, 2026 12:57
@vharseko

vharseko commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

#132 is merged (squashed as 027dcdf), so I rebased this branch onto master. It now carries only this PR's two commits:

Before After Commit
2b0233b 05c67ed Unregister the published customizer class on release()
3f79808 ff4d1db Unregister the customizer class even when the release closure throws

The content is unchanged. git range-diff shows both commits as identical, and the squash commit on master has the same diff as #132's four commits. That was the source of the conflict: the branch still carried #132's original commits. My previous reply's 3f79808 is now ff4d1db. I also removed the "Stacked on #132" note from the description.

Local run after the rebase: mvn -pl OpenICF-groovy-connector -am package -Dtest=ScriptedConfigurationTest, 8 run, 0 failed.

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

praise: The new finally covers the path that OperationalContext.dispose() never retries.

  • ScriptedConfiguration.release() (:663-680) now runs InvokerHelper.removeClass, the publishedCustomizerClass clear and groovyScriptEngine = null in a finally, so a release {} that throws no longer keeps the loader pinned.
  • testCRESTReleaseUnregistersTheCustomizeMetaClass and testRESTReleaseUnregistersTheCustomizeMetaClass use the real customize {} DSL and the real overrides. ScriptedConfigurationTest passes locally at ff4d1db: 8 run, 0 failed, 0 skipped.

issue (non-blocking): The REST, CREST and SQL release() overrides close httpClient / dataSource only when super.release() returns normally, so a release {} that throws still leaks them.

OpenICF-groovy-connector/src/main/groovy/org/forgerock/openicf/connectors/scriptedrest/ScriptedRESTConfiguration.groovy:239-246, scriptedcrest/ScriptedCRESTConfiguration.groovy:144-151, scriptedsql/ScriptedSQLConfiguration.groovy:163-170

Each override calls super.release() and then closes its client, with no try/finally. The base release() still rethrows the closure's exception after its own finally. OperationalContext.dispose() only logs that exception and never calls release() again. The result is a leak: the REST CloseableHttpClient pool and the SQL tomcat-jdbc pool stay open, and so does the CREST async client. The CREST client's started I/O reactor threads are a GC root, so that leak is permanent. This behaviour predates the PR, since these three files are unchanged on master. The reasoning this PR gives for its finally applies to these resources too. A follow-up to #154 is fine.

    @Override
    void release() {
        synchronized (this) {
            try {
                super.release()
            } finally {
                if (null != httpClient) {
                    httpClient.close();
                    httpClient = null;
                }
            }
        }
    }

Or: the same shape in ScriptedCRESTConfiguration, and with dataSource.close() in ScriptedSQLConfiguration.


suggestion (non-blocking): On the throw path, testThrowingReleaseClosureStillUnregistersTheCustomizerClass pins only removeClass. It does not pin publishedCustomizerClass = null or groovyScriptEngine = null, which this change also moved into the finally.

OpenICF-groovy-connector/src/test/java/org/forgerock/openicf/misc/scriptedcommon/ScriptedConfigurationTest.java:172-194, OpenICF-groovy-connector/src/main/java/org/forgerock/openicf/misc/scriptedcommon/ScriptedConfiguration.java:675, :678

After the failed release(), the test checks only the rethrown message and the strong metaclass. No test calls getGroovyScriptEngine() or a second release() after a release that throws. Moving either statement back out of the finally (so a throw skips it) would therefore still pass the whole class. This is traced by reading the tests; the mutants were not run. In production both mutants are close to equivalent, because the caller drops the configuration. The following, added after the catch, turns the field mutant red:

        configuration.setReleaseClosure(null);
        ExpandoMetaClass again = new ExpandoMetaClass(customizerClass.get(), false, true);
        again.initialize();
        GroovySystem.getMetaClassRegistry().setMetaClass(customizerClass.get(), again);
        try {
            configuration.release();
            assertThat(ClassInfo.getClassInfo(customizerClass.get()).getStrongMetaClass())
                    .as("metaclass registered after the failed release()").isNotNull();
        } finally {
            InvokerHelper.removeClass(customizerClass.get());
        }

Pin: a sibling test for the engine mutant. Capture engineBefore = configuration.getGroovyScriptEngine() in place of :178. After the failed release(), call setReleaseClosure(null) and assert that getGroovyScriptEngine() isNotSameAs(engineBefore). Then call release().

testThrowingReleaseClosureStillUnregistersTheCustomizerClass checked
only removeClass after a release closure that throws, so moving
publishedCustomizerClass = null or groovyScriptEngine = null back out
of the finally block left the class green. The test now releases again
and requires a metaclass registered by hand to survive, and
testThrowingReleaseClosureStillDropsThePublishedEngine requires a new
engine after the failed release().
@vharseko

vharseko commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

suggestion: the throw path pins only removeClass. I took it in a9afc2a. The two clears now have separate tests, because they cannot share one. Calling getGroovyScriptEngine() after the failed release() builds a new engine and overwrites publishedCustomizerClass with the new class, and that hides the field mutant.

  • testThrowingReleaseClosureStillUnregistersTheCustomizerClass gets your addition after the catch. It calls setReleaseClosure(null), registers the metaclass again by hand, and then calls a second release(). That release() must leave the metaclass registered. The assertion sits in a try/finally that unregisters the class, as in testReleaseUnregistersThePublishedCustomizerClass.
  • testThrowingReleaseClosureStillDropsThePublishedEngine is the sibling test you sketched. It keeps engineBefore, gets the exception from release(), calls setReleaseClosure(null), and asserts that getGroovyScriptEngine() isNotSameAs(engineBefore). A release() in a finally then unregisters the class of the new engine.

Mutation check: each mutant was applied on its own, and ScriptedConfigurationTest was run against it.

Mutant Killed by
publishedCustomizerClass = null moved out of the finally testThrowingReleaseClosureStillUnregistersTheCustomizerClass ("metaclass registered after the failed release()")
groovyScriptEngine = null moved out of the finally testThrowingReleaseClosureStillDropsThePublishedEngine

issue: the REST, CREST and SQL overrides skip httpClient.close() / dataSource.close() when super.release() throws. As noted in my earlier reply, this stays out of this PR. It is now #166, with your finally shape. The issue adds one point: a close() that throws inside that finally must not hide the closure's exception.

Local run: mvn -pl OpenICF-groovy-connector,OpenICF-ssh-connector -am package. groovy-connector: 135 run, 0 failed, 42 skipped. ssh-connector: 97 run, 0 failed, 82 skipped. The skipped tests are the samples that need external systems.

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

praise: a9afc2a pins both throw-path clears in ScriptedConfiguration.release(), each with its own test.

  • testThrowingReleaseClosureStillUnregistersTheCustomizerClass registers an ExpandoMetaClass by hand and calls release() a second time. ScriptedConfigurationTest.java:203 goes red when publishedCustomizerClass = null is moved out of the finally.
  • testThrowingReleaseClosureStillDropsThePublishedEngine checks that getGroovyScriptEngine() returns a new engine after the failed release(). ScriptedConfigurationTest.java:232 goes red when groovyScriptEngine = null is moved out of the finally.
  • Separate tests are the right call. Each assertion depends on only one of the two clears, so neither mutant can hide behind the other. At a9afc2a the class ran 9 tests with 0 failures, and build-maven passed on all 9 jobs.

@vharseko
vharseko merged commit 0dc965b into OpenIdentityPlatform:master Oct 7, 2026
15 checks passed
@vharseko
vharseko deleted the issue-154-release-unregisters-customizer branch October 7, 2026 08:34
vharseko added a commit that referenced this pull request Oct 7, 2026
… throws (#168)

Fixes #166

## Problem

`ScriptedRESTConfiguration`, `ScriptedCRESTConfiguration` and
`ScriptedSQLConfiguration` close their HTTP client or connection pool in
`release()` only when `super.release()` returns normally.
`ScriptedConfiguration.release()` rethrows the exception of the
connector's `release {}` closure, and `OperationalContext.dispose()`
only logs it and never calls `release()` again. On that path the REST
connection pool, the SQL tomcat-jdbc pool and the CREST async client
stay open. The started I/O reactor threads of the CREST client are a GC
root, so that leak is permanent.

Raised in the review of #155, follow-up to #154. The three files are
unchanged by #155, and this PR does not touch the files #155 changes.

## Change

- The three overrides close the resource in a `finally` around
`super.release()`.
- A failing `close()` is logged at WARN and the field is cleared either
way, so it cannot replace the release closure's exception.
- REST and CREST get a `private static final Log log`, as SQL already
has.

One behaviour change: when the release closure succeeds and only
`close()` fails, `release()` now logs the failure instead of throwing
it. Before, `OperationalContext.dispose()` logged it, so the outcome for
the caller is the same.

## Tests

New `ScriptedConfigurationReleaseTest`, a data provider over REST, CREST
and SQL (9 tests). Each test injects a stand-in client or pool that
counts its `close()` calls.

- A release closure that throws: the closure's exception reaches the
caller, the resource is closed once, and the field is `null`.
- The closure and `close()` both throw: the closure's exception reaches
the caller.
- Only `close()` throws: `release()` returns normally and the field is
`null`.

The stand-ins are hand-written rather than Mockito mocks because CI runs
JDK 11 to 26 and the class mocks of mockito-all 1.9.5 depend on an old
cglib.

- With the fix: 9 run, 0 failed. Full `OpenICF-groovy-connector` suite:
139 run, 0 failed, 42 skipped.
- With the three `release()` overrides reverted to master: all 9 fail.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working connector:groovy Groovy connector connector:ssh SSH connector java Pull requests that update java code resource-leak Memory, class-loader, thread or handle leaks tests Test additions or fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ScriptedConfiguration.release() leaves the published engine's customizer class registered, pinning one GroovyClassLoader per release

2 participants