Skip to content

Fix PsiEnvironment thread safety in SymbolExtractor#11

Merged
ClankerGuru merged 2 commits intomainfrom
fix/psi-thread-safety-symbol-extractor
Apr 13, 2026
Merged

Fix PsiEnvironment thread safety in SymbolExtractor#11
ClankerGuru merged 2 commits intomainfrom
fix/psi-thread-safety-symbol-extractor

Conversation

@ClankerGuru
Copy link
Copy Markdown
Owner

@ClankerGuru ClankerGuru commented Apr 13, 2026

Summary

  • extractSymbolsFromDirs and extractDependenciesFromBuildFile each created a new PsiEnvironment() per call. When ContextTask runs these in parallel across 4 threads via runParallelMapped, multiple threads simultaneously call KotlinCoreEnvironment.createForProduction(), racing on IntelliJ's global ApplicationManager singleton and leaving the internal lateinit var module uninitialized.
  • This caused every project to fail with: Analysis failed for '<module>': lateinit property module has not been initialized
  • Both methods now use PsiEnvironment.shared() with synchronized(env), matching the pattern already used by scanSources.

Test plan

  • ./gradlew build passes (detekt, ktlint, tests, kover)
  • Run srcx-context on a multi-module repo to verify analysis completes without lateinit errors

Summary by CodeRabbit

  • Refactor
    • Improved resource efficiency in symbol extraction by reusing shared environments instead of creating new instances.
    • Enhanced thread-safety with synchronized access to shared resources.

extractSymbolsFromDirs and extractDependenciesFromBuildFile each created
a new PsiEnvironment per call. When ContextTask runs these in parallel
across 4 threads, multiple threads simultaneously call
KotlinCoreEnvironment.createForProduction(), racing on IntelliJ's global
ApplicationManager singleton and leaving the internal lateinit module
uninitialized — crashing every project with "lateinit property module
has not been initialized".

Switch both methods to use PsiEnvironment.shared() with synchronized
access, matching the pattern already used by scanSources.
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 13, 2026

Warning

Rate limit exceeded

@ClankerGuru has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 52 minutes and 27 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 52 minutes and 27 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 88fd7bf5-bc87-4195-ab6e-c273744b666a

📥 Commits

Reviewing files that changed from the base of the PR and between e2fb3a7 and e3b8779.

📒 Files selected for processing (2)
  • src/main/kotlin/zone/clanker/gradle/srcx/parse/PsiEnvironment.kt
  • src/main/kotlin/zone/clanker/gradle/srcx/scan/SymbolExtractor.kt
📝 Walkthrough

Walkthrough

The SymbolExtractor refactored internal PSI resource management to reuse a shared PsiEnvironment instead of creating fresh instances. Early returns now occur when the shared environment is unavailable, and PSI operations are synchronized to coordinate access.

Changes

Cohort / File(s) Summary
PsiEnvironment Resource Reuse
src/main/kotlin/zone/clanker/gradle/srcx/scan/SymbolExtractor.kt
Refactored extractSymbolsFromDirs and extractDependenciesFromBuildFile to reuse shared PsiEnvironment instead of creating new instances; added thread-safe synchronization and early returns when shared environment is unavailable.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

🐰 A rabbit hops through shared burrows,
No need to dig a hole anew,
With synchronized safety locks in rows,
Resources dance in harmony's brew! 🔐

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing thread safety issues in SymbolExtractor by switching to a shared PsiEnvironment with synchronization.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/psi-thread-safety-symbol-extractor

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.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/kotlin/zone/clanker/gradle/srcx/scan/SymbolExtractor.kt (1)

291-294: Narrow the synchronized section to avoid lock contention on file I/O.

buildFile.readText() (Line 293) does not require PSI access; keeping it inside synchronized(env) serializes avoidable I/O across threads.

♻️ Proposed refactor
-        val env = PsiEnvironment.shared() ?: return emptyList()
-        return synchronized(env) {
-            val vf = LightVirtualFile(buildFile.name, KotlinFileType.INSTANCE, buildFile.readText())
+        val scriptText = buildFile.readText()
+        val env = PsiEnvironment.shared() ?: return emptyList()
+        return synchronized(env) {
+            val vf = LightVirtualFile(buildFile.name, KotlinFileType.INSTANCE, scriptText)
             val ktFile = env.psiManager.findFile(vf) as? KtFile ?: return@synchronized emptyList()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/kotlin/zone/clanker/gradle/srcx/scan/SymbolExtractor.kt` around
lines 291 - 294, Move file I/O out of the synchronized block: call
buildFile.readText() before entering synchronized(env) and pass the resulting
String into LightVirtualFile, so only PSI-dependent operations
(PsiEnvironment.shared(), env.psiManager.findFile(...), casting to KtFile)
remain inside synchronized(env); update references around LightVirtualFile,
buildFile.readText(), and the synchronized(env) block to reflect this narrower
synchronization.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/main/kotlin/zone/clanker/gradle/srcx/scan/SymbolExtractor.kt`:
- Around line 291-294: Move file I/O out of the synchronized block: call
buildFile.readText() before entering synchronized(env) and pass the resulting
String into LightVirtualFile, so only PSI-dependent operations
(PsiEnvironment.shared(), env.psiManager.findFile(...), casting to KtFile)
remain inside synchronized(env); update references around LightVirtualFile,
buildFile.readText(), and the synchronized(env) block to reflect this narrower
synchronization.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c742ba87-8327-49c9-b999-919561153bb2

📥 Commits

Reviewing files that changed from the base of the PR and between 3505266 and e2fb3a7.

📒 Files selected for processing (1)
  • src/main/kotlin/zone/clanker/gradle/srcx/scan/SymbolExtractor.kt

Pass the exception as the second argument to logger.warn/error in
handleAnalysisFailure, extractSymbolsFromDirs, and PsiEnvironment.shared
so Gradle prints the full stack trace instead of just the message.
@ClankerGuru ClankerGuru merged commit 3a1f363 into main Apr 13, 2026
2 checks passed
@ClankerGuru ClankerGuru deleted the fix/psi-thread-safety-symbol-extractor branch April 13, 2026 15:44
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.

1 participant