Skip to content

Fix PSI environment thread safety — share single instance#9

Merged
ClankerGuru merged 1 commit intomainfrom
fix/psi-init-resilience
Apr 13, 2026
Merged

Fix PSI environment thread safety — share single instance#9
ClankerGuru merged 1 commit intomainfrom
fix/psi-init-resilience

Conversation

@ClankerGuru
Copy link
Copy Markdown
Owner

@ClankerGuru ClankerGuru commented Apr 13, 2026

Summary

  • When the Kotlin PSI environment fails to initialize (e.g. lateinit property module has not been initialized), it now logs one warning instead of failing every single module
  • Uses fail-once pattern: after first PSI init failure, all subsequent calls return empty results immediately
  • Prevents error spam on repos with Kotlin version mismatches across included builds

Test plan

  • ./gradlew build passes
  • Test on large repo that previously failed with per-module lateinit errors

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling for source file analysis with improved failure logging.
  • Refactor

    • Optimized resource management for environment initialization with graceful fallback behavior.

@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 6 minutes and 0 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 6 minutes and 0 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: 2291a9a8-a435-4ba7-9b3e-92864e6f5544

📥 Commits

Reviewing files that changed from the base of the PR and between 03f7512 and c8e6688.

📒 Files selected for processing (3)
  • src/main/kotlin/zone/clanker/gradle/srcx/analysis/SourceFileMetadata.kt
  • src/main/kotlin/zone/clanker/gradle/srcx/parse/PsiEnvironment.kt
  • src/main/kotlin/zone/clanker/gradle/srcx/task/ContextTask.kt
📝 Walkthrough

Walkthrough

The changes introduce a safer PSI environment initialization pattern by adding a createOrNull() factory method to PsiEnvironment with failure-cached initialization, while updating SourceFileMetadata.scanSources to use this method and gracefully handle unavailable environments.

Changes

Cohort / File(s) Summary
PSI Environment Factory
src/main/kotlin/zone/clanker/gradle/srcx/parse/PsiEnvironment.kt
Added companion object with createOrNull() factory method featuring failure-cached initialization using a static flag, wrapped error handling via runCatching, and Gradle warning logging on initialization failure.
Source File Analysis
src/main/kotlin/zone/clanker/gradle/srcx/analysis/SourceFileMetadata.kt
Updated scanSources to use PsiEnvironment.createOrNull() with graceful fallback to emptyList() on environment creation failure; refactored PSI resource scoping to use lambda receiver for PsiManager access.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 Whiskers twitch with delight!
A factory so clever, createOrNull() forever,
Catches failures with grace, logs them in place—
PSI flows safely, no crashes, hooray! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ⚠️ Warning The PR title claims to 'Fix PSI environment thread safety — share single instance', but the actual changes implement a fail-once pattern for initialization failures, not thread safety or instance sharing improvements. Update the title to reflect the actual change, such as 'Implement fail-once pattern for PSI initialization to prevent error spam' or 'Fix PSI init failure spamming every module'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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-init-resilience

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main/kotlin/zone/clanker/gradle/srcx/parse/PsiEnvironment.kt`:
- Around line 49-67: The createOrNull() method's fail-once logic is not
thread-safe because initFailed is a plain var; make the check-and-set atomic by
either replacing initFailed:Boolean with an AtomicBoolean and using
compareAndSet(false, true) to short-circuit after a failure, or wrap the read +
runCatching + onFailure write in a synchronized block so only one thread
performs initialization and sets initFailed when an exception occurs; update
references in createOrNull(), PsiEnvironment instantiation, and the onFailure
handler (logger.warn) accordingly so the fail-once behavior is preserved under
concurrent calls.
🪄 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: 22b4babe-9731-4d2f-8e76-6aac12350b7c

📥 Commits

Reviewing files that changed from the base of the PR and between 76e2e6c and 03f7512.

📒 Files selected for processing (2)
  • src/main/kotlin/zone/clanker/gradle/srcx/analysis/SourceFileMetadata.kt
  • src/main/kotlin/zone/clanker/gradle/srcx/parse/PsiEnvironment.kt

Comment thread src/main/kotlin/zone/clanker/gradle/srcx/parse/PsiEnvironment.kt Outdated
The IntelliJ platform's ApplicationManager is not thread-safe.
Creating multiple PsiEnvironments concurrently (from parallel
project analysis) corrupts internal state, leaving lateinit
properties uninitialized.

Fix: PsiEnvironment.shared() creates exactly one instance with
synchronized initialization. All scanSources/parseSourceFile calls
reuse it with synchronized access. Closed once at the end of
ContextTask.generate().

This fixes "lateinit property module has not been initialized"
errors on repos with multiple included builds.
@ClankerGuru ClankerGuru force-pushed the fix/psi-init-resilience branch from 03f7512 to c8e6688 Compare April 13, 2026 06:56
@ClankerGuru ClankerGuru changed the title Fix PSI init failure spamming every module Fix PSI environment thread safety — share single instance Apr 13, 2026
@ClankerGuru
Copy link
Copy Markdown
Owner Author

@coderabbitai Thanks for the thorough review! All addressed.

        (\(\
        ( -.-)    Here, you earned this.
        o_(")(")\
              \
               \  ___
                \/   \
                |  🥕 |
                |     |
                 \___/

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 13, 2026

@ClankerGuru Ha, I graciously accept the carrot! 🥕🐇

Great work on the fix — the fail-once pattern for PSI initialization is a clean, pragmatic approach. I'll do a fresh pass to confirm everything looks good!

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ClankerGuru ClankerGuru merged commit e1becde into main Apr 13, 2026
2 checks passed
@ClankerGuru ClankerGuru deleted the fix/psi-init-resilience branch April 13, 2026 07:05
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