Skip to content

chore: Simplify shared Roslyn worker lifecycle ownership - #1629

Merged
hatayama merged 1 commit into
v3-betafrom
refactor/hatayama/extract-shared-roslyn-worker-lifecycle
Jul 8, 2026
Merged

hatayama merged 1 commit into
v3-betafrom
refactor/hatayama/extract-shared-roslyn-worker-lifecycle

Conversation

@hatayama

@hatayama hatayama commented Jul 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • The shared Roslyn worker now has one instance-owned session for its process, temporary directory, synchronization lock, and test seams.
  • The static host remains the stable orchestration facade without directly owning mutable worker state.

User Impact

  • Dynamic code compilation behavior, retry policy, shutdown timing, fallback behavior, and diagnostics are unchanged.
  • Worker lifecycle ownership is explicit, reducing the risk of future start, retry, and shutdown paths mutating related state under different locks.

Changes

  • Add SharedRoslynCompilerWorkerSession as the single owner of worker process and directory state, synchronization, startup, request I/O, compiler test delegation, and shutdown cleanup.
  • Keep the existing SharedRoslynCompilerWorkerHost entrypoints and test facades, delegating through one private ServiceValue.
  • Preserve the existing whole-compile lock scope with ExecuteLocked<T> and assert every lock-required session operation with Monitor.IsEntered.
  • Extend static facade guards so mutable state cannot move back into the host and the session cannot become a static service.
  • Preserve the currently orphaned directory-deleter test seam for behavior-equivalent extraction; its removal is tracked separately as R2-37.
  • Add a process-free test that verifies shutdown is idempotent before a worker starts. Real worker lifecycle EditMode tests remain intentionally excluded because PR fix: keep EditMode tests from freezing the editor #942 removed them to prevent Unity Test Runner freezes.

Verification

  • Confirmed the static facade guard was Red before extraction on the host's direct lock, request sender, process, and directory state.
  • dist/darwin-arm64/uloop compile --project-path <PROJECT_ROOT>: 0 errors, 0 warnings
  • SharedRoslynCompilerWorkerHostTests: 15 passed
  • ExternalCompilerPathResolverTests: 15 passed
  • ExternalCompilerMessageParserTests: 1 passed
  • StaticFacadeStateGuardTests: 20 passed
  • OnionAssemblyDependencyTests: 83 passed
  • Confirmed SharedRoslynCompilerWorkerSession has no dependency on SharedRoslynCompilerWorkerHost.
  • No wire-format or protocol-version change

Refs: R2-32 in the Unity CLI Loop refactoring ToDo.

Review in cubic

Move process, temporary-directory, synchronization, and test-seam ownership from the static host into one instance session. Keep host entrypoints and orchestration stable while source guards prevent mutable state from returning to the facade.
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Shared Roslyn compiler worker process lifecycle and I/O handling is extracted from SharedRoslynCompilerWorkerHost into a new internal SharedRoslynCompilerWorkerSession class. The host now delegates locking, startup, compile requests, output reading, directory tracking, and shutdown to the session. Tests and static-guard allowlists are updated accordingly.

Changes

Worker Session Extraction

Layer / File(s) Summary
New SharedRoslynCompilerWorkerSession class
Packages/.../SharedRoslynCompilerWorkerSession.cs
Adds a class encapsulating locked process lifecycle: liveness checks, startup, compile request sending, output reading, worker directory recording/cleanup, assembly compilation with test override hooks, graceful/forced shutdown, and lock-assertion.
Host refactored to delegate to session
Packages/.../SharedRoslynCompilerWorkerHost.cs
Host adds a ServiceValue field of the new session type and routes TryCompile, readiness checks, assembly building, process startup, compile request/response, directory recording, cancellation/retry shutdown, and test swap hooks through session *Locked methods; removes prior local implementations, the Debug alias, and shutdown-failure logging.
Tests and static-guard allowlist updates
Assets/Tests/Editor/DynamicCodeToolTests/SharedRoslynCompilerWorkerHostTests.cs, Assets/Tests/Editor/StaticFacadeStateGuardTests.cs
Adds a test verifying Shutdown is idempotent when the worker was never started, and extends MigratedFacadePaths/InstanceServicePaths allowlists to include the host and session files.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Host as SharedRoslynCompilerWorkerHost
  participant Session as SharedRoslynCompilerWorkerSession
  participant Process as Worker Process

  Host->>Session: ExecuteLocked(TryCompileWithRetries)
  Session->>Session: HasLiveProcessLocked()
  alt worker not ready
    Session->>Session: CompileWorkerAssemblyLocked()
    Session->>Process: StartProcessLocked(startInfo)
  end
  Session->>Process: SendCompileRequestLocked(requestFile)
  Session->>Process: GetOutputReaderLocked()
  Process-->>Session: response
  Session-->>Host: compile result
  Host->>Session: ShutdownProcessLocked() (on cancel/retry failure)
Loading

Possibly related PRs

  • hatayama/unity-cli-loop#901: Introduces SharedRoslynCompilerWorkerHost and its original tests, which this PR refactors to delegate lifecycle to the new session class.
  • hatayama/unity-cli-loop#1156: Removes SharedRoslynCompilerWorkerHostTests.cs entirely, conflicting with this PR's addition of a new test method to the same fixture.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the refactor that moves shared Roslyn worker lifecycle ownership into a session.
Description check ✅ Passed The description is clearly aligned with the refactor and its tests, so it passes the lenient relevance check.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/hatayama/extract-shared-roslyn-worker-lifecycle

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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SharedRoslynCompilerWorkerSession.cs`:
- Around line 100-127: The shutdown path in SharedRoslynCompilerWorkerSession
currently exits to the catch blocks on StandardInput failures before reaching
the Kill() fallback, which can leave the worker process orphaned after
_workerProcess is cleared. Refactor the quit/flush/wait logic in the worker
shutdown code so that any IOException, ObjectDisposedException, or
InvalidOperationException from writing
SharedRoslynCompilerWorkerProtocol.SharedCompilerWorkerQuitCommand still falls
through to the kill fallback when workerProcess.HasExited is false, and keep
LogWorkerShutdownFailure as the shared error reporting path.
- Around line 41-45: Dispose any stale cached worker before replacing it in
StartProcessLocked. When ProcessStartHelper.TryStart returns a new process,
check the existing _workerProcess and, if it is non-null and not live according
to HasLiveProcessLocked(), dispose it before assigning the new process handle.
Use the StartProcessLocked and HasLiveProcessLocked methods in
SharedRoslynCompilerWorkerSession to keep the cached process lifecycle correct.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c7f8c80e-ac21-432c-8b67-bf792fad4c0c

📥 Commits

Reviewing files that changed from the base of the PR and between e1eb989 and bca55f5.

⛔ Files ignored due to path filters (1)
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SharedRoslynCompilerWorkerSession.cs.meta is excluded by none and included by none
📒 Files selected for processing (4)
  • Assets/Tests/Editor/DynamicCodeToolTests/SharedRoslynCompilerWorkerHostTests.cs
  • Assets/Tests/Editor/StaticFacadeStateGuardTests.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SharedRoslynCompilerWorkerHost.cs
  • Packages/src/Editor/FirstPartyTools/ExecuteDynamicCode/DynamicCompilation/SharedRoslynCompilerWorkerSession.cs

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 5 files

You’re at about 93% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

@hatayama
hatayama merged commit 764021c into v3-beta Jul 8, 2026
10 checks passed
@hatayama
hatayama deleted the refactor/hatayama/extract-shared-roslyn-worker-lifecycle branch July 8, 2026 17:54
RyanXie123 pushed a commit to RyanXie123/unity-cli-loop that referenced this pull request Sep 22, 2026
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