#14570·graal

Since Polyglot 24.2, unclosed `Context` referenced from its own guest heap is never collected

Author: JohnTortugoCreated Sep 30, 2026Updated Sep 30, 2026
Labelsfeature

GR-54300 (#10062) made PolyglotEngineImpl.contexts hold PolyglotContextImpl strongly (it used to hold ContextWeakReferences) and added the auto-close-on-GC mechanism that fires when the public Context becomes weakly reachable.

There is a case where the two don't compose: a host object that lives in the context's guest heap and holds a reference to its own Context. Think a Proxy stored in the JS global object that keeps the Context around so it can call back into JS. Then the public Context is strongly reachable from the engine, through the context itself:

PolyglotEngineImpl.contexts → PolyglotContextImpl → ... → JSGlobalObject → HostProxy → <host object>.context → Context → Context.receiver → same PolyglotContextImpl

The Context never becomes weakly reachable, ContextReference.clean() never runs, disposeContext() is never called, and the context plus everything under its realm stays alive as long as the engine does. On 24.1 and earlier the same object graph was an unrooted cycle and GC took it.

Yes, the Context Javadoc has always said you must call close() ("if the context is no longer needed, it is necessary to close it to ensure that all resources are freed", and on close(boolean): "A context cannot free all native resources allocated automatically. For this reason it is necessary to close contexts after use"), so anyone relying on GC was outside the contract on every version. Still, the changelog entry for GR-54300 only says contexts are now closed automatically when unreferenced, which reads like things got safer, and CloseOnGc.md lists what blocks automatic closure without mentioning this. A host object holding its context is the normal way to write a callback, so this isn't an exotic shape. I ran into it on a production GraalJS embedding that was stable on 21 and OOMed within hours on 25 (numbers at the end).

Reproducer

java
import java.lang.ref.WeakReference;
import org.graalvm.polyglot.*;
import org.graalvm.polyglot.proxy.ProxyExecutable;

public final class Minimal {
    static final class Holder implements ProxyExecutable {
        final Context context;                       // null in no-cycle mode
        Holder(Context c) { context = c; }
        public Object execute(Value... a) { return null; }
    }

    public static void main(String[] args) throws Exception {
        boolean cycle = args.length == 0 || !args[0].equals("no-cycle");
        try (Engine engine = Engine.newBuilder("js").option("engine.WarnInterpreterOnly", "false").build()) {
            @SuppressWarnings("unchecked") WeakReference<Context>[] refs = new WeakReference[10];
            for (int i = 0; i < refs.length; i++) refs[i] = create(engine, cycle);
            for (int i = 0; i < 10; i++) { System.gc(); Thread.sleep(100); }
            int live = 0; for (var r : refs) if (r.get() != null) live++;
            System.out.printf("mode=%s retained=%d/%d%n", cycle ? "cycle" : "no-cycle", live, refs.length);
        }
    }

    static WeakReference<Context> create(Engine engine, boolean cycle) {
        Context context = Context.newBuilder("js").engine(engine).build();
        context.eval("js", "x => { globalThis.keep = x; }").execute(new Holder(cycle ? context : null));
        return new WeakReference<>(context);      // never closed, nothing else holds it
    }
}

org.graalvm.polyglot:polyglot + js-community, JDK 21:

Polyglot cycle no-cycle
23.1.12 0/10 0/10
24.1.2 0/10 0/10
24.2.2 10/10 0/10
25.0.4.1 10/10 0/10

Same result on GraalVM CE 21.0.2 (collected) and CE 25.0.2 (retained) with the optimizing runtime, so it's not a fallback-runtime artifact.

With -Xmx256m and a loop that creates these contexts and drops them, 25.0.4.1 OOMs at iteration ~2850. 23.1.12 sits at ~14 MiB; I stopped it at 4000.

Path in a real heap dump

Polyglot 25.0.4.1, MAT, weak/soft/phantom excluded. MAT finds exactly one path to the Context and there is no application root in it:

com.oracle.truffle.polyglot.PolyglotEngineImpl.contexts            (GC root)
org.graalvm.collections.EconomicMapImpl.entries
java.lang.Object[] [i]
com.oracle.truffle.polyglot.PolyglotContextImpl.cachedThreadInfo   (*)
com.oracle.truffle.polyglot.PolyglotThreadInfo.fastThreadLocals
java.lang.Object[] [6]
com.oracle.truffle.js.runtime.JSRealm.globalObject
com.oracle.truffle.js.runtime.builtins.JSGlobalObject.extRef
java.lang.Object[] [n]
com.oracle.truffle.host.HostProxy.proxy
<application object>.context
org.graalvm.polyglot.Context.receiver
com.oracle.truffle.polyglot.PolyglotContextImpl                    (same object as above)

(*) cachedThreadInfo is just the shortest route MAT shows. PolyglotContextImpl.contexts[] → PolyglotLanguageContext.env → Env.context → JSRealm gets there too; nulling cachedThreadInfo via reflection frees nothing.

Dropping the Engine as well doesn't help: Context.engine keeps the public Engine reachable, so the EngineReference in Engine.ENGINES never gets cleaned either. Removing that set entry by reflection releases the whole thing, which is how I confirmed the root.

Production numbers

Same host, GraalJS, one shared engine, contexts pooled, host callbacks in the global scope, pools dropped on config refresh without close():

CE 21.0.12 CE 25.0.4.1
PolyglotContextImpl 2,297 18,157
PolyglotContextImpl$ContextWeakReference 2,297 0
retained set of all contexts 43 MB, Truffle bookkeeping only 22.7 GB, ~46% of the heap
per context 18.5 KiB 1.19 MiB
state 18,154 of 18,157 DEFAULT

The missing close() is an application bug and is being fixed there. The point of this issue is that the upgrade made it go from invisible to fatal with no warning in the release notes.

What I'd like to do

  1. Docs. Add the self-reference case to the eligibility list in CloseOnGc.md, and a note next to the GR-54300 changelog entry saying that contexts are now held strongly by the engine and unclosed contexts are no longer collected. I'll send the PR.
  2. Maybe an engine option that restores the weak registry (23.1 behavior) for embedders who'd rather have abandoned contexts collected without close() running. The code existed until 24.1. Worth discussing whether we want to offer that at all.
  3. Longer term, the real fix would be to make the impl weakly held again and keep only what close() needs alive (Cleaner-style). Language disposal would need its own cleaners. I haven't prototyped it.

Environment

  • Polyglot 23.1.12 / 24.1.2 / 24.2.2 / 25.0.4.1 on Corretto 21.0.11 (fallback runtime)
  • GraalVM CE 21.0.2+13.1 and 25.0.2+10.1 (optimizing runtime)
  • Production dumps: GraalVM CE 21.0.12.1+10.1 and 25.0.4.1+9.1 (internal builds), Linux x86_64
  • Reproducer runs on macOS aarch64