Skip to content

perf: discover tools and resources via TypeCache instead of scanning every assembly - #1358

Closed
ananttheant wants to merge 2 commits into
CoplayDev:betafrom
ananttheant:perf/typecache-command-discovery
Closed

ananttheant wants to merge 2 commits into
CoplayDev:betafrom
ananttheant:perf/typecache-command-discovery

Conversation

@ananttheant

@ananttheant ananttheant commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

CommandRegistry.AutoDiscoverCommands walks every type of every loaded assembly and then runs two full attribute-matching passes over that list, once per domain reload. ToolDiscoveryService.DiscoverAllTools is worse: it queries TypeCache first and then runs the same exhaustive AppDomain walk anyway — unconditionally, merging and de-duplicating the two results — so the fast path never actually saved anything.

ResourceDiscoveryService already trusts TypeCache alone, so this brings the other two in line with it.

Measured in this repo's own TestProjects/UnityMCPTests on Unity 2022.3.62f1 — 193 non-dynamic assemblies, 44,195 types, averaged over 5 runs after warm-up:

Path Time Types found
TypeCache 0.01 ms 54
Exhaustive assembly walk 310.63 ms 54

Both find exactly the same 54 types, which is the important part: this is a pure cost reduction, not a change in what gets discovered. That is 310 ms per domain reload in a near-empty project; the multi-second figure in #1336 comes from real projects carrying far more assemblies.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Refactoring (no functional changes)
  • Test update

Changes Made

  • CommandRegistry.AutoDiscoverCommands reads tools and resources from TypeCache. The old assembly walk moves into a GetAllLoadedTypes() helper, reached only when the index returns nothing at all for this domain.
  • ToolDiscoveryService.DiscoverAllTools runs the AppDomain scan only when TypeCache came back empty, instead of always running it and merging.
  • New CommandRegistry.ShouldFallBackToExhaustiveScan(int, int) pure predicate expressing that rule, following the existing ShouldAbandonBusyPort / ShouldKeepWaitingForReady pattern, plus an EditMode test covering all four combinations.
  • The AssetImportWorker guard from AssetImportWorker crash in CommandRegistry.AutoDiscoverCommands during domain reload #1134 is untouched and still short-circuits before any scanning.

The one behavioural trade-off worth your call: the old code always merged the exhaustive scan in, so a type that TypeCache somehow missed while other types resolved would still have been found. Now a non-empty index is treated as authoritative. I chose this because it keeps a safety net for the "index not ready" case the original comments describe while removing the cost from the normal path — but if you would rather always merge, or gate the fallback differently (say, per-attribute rather than on the combined count), that is a small change to ShouldFallBackToExhaustiveScan and its call site.

Compatibility / Package Source

  • Unity version(s) tested: 2022.3.62f1 (full EditMode suite + benchmark)
  • Package source used: file: (local clone, branch perf/typecache-command-discovery off beta)
  • Resolved commit hash from Packages/packages-lock.json: n/a (file reference)

TypeCache is UnityEditor API available well below this package's 2021.3 floor, so no version gating is needed.

Testing/Screenshots/Recordings

  • Python tests — not applicable, no Python-side changes
  • Unity EditMode tests
  • Unity PlayMode tests — not applicable, editor-only services
  • Package import/compile check

Full EditMode suite on 2022.3.62f1: 1121 passed, 0 failed (66 pre-existing ignores). The existing CommandRegistryTests.AutoDiscovery_RegistersAllBuiltInTools and ToolDiscoveryServiceTests are the real regression guard here — they assert the built-in tools still resolve, and they pass unchanged.

Documentation Updates

  • I have added/removed/modified tools or resources — no tool or resource surface changed

Related Issues

Closes #1336

Additional Notes

The benchmark above came from a throwaway test I did not commit; it timed both strategies in the same editor session and asserted their results matched. Happy to add it as a permanent [Explicit] test if that is useful to you, though wall-clock assertions in CI tend to be flaky, which is why I left it out.

Summary by CodeRabbit

  • Performance Improvements
    • Improved tool, command, and resource discovery speed in the Unity Editor by prioritizing indexed discovery results.
    • Reduced unnecessary scanning of loaded assemblies during setup and refresh operations.
  • Reliability
    • Added a fallback scan when indexed discovery finds no tools or resources.
    • Improved handling of assemblies that cannot be inspected, helping discovery complete more reliably.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Team

Run ID: 2ca188a1-209a-425c-b241-95c96a3d30c0

📥 Commits

Reviewing files that changed from the base of the PR and between db7eb72 and 4d01462.

📒 Files selected for processing (1)
  • MCPForUnity/Editor/Tools/CommandRegistry.cs

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Tool and command discovery now uses Unity TypeCache results first. Exhaustive assembly reflection runs only when the relevant TypeCache results are empty. Tests cover the command fallback condition.

Changes

TypeCache-first discovery

Layer / File(s) Summary
Tool discovery fallback strategy
MCPForUnity/Editor/Services/ToolDiscoveryService.cs
DiscoverAllTools uses TypeCache results when present and retains filtered, deduplicated assembly scanning as the fallback.
Command registry fallback and coverage
MCPForUnity/Editor/Tools/CommandRegistry.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/CommandRegistryTests.cs
AutoDiscoverCommands resolves tools and resources through TypeCache, orders results by full name, falls back only when both results are empty, and tests this condition.

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

Merge Risk: ⚪ Minimal · up to 4d014

The PR replaces repeated assembly scans with indexed type discovery while retaining a fallback for an entirely empty index, and the supplied EditMode and compile checks pass. No actionable merge-blocking risk remains beyond normal checks and review.

Suggested reviewers: scriptwonder

Sequence Diagram(s)

sequenceDiagram
  participant CommandRegistry
  participant TypeCache
  participant LoadedAssemblies
  CommandRegistry->>TypeCache: Get tool and resource types
  alt both TypeCache results are empty
    CommandRegistry->>LoadedAssemblies: Enumerate non-dynamic loaded types
    LoadedAssemblies-->>CommandRegistry: Return reflected types
  else cached types found
    TypeCache-->>CommandRegistry: Return cached types
  end
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: using Unity TypeCache for tool and resource discovery instead of scanning every assembly.
Description check ✅ Passed The description follows the repository template, explains the performance change, identifies the behavioral trade-off, records compatibility details, and documents EditMode and compile testing.
Linked Issues check ✅ Passed The changes satisfy issue #1336 by using TypeCache for command and tool discovery and limiting exhaustive AppDomain scanning to the empty-index case. The requested performance objective and fallback b…
Out of Scope Changes check ✅ Passed The changes remain within the scope of issue #1336. They modify discovery behavior, add a focused predicate test, and preserve the existing AssetImportWorker guard without unrelated changes.
Full details: Linked Issues check

Explanation

The changes satisfy issue #1336 by using TypeCache for command and tool discovery and limiting exhaustive AppDomain scanning to the empty-index case. The requested performance objective and fallback behavior are implemented, with tests added for the fallback predicate.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

ananttheant and others added 2 commits September 1, 2026 15:12
…every assembly

CommandRegistry.AutoDiscoverCommands walked every type of every loaded
assembly and then ran two full attribute-matching passes over that list,
on every domain reload. ToolDiscoveryService.DiscoverAllTools was worse:
it queried TypeCache first and then ran the same exhaustive AppDomain
walk anyway, unconditionally, merging the two results.

Both now read from TypeCache, Unity's prebuilt attribute index, and keep
the exhaustive walk only as a fallback for when the index comes back
empty — the domain-reload state the old comments were guarding against.
ResourceDiscoveryService already trusted TypeCache alone, so this brings
the other two in line with it.

Measured in TestProjects/UnityMCPTests (193 assemblies, 44,195 types) on
Unity 2022.3.62f1: the exhaustive scan takes 310.63 ms versus 0.01 ms for
TypeCache, and both find exactly the same 54 types. Real projects carry
more assemblies, which is where the multi-second reload cost reported in
the issue comes from.

Closes CoplayDev#1336
RegisterCommandType lets a duplicate command name overwrite the previously
registered handler, so registration order decides which type wins a collision.
Neither TypeCache nor the exhaustive fallback documents an order, while the
assembly scan they replace was stable within a build -- so a name collision
could otherwise resolve differently between domain reloads.

Orders both discovery paths by Type.FullName (ordinal). ~54 types, so the cost
is noise against the ~310ms this PR removes.

Added by a maintainer while rebasing this PR onto beta; the same fix was raised
in review on CoplayDev#1364.
@Scriptwonder
Scriptwonder force-pushed the perf/typecache-command-discovery branch from db7eb72 to 4d01462 Compare September 1, 2026 19:13
@ananttheant

Copy link
Copy Markdown
Contributor Author

Superseded by #1364, which landed the same TypeCache switch — closing this.

Yours is the better change: you dropped the exhaustive fallback entirely rather than keeping it for the empty-index case, and the OrderBy(t => t.FullName) is a genuine catch I missed. RegisterCommandType lets a duplicate command name overwrite the previous handler, so registration order decides the winner, and TypeCache documents no order — my version would have made collisions resolve differently between reloads. Good spot.

For whatever it is worth, the numbers I measured in TestProjects/UnityMCPTests (193 assemblies, 44,195 types, Unity 2022.3.62f1) back the change up: 310.63 ms for the assembly walk versus 0.01 ms for TypeCache, both finding exactly the same 54 types.

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.

[Bug]: CommandRegistry.AutoDiscoverCommands adds ~9s to every domain reload in large projects

2 participants