Fix project leak from tc report

From JetBrains/intellij-community · View interactive version

Fix project leak from tc report is an AI agent skill from the GitHub repository JetBrains/intellij-community. Fix TeamCity project-leak test failures.

How to use this skill

Skill file

<!-- Generated by community/.ai/render-guides.mjs; edit community/.agents/skills/fix-project-leak-from-tc-report/SKILL.md -->

Fix a `_LastInSuiteTest.testProjectLeak` from a TeamCity report

Phase 1 — identify the culprit test

The leaked Project name is the strongest signal. In ProjectRule() / heavy-project rules the project name defaults to the test class simple name. So:

If the project name is generic (light_temp_…), pick the first non-platform class from the retention chain (ProjectCodeStyleSettingsManager, a plugin service, a Mockito mock, …) and search callers/tests referencing it plus the plugin area.

Fallback ordering (in decreasing signal strength): heap Instance line → CI hashcode branch → retention-chain class names → the user.

Phase 2 — reproduce locally 10 times

_LastInSuiteTest.testProjectLeak is filtered out of pattern discovery (community/platform/testFramework/core/src/com/intellij/TestCaseLoader.java:177-178,375-377); its body runs via JUnit5TestSessionListener.testPlanExecutionFinished

(community/platform/testFramework/src/com/intellij/tests/JUnit5TestSessionListener.java:39-193), gated on UsefulTestCase.IS_UNDER_TEAMCITY == true, i.e. env TEAMCITY_VERSION != null.

To activate locally, set TEAMCITY_VERSION and point TEAMCITY_BUILD_PROPERTIES_FILE at a stub properties file with agent.persistent.cache and teamcity.build.tempDir (needed so TeamCityHelper.getPersistentCachePath in the wrapper doesn't crash).

Then run the bundled loop script — do not hand-roll 10 sequential tests.cmd calls in the harness:

"${CLAUDE_SKILL_DIR}/scripts/leak-loop.sh" \
  --module <test-module-iml-name> \
  --test  <test-FQN> \
  --runs  10 \
  --archive /tmp/<name>-leak-runs

leak-loop.sh sets the two env vars for you (auto-creating the stub properties file if missing), loops N times, copies each run's Heap dump is published to <path> file to $ARCHIVE/run-NN.hprof.zip, saves stdout to run-NN.output, and prints one boundary line per run so a Monitor can subscribe.

Fast-exit contract. If run 1 produces no heap dump (no leak line in the output), the script aborts with exit code 3 and does not queue the remaining runs. Treat this signal explicitly:

| Exit code | Meaning | Interpretation during Phase 2 |

|-----------|---------------------------------------------|--------------------------------------------------|

| 0 | All N runs finished; run 1 produced a leak. | Proceed to analysis. |

| 3 | Run 1 produced no heap dump; loop aborted. | Either the leak is not reproducible locally, or the leak-hunter didn't fire. Debug before continuing. |

If exit code is 3 in Phase 2, verify that the run's stdout contains an ideaTests.totalTimeMs line (comes from JUnit5TestSessionListener.testStatistics after the leak check) — if yes, testProjectLeak fired and found no leak (unreliable repro; check the test suite membership, ordering, and any co-located classes). If no, the listener didn't fire — recheck TEAMCITY_VERSION propagation.

Cold Bazel compile + JBR download makes run 1 take 4–5 minutes; subsequent runs are ~30–60 s each with warm caches.

Phase 3 — analyze every unique retention chain

After Phase 2, invoke:

"${CLAUDE_SKILL_DIR}/scripts/summarize-runs.sh" /tmp/<name>-leak-runs

It writes SUMMARY.md with a per-run table plus the set of unique retention-chain shapes (class-only, argument values stripped). This tells you whether all runs leaked the same way or you have multiple parallel bugs.

Then hand-write <archive-dir>/ANALYSIS.md — required before writing any fix — covering:

  1. What reproduced. Test FQN + module, N/N run ratio, list of unique retention chains.
  2. Each unique retention chain, both local and the one reported by CI (if different). Print the full via '<field>' path with class names, and label the chain (e.g. Chain L / Chain C).
  3. Root cause per chain. Locate the retaining code via ./community/tools/accio.cmd symbol <Name> and cite file:line-range.
  4. Recommended fix per chain — pick from the catalogue below.

Do not skip the CI-reported chain even if you only reproduced a different one locally. The leak checker reports one path per project; multiple retainers can coexist on the same leaked instance. Fixing only one usually promotes the next to be reported next time.

Phase 4 — apply fixes

MANDATORY first check — is the retaining class a Disposable project service?

Before you apply any pattern from this catalogue, answer this question about the class that ends up as a Disposer ROOT (or otherwise pins the Project):

Is the class both

  1. registered via <projectService> in a plugin descriptor or annotated @Service(Level.PROJECT) (equivalently @Service with a project-level scope inferred by the container), and
  2. a Disposable (implements Disposable directly or via a base class)?

If YES, then the service container itself already registers this instance into the Disposer tree and disposes it correctly. Specifically:

Consequences for the fix:

If NO (the class is not a Disposable project service, or it is manually instantiated / registered outside the standard service container path), fall through to the "Root cause first" section and pick a pattern.

Root cause first — fix disposal, not the reference

A Project reaches the leak-hunter because some object holds it. That object falls into one of three categories, and the correct fix depends on which:

(B1) is by far the more common case for a service that appears as a Disposer ROOT, and neither WeakReference on myProject nor flattening the child-Disposer registrations is a valid fix for it. See the two anti-patterns below.

Only reach for WeakReference after you have identified case (A) and confirmed the container legitimately outlives its contents.

Anti-pattern — `WeakReference` on a service's own `Project` field

Do not "fix" a project-service leak by wrapping the service's own myProject field in a WeakReference. Example of what NOT to do:

// BAD — hides the disposal bug, does not fix it.
private final WeakReference<Project> myProjectRef;
public MyService(Project project) { myProjectRef = new WeakReference<>(project); }
private Project project() { return Objects.requireNonNull(myProjectRef.get(), "disposed"); }

Why this is wrong: a project service must be disposed together with the project. If the retention chain shows a project service pinning its own Project, the service outlives the project. That is the actual bug. Weakening the field only masks the Project reference. The service instance itself is still leaked. TC will keep reporting a leak; the report just points somewhere else.

Correct approach for a service-in-the-Disposer-tree chain — diagnosis flow:

  1. Only if the service is NOT properly integrated with the container (manually instantiated by test / production code, custom registration path that bypasses ServiceInstanceInitializer, or a non-service Disposable that ended up as a Disposer ROOT), apply a structural registration fix. Options, in order:
  1. Only after these are exhausted and you have confirmed with a repro loop that the service genuinely cannot be disposed in time (an infrastructure bug that is out of scope for the ticket), consider surface-level containment — and prefer a test-side dispose in tearDown or an explicit unregistration hook over field-weakening.

Anti-pattern — flattening the Disposer tree by hoisting children to `project`

Do not "fix" a project-service leak by rewriting Disposer.register(this, child) in the service's constructor to Disposer.register(project, child) (or to any other higher-level parentDisposable). Example of what NOT to do:

// BAD — reduces Disposer tree height but does not fix the leak.
public DbPsiFacadeImpl(@NotNull Project project) {
  Disposer.register(project, new Alarm(SWING_THREAD, this)); // was: Disposer.register(this, ...)
  Disposer.register(project, project.getMessageBus().connect()); // was: connect(this)
  EP.addExtensionPointListener(project, listener, project); // was: parentDisposable = this
}

Symptom this often gets confused with: the retention chain terminates at ObjectTree.myObject2ParentNode with the service instance itself as a Disposer ROOT (e.g. ObjectNode.myObject → MyServiceImpl@..., ObjectTree.myObject2ParentNode → ..., (root) → ObjectTree, Path from that Disposable up to the Disposer ROOT: MyServiceImpl@... <- ROOT).

Why it's tempting: removing the Disposer.register(this, ...) calls in the constructor appears to "remove the ROOT node" (children no longer keep the service pinned via their parent-node backref) and a single local run of the leak-hunter can look clean.

Why it's wrong:

Correct alternative: treat the retention as a bug on the framework's disposal path, not in the service's constructor. Investigate the "MANDATORY first check" possibilities.

Chain families

Two chain families cover the vast majority of testProjectLeak failures. Match your observed chain to one of the patterns:

Pattern A — Mockito thread-local retention on the EDT

Signature: chain terminates in MockingProgressImpl.ongoingStubbing → Thread[AWT-EventQueue-…].threadLocals → IdeEventQueue (root). The retained argument array contains the leaked Project.

Root cause. Every mock invocation goes through Mockito's MockHandlerImpl.handle(...), which writes the current Invocation into a MockingProgress ThreadLocal and never clears it. Tests annotated @RunsInEdt run on the EDT, so this ThreadLocal accumulates on the EDT and outlives the test class.

Preferred fix. Replace mock<Foo>() + whenever(...) with a small hand-rolled fake. Example: FakeFileEditorProvider and FakeFileEditorProviderManager in community/android/apkanalyzer/testSrc/java/com/android/tools/idea/apk/viewer/ApkEditorTest.kt.

Fallback fix (when a fake is too much work — many abstract methods, awkward suspend signatures, etc.): hoist the mocks to class fields and reset them on the EDT after each test.

private val mgr = mock<FileEditorProviderManager>()
private val provider = mock<FileEditorProvider>()

@After
fun clearMockitoEdtState() {
  runInEdtAndWait {
    Mockito.reset(mgr, provider)          // clears MockingProgress ThreadLocal on this thread
  }
}

The Mockito.reset(...) route resolves the ThreadLocal on whichever thread it's called on, so the runInEdtAndWait { } wrapper is load-bearing.

Pattern B — Extension-point / message-bus listener with a strong `this` capture

Signature: chain contains ExtensionPointImpl.listeners (or MessageBusImpl.subscribers) → <listenerAdapter>.handle → a lambda / anonymous inner class whose arg$1 is the retaining service, whose field points at the leaked Project. Read references/pattern-b-listener-capture.md for the scope, the root cause and the fix.

Other patterns (rarer)

Phase 5 — verify

Rerun the same loop, targeting the same archive directory (or a fresh one). The loop's fast-exit is the desired positive signal here:

"${CLAUDE_SKILL_DIR}/scripts/leak-loop.sh" \
  --module <test-module-iml-name> \
  --test  <test-FQN> \
  --runs  3 \
  --archive /tmp/<name>-leak-verify

Interpretation of the verify run:

| Signal | Meaning |

|-------------------------------------------------------------------------------------------------|------------------------------------------------|

| Exit code 3 + first-run ideaTests.totalTimeMs line present + no Found a leaked instance. | Success: testProjectLeak ran and passed. |

| Exit code 0 + N/N runs still producing hprofs. | Fix did not close the leak. Reopen ANALYSIS.md and look for a chain you missed (or a wrong pattern). |

| Exit code 3 + no ideaTests.totalTimeMs in the stdout. | The leak-hunter didn't fire. Recheck TEAMCITY_VERSION propagation and the properties stub. |

For extra confidence do 2–3 additional plain tests.cmd invocations after the loop's success, greping the output:

export TEAMCITY_VERSION=local-leak-check TEAMCITY_BUILD_PROPERTIES_FILE=/tmp/tc-stub.properties
for i in 1 2 3; do
  ./tests.cmd --module <mod> --test <FQN> > /tmp/verify-$i.out 2>&1
  leak=$(./community/tools/rg.cmd -c 'Found a leaked instance' /tmp/verify-$i.out || echo 0)
  stats=$(./community/tools/rg.cmd -c 'ideaTests.totalTimeMs'   /tmp/verify-$i.out || echo 0)
  echo "run $i: leaked=$leak listener_ran=$stats"
done

Expected: every run prints leaked=0 listener_ran=1.

Reporting

Finish with a compact table like:

| | Before fix | After fix |

|----------------------------------------|---------------------------|--------------------|

| Found a leaked instance occurrences | N/N runs | 0/M runs |

| Heap dump is published occurrences | N/N runs | 0/M runs |

| Listener ran (ideaTests.totalTimeMs) | N/N | M/M |

| Test JVM exit code | 41 (leak) | 0 (clean) |

Attach the diff of the fixes (test-side + platform-side) and the path to the archived SUMMARY.md / ANALYSIS.md. This is the deliverable.

Guardrails

Key source references

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.