Skip to content

perf(execute_code): compile with the Editor's bundled Roslyn, out of process - #1499

Open
KamilDev wants to merge 1 commit into
CoplayDev:betafrom
KamilDev:perf/execute-code-bundled-csc
Open

KamilDev wants to merge 1 commit into
CoplayDev:betafrom
KamilDev:perf/execute-code-bundled-csc

Conversation

@KamilDev

@KamilDev KamilDev commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Description

The first execute_code after every domain reload takes ~9 s, and every later one ~1 s. Agents pay it after each script change, usually on the very next call: they recompile, then inspect with execute_code.

The cost is the in-process Microsoft.CodeAnalysis backend running on the Editor's Mono, which JIT-compiles Roslyn afresh in every domain. Measured on 6000.3.14f1 by timing each phase of the cold path right after a reload (driven through the CodeDom backend, so Roslyn itself stayed cold):

First execute_code after a reload, in-process Roslyn Time
Resolve the 266 loaded assembly paths 1 ms
Load Roslyn's types and initialise 0.5 s
MetadataReference.CreateFromFile × 266 0.2 s
First compile, against mscorlib only 7.6 s
Next compile, all 266 references 0.8 s

The first compile is as slow with one tiny reference, so the cost is JIT-compiling Roslyn, not reading metadata. A background warm-up after each reload wouldn't help the common case: refresh_unity returns right as the reload ends, so the next call would run into a warm-up that has barely started.

The Editor ships its own Roslyn for script compilation (Data/DotNetSdkRoslyn/csc.dll on Data/NetCoreRuntime/dotnet), precompiled for .NET, plus its compiler server (VBCSCompiler). With the same 266 references from the command line: 0.37 s per compile as a fresh process, 0.09 s through the warm server. The server is a separate process, so a domain reload doesn't touch it.

Type of Change

  • New feature (non-breaking change that adds functionality)

Changes Made

  • New csc backend (BundledCscCompiler in ExecuteCode.cs). It writes the wrapped snippet and a response file with the references (~300 -r: flags would overflow the command line), then runs dotnet csc.dll -noconfig -shared (-langversion:latest, 60 s timeout). It loads the DLL it writes the same way the other backends do, and maps compile errors to the snippet's lines (WrapperLineOffset). Work files go to a per-call temp folder that is deleted afterwards.
  • auto tries it first, then the in-process package, then CodeDom. It falls through only when the compiler couldn't run (not found, didn't start, timed out, exited without diagnostics), with a warning in the console. Compile errors are returned as they are. roslyn and codedom are unchanged when asked for.
  • Server: compiler accepts csc, and the tool and parameter descriptions say what each backend is and costs. The "Compiled in-memory — no script files created" line now says nothing is added to the project, since the work files go to the OS temp folder. website/docs/reference/tools/scripting_ext/execute_code.md was regenerated.

Measured live on 6000.3.14f1 (a Game14-sized project, 266 references), auto with this change:

Before (in-process Roslyn) After (csc)
First call right after refresh_unity(compile="request") 9.3–10.5 s 0.45 s
First call with no compiler server running yet 0.61 s
Later calls ~1.0 s 0.2–0.35 s
Compile error 0.4 s, Line 1: Invalid expression term ';'

(Wall time through the MCP round trip; a non-compiling call takes ~0.3 s on the same setup.)

Compatibility / Package Source

  • Unity version(s) tested: 6000.3.14f1. The bundled compiler is also present in 6000.3.9f1 and 2022.3.27f1 here; editors without it keep the current behaviour.
  • Package source used: file: (this branch's MCPForUnity) in a Unity 6 project
  • Resolved commit hash: n/a (file: package)

Testing/Screenshots/Recordings

  • Python tests (cd Server && uv run pytest tests/ -v): 1591 passed, 3 skipped
  • Unity EditMode tests: added Execute_CscBackend_CompilesAndRuns, Execute_CscBackend_CompilesModernSyntax (tuple, positional pattern, static local function, switch expression), Execute_CscBackend_CompileErrorReportsUserLine and Execute_Auto_PrefersBundledCsc. They Assume the bundled compiler is present. I couldn't run the test project locally (2021.3.45f2 isn't installed here), so I ran each new test's scenario and every existing ExecuteCodeTests snippet through ExecuteCode.HandleCommand in a 6000.3.14f1 project. All gave the asserted results, including the compile-cache check (the same snippet twice loads no second assembly). CI will be the first real run.
  • Package import/compile check (6000.3.14f1)

Documentation Updates

  • I have added/removed/modified tools or resources (execute_code's compiler option and description)
  • If yes, I have updated all documentation files using:
    • The LLM prompt at tools/UPDATE_DOCS_PROMPT.md (recommended)
    • Manual review of the generated changes (generate_docs_reference.py; it also rewrites manage_material.md and manage_texture.md, already out of date on beta, which I left out)

Related Issues

Relates to #1498 (same goal: agents shouldn't wait on top of a refresh that has already finished)

Summary by CodeRabbit

  • New Features
    • Added a bundled compiler option for executing C# code, including support for modern syntax and clear compilation diagnostics.
    • Automatic compiler selection now tries the bundled compiler first, then falls back to other available compilers.
    • Compiler startup or timeout failures can fall back to another backend.
  • Documentation
    • Clarified compiler choices and fallback behavior. Compiled work files are stored in the operating system’s temporary folder.

…process

The first execute_code after every domain reload took ~9 s, every later one ~1 s. The cost is the in-process Microsoft.CodeAnalysis backend running on the Editor's Mono, which JIT-compiles Roslyn afresh in each domain: measured on 6000.3, its first compile takes 7.6 s even against mscorlib alone, then ~0.8 s. A reload throws that away, so agents pay it after each script change, usually on the very next call.

The Editor ships its own Roslyn for script compilation (Data/DotNetSdkRoslyn/csc.dll on Data/NetCoreRuntime/dotnet, precompiled for .NET). A new `csc` backend runs it out of process through its compiler server (-shared, VBCSCompiler), with references in a response file, and loads the DLL it writes. The server is a separate process, so a domain reload doesn't touch it. With the same 266 references, the first call after a reload now takes 0.45 s, 0.6 s when the server isn't running yet, and ~0.2-0.3 s after that. It takes the latest C# without the NuGet install.

`auto` tries it first, then the in-process package, then CodeDom. It falls through only when the compiler couldn't run (not found, didn't start, timed out, exited without diagnostics). Compile errors are returned as they are, mapped to the snippet's lines like the other backends. `roslyn` and `codedom` are unchanged when asked for.
@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: dc123c70-a511-40a4-8513-5c03518f6627
Commits

Reviewing files that changed from the base of the PR and between ed4e205 and 15413c6.

Files selected for processing: 4
  • MCPForUnity/Editor/Tools/ExecuteCode.cs
  • Server/src/services/tools/execute_code.py
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs
  • website/docs/reference/tools/scripting_ext/execute_code.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Walkthrough

The execute-code tool adds an Editor-bundled Roslyn compiler option. The auto choice tries this backend before in-process Roslyn. Server parameter descriptions, tests, and reference documentation include the new option and selection order.

Changes: Compiler support

Layer / File(s) Summary
Bundled compiler execution
MCPForUnity/Editor/Tools/ExecuteCode.cs
Adds a backend that locates the Editor’s dotnet runtime and csc.dll, compiles temporary source and reference files with a 60-second timeout, parses diagnostics, and loads successful output assemblies.
Compiler selection and validation
MCPForUnity/Editor/Tools/ExecuteCode.cs, Server/src/services/tools/execute_code.py, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ExecuteCodeTests.cs, website/docs/reference/tools/scripting_ext/execute_code.md
Adds explicit csc selection and tries the bundled compiler first in auto mode. Updates the server parameter and reference documentation. Adds tests for execution, modern syntax, line-numbered errors, and auto selection.

Priority: Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant ExecuteCode
  participant BundledCscCompiler
  participant CscProcess
  ExecuteCode->>BundledCscCompiler: Compile source with bundled csc
  BundledCscCompiler->>CscProcess: Start compiler with timeout
  CscProcess-->>BundledCscCompiler: Return diagnostics and output assembly
  BundledCscCompiler->>BundledCscCompiler: Parse diagnostics or load assembly
Loading

Suggested reviewers: scriptwonder, kpkhxlgy0

Merge Risk: Minimal · up to 15413

The new compiler option appears ready to merge after normal checks; no concrete issue requiring a code change was found.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 3 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: using the Unity Editor's bundled Roslyn compiler out of process for execute_code. It is concise and specific.
Description check Passed The description follows the repository template and explains the motivation, implementation, fallback behavior, compatibility, testing, documentation updates, and related issue. It clearly notes that …
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.
Full details: Description check

Explanation

The description follows the repository template and explains the motivation, implementation, fallback behavior, compatibility, testing, documentation updates, and related issue. It clearly notes that Unity EditMode tests were added but not run locally.

Full details: Docstring Coverage

Explanation

Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 3 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
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.

2 participants