Back to all posts

Measure Unity performance regressions with Cluewren autoplay

Playing a fixed route by hand on every build is slow, making precise comparisons between builds difficult. With the open-source (Apache-2.0) Cluewren, your own coding agent (Claude Code or Codex) uses Cluewren’s MCP server to play the game open in the Unity, Godot, or Unreal Engine editor. The agent reads the code and writes a C# harness, Jev (a fast decision model from TypeSafe) plays it through the engine plugin, and the agent reports a verdict with measured evidence. During that play, the Framedash Unity SDK records frame time. This post walks the same route on two builds to find which build and which part of the level got slower. The slowdown in the candidate build was simulated as a stand-in for a heavy asset or effect.

Environment and prerequisites

This walkthrough used the following setup:

  • Unity: Unity 6000.6.7f1
  • Sample project: a copy of Unity’s FPS Microgame (MainScene) with the Cluewren Unity plugin installed
  • Cluewren requirements: Windows 11 (tested), .NET 10 SDK, build from source, a TypeSafe API key, Claude Code or Codex

Cluewren itself sends nothing to Cluewren. Decision requests go to TypeSafe’s API, and the agent talks to its own provider.

Install the plugin and SDK

For installing Cluewren, see the Cluewren install guide. For adding the plugin to a Unity project, see the Cluewren Unity plugin docs. The Framedash Unity SDK v0.1.9 is added via Package Manager git URL:

https://github.com/crane-valley/framedash-unity-sdk.git#v0.1.9

Add the telemetry probe script

Add the following script to the project:

using System;
using Framedash;
using Unity.FPS.Gameplay;
using UnityEngine;

public sealed class FramedashPlaytestProbe : MonoBehaviour
{
    const string MapId = "fps-microgame-main";
    const float Interval = 0.25f;

    PlayerCharacterController _player;
    float _next;
    bool _closing;
    public string CompletionMarker { get; private set; }
    public bool FlushHttp202;
    public bool FlushAcknowledged;
    public int Samples;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    static void Boot()
    {
        if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("FRAMEDASH_API_KEY")))
            return;
        TelemetrySDK.Initialize(buildId: Environment.GetEnvironmentVariable("FRAMEDASH_BUILD_ID"), enableOfflineQueue: false);
        TelemetrySDK.Instance.VerboseLogging = true;
        TelemetrySDK.Instance.BeginAutomatedSessionFromEnvironment();
        var go = new GameObject(nameof(FramedashPlaytestProbe));
        DontDestroyOnLoad(go);
        go.AddComponent<FramedashPlaytestProbe>();
    }

    void OnEnable() => Application.logMessageReceived += ObserveLog;
    void OnDisable() => Application.logMessageReceived -= ObserveLog;

    void ObserveLog(string message, string stackTrace, LogType type)
    {
        if (_closing && message.StartsWith("[Framedash] Flushed ") && message.Contains("HTTP 202"))
            FlushHttp202 = true;
    }

    void Update()
    {
        if (_closing || Time.unscaledTime < _next)
            return;
        _next = Time.unscaledTime + Interval;
        if (_player == null)
            _player = FindAnyObjectByType<PlayerCharacterController>();
        if (_player != null)
        {
            TelemetrySDK.Instance.Track("player_position", MapId, _player.transform.position);
            Samples++;
        }
    }

    public void BeginFinalFlush()
    {
        _closing = true;
        FlushHttp202 = false;
        CompletionMarker = "cluewren_complete_" + Guid.NewGuid().ToString("N");
        Debug.Log("Completion marker: " + CompletionMarker);
        TelemetrySDK.Instance.SetEventSamplingRate(CompletionMarker, 1f);
        TelemetrySDK.Instance.Track(CompletionMarker, MapId, Vector3.zero);
        TelemetrySDK.Instance.Flush();
    }

    public void FinishFinalFlush() => FlushAcknowledged = TelemetrySDK.Instance.FlushBlocking(10000);
}

This script initializes the SDK only when FRAMEDASH_API_KEY is set. The build tags are applied automatically from FRAMEDASH_BUILD_ID and FRAMEDASH_TEST_SCENARIO. The player position is sent every 0.25 s as a player_position event with map_id set to fps-microgame-main. By SDK design, every Track() event records the frame time, FPS, GPU time, and memory of that moment, so the position samples double as per-location frame-time samples. The SDK also automatically sends a perf_heartbeat event every 10 s.

Before reporting done or stopping Play mode, call BeginFinalFlush() in the final executor, keep the Unity player loop running until the verbose SDK log reports HTTP 202, then call FinishFinalFlush(). Treat a timeout, missing 202, false, or insufficient samples as a failure. Record the marker and build ID; use a separate host or manual step with a query:read (Read-only + SQL) key to query the server and confirm the fresh matching marker and expected position count before declaring end-to-end verification complete. A 202 is asynchronous acceptance, not proof of storage. Do not defer this remote work to Harness.Teardown or rely on quit alone.

Add this to the final executor and call it after the route, before setting Status to done. Adjust the Probe hierarchy path to your scene.

const string Probe = "/FramedashPlaytestProbe|FramedashPlaytestProbe";

async Task FinalDelivery(Game game)
{
    await game.Call(Probe, "BeginFinalFlush");
    var timeout = System.Diagnostics.Stopwatch.StartNew();
    while (timeout.Elapsed.TotalSeconds < 15 && !(await game.Get(Probe, "FlushHttp202")).Truthy)
        await game.Tick();
    await game.Call(Probe, "FinishFinalFlush");
    if (!(await game.Get(Probe, "FlushHttp202")).Truthy ||
        !(await game.Get(Probe, "FlushAcknowledged")).Truthy ||
        await game.Num(Probe, "Samples") < 1)
        throw new InvalidOperationException("Telemetry delivery was not acknowledged.");
}

The final executor checks delivery signals only. Cluewren reaching done is distinct from end-to-end verification: the separate server query determines whether the experiment is complete.

A separate short-run check with Cluewren 0.1.0, Jev 1.13.0 and Unity SDK 0.1.9 lost all telemetry when relying on quit; a remote flush in teardown was cancelled. That test confirmed the sequence with a separate synthetic fixture. The exact FPS probe and executor shown here were also tested locally with Cluewren Game and Unity SDK 0.1.9 against a loopback receiver: the success case delivered the marker, and missing 202, failed acknowledgement and zero samples each failed the executor. This used a stub FPS controller and a locally initialized bridge; it did not run the FPS route or verify cloud storage. The original experiment used SDK 0.1.8; use 0.1.9 for this updated probe.

Set environment variables and launch the editor

Before launching the Unity editor, set these environment variables:

FRAMEDASH_API_KEY=<Ingest key with events:write>
FRAMEDASH_BUILD_ID=fps-walk-base
FRAMEDASH_TEST_SCENARIO=cluewren-walkthrough

The first run, in which the agent writes and fixes the harness, gets its own build ID (we used fps-walkthrough-baseline) so its events stay out of the comparison. Then set fps-walk-base for the measured baseline run and fps-walk-heavy-chamber for the candidate run, each in a fresh editor launch with that variable set. Set the API key only in the environment that runs the editor; never paste keys into the agent chat.

Before running, start the MCP server and agent from the actual Unity project directory and check the selected project path and Editor version in metadata. Use a fresh build ID for each run; keep warmup, calibration and idle samples out of the measured route.

Prompt the agent and run the cold pass

Give the coding agent (Claude Code) the same request for both builds:

Walk the player through the whole level: start at the spawn point, go through every area the level contains, and finish back at the start. Do not fight unless an enemy blocks the way.

On the first (cold) run, the agent required 3 episodes and 471 s. In episode 1 it fell off the field edge into the lava, and in episode 2 a HoverBot killed it. The agent fixed its harness each time and completed the route in episode 3. This run was recorded under its own build ID, fps-walkthrough-baseline, so its events are not in the comparison. The generated harness is kept in the project’s run memory and reused for the same request.

Results across both builds

The candidate build simulates an expensive effect inside the lower chamber: while the player stands inside the chamber, the main thread spins for 12 ms each frame. This stands in for a real heavy asset or effect.

Because the runs reused the warm harness, each compared run took a single episode:

  • Baseline (fps-walk-base): achieved, 84.7 s report time, back at the spawn point at t=62.0 s. Route: central hall, west altar, four quarters of the big open field, field gateway, stairs through the big door, entrance, far end and east side of the lower chamber, and back to spawn. One fight (shot the HoverBot that was shooting at it, 2.8 s).
  • Candidate (fps-walk-heavy-chamber): achieved, 83.4 s report time, same 12 plan steps in the same order, back at spawn at t=62.4 s. Same single fight (2.8 s).

Compare with perf-diff and the Regression page

Compare the two builds with the Framedash CLI (@framedash/cli 0.2.0) using an analytics:read key:

npx @framedash/cli perf-diff --baseline fps-walk-base --candidate fps-walk-heavy-chamber --metric frame_time --threshold 10 --days 7

The output lines for the metrics:

  • frame_time: baseline P50 8.92 ms, candidate P50 15.09 ms (+69.3 %, isRegression is true); P95 52.66 ms vs 53.20 ms.
  • memory: -0.4 % (not a regression).
  • gpu_time: -15.6 % (not a regression; values are around 1.4-1.6 ms, so this is noise).

The report’s isRegression flag is directional: it is true whenever the metric got worse. The percentage threshold is not applied to this flag. The --threshold value gates only the exit code when you pass --fail-on-regression. Add --fail-on-regression to fail a CI job when a regression exceeds the threshold. For CI setup, see Check game performance in CI before merging a change, Detect Unity performance regressions in CI, and the CLI reference.

The dashboard’s Regression page shows the same result:

Framedash dashboard Regression page comparing frame times between the baseline and candidate builds
The dashboard Regression page comparing frame time between fps-walk-base and fps-walk-heavy-chamber.

The dashboard shows the same numbers: Frame Time +69.3 % (8.92 ms vs 15.09 ms), with 299 samples for each build.

Whole-build P50 depends on the population of events, including idle time. Compare the same route and conditions, and restrict SQL to each measured episode time window and area. In a separate toy test, nine samples per build in the same upper-right area had P50 6.471 → 25.603 ms and a 10% regional SQL gate exited 1, while whole-build perf-diff returned -3.318% and exit 0 with unequal idle populations. The latter does not rule out a local regression; this small artificial test is not a general performance guarantee.

Break down by area with the query

To locate where the slowdown happened, run SQL through the CLI’s query command to group by area. This command requires a Read-only + SQL key (query:read) or a Full key (data:admin); keys with only analytics:read receive a 403 error. The lower chamber is the part of the level below floor level (y < -3) at x > 20 in Unity world units.

The following is the original historical query, without episode time filters; it produced the table below. For a new comparison, replace the build IDs and UTC timestamps in the next query with your recorded episode boundaries.

npx @framedash/cli query "SELECT build_id, (position_y < -3 AND position_x > 20) AS lower_chamber, count() c, round(quantile(0.5)(frame_time_ms),1) p50, round(quantile(0.95)(frame_time_ms),1) p95 FROM events WHERE build_id IN ('fps-walk-base','fps-walk-heavy-chamber') AND event_name='player_position' GROUP BY build_id, lower_chamber ORDER BY build_id, lower_chamber"
SELECT build_id, (position_y < -3 AND position_x > 20) AS lower_chamber,
       count() AS samples, quantile(0.5)(frame_time_ms) AS p50_ms
FROM events
WHERE event_name = 'player_position' AND map_id = 'fps-microgame-main'
  AND ((build_id = 'BASE_BUILD_ID' AND timestamp >= toDateTime64('2026-01-01 00:00:00.000', 3, 'UTC') AND timestamp < toDateTime64('2026-01-01 00:01:00.000', 3, 'UTC'))
    OR (build_id = 'CANDIDATE_BUILD_ID' AND timestamp >= toDateTime64('2026-01-01 01:00:00.000', 3, 'UTC') AND timestamp < toDateTime64('2026-01-01 01:01:00.000', 3, 'UTC')))
GROUP BY build_id, lower_chamber
ORDER BY build_id, lower_chamber

The aggregated results:

build_idareasamplesP50P95
fps-walk-baseoutside chamber2277.6 ms52.9 ms
fps-walk-baselower chamber6511.5 ms36.7 ms
fps-walk-heavy-chamberoutside chamber2247.0 ms53.2 ms
fps-walk-heavy-chamberlower chamber6826.0 ms54.0 ms

The chamber P50 increased by 14.5 ms in this comparison; the outside-chamber P50 decreased by 0.6 ms. These aggregates do not establish the cause of every spike.

Compare on the top-down heatmap

The breakdown identified by the query can also be seen visually on the dashboard map. Framedash now allows maps to be registered as Y-up (Unity, Godot), which bins the heatmap on world X/Z with Y as height so a Unity level appears top-down. The map fps-microgame-main was re-captured as an orthographic top-down image (placing the camera below room ceilings so floors remain visible) and uploaded with the required “Up axis” setting set to “Y-up (Unity, Godot)”. Telemetry was not changed or re-sent; the same player_position events from both runs land on the top-down map. For details on the up axis, see the heatmap documentation.

In the dashboard, open Maps > fps-microgame-main, select Performance mode, set the metric to Frame Time, cell size to 10 m, period to the last 7 days, and filter each panel to one build.

Two top-down heatmaps of the level, baseline left and candidate right, with the lower chamber red in the candidate
Top-down heatmap comparison: left = fps-walk-base, right = fps-walk-heavy-chamber.

The lower chamber is the room on the right of the map. In the candidate (fps-walk-heavy-chamber), the chamber cells turn red, whereas in the baseline (fps-walk-base) they remain mostly yellow and orange. Across the rest of the route, the heatmap looks alike in both builds. Color is relative per panel: each panel has its own legend (baseline 7.24 to 52.67 ms, candidate 5.21 to 53.13 ms), so compare colors only roughly; the exact numbers come from the SQL query above. Both builds also show scattered red cells outside the chamber; their causes were not established.

Caveats to keep in mind

Keep these points in mind when applying this workflow:

  • Editor and capture overhead: this measurement runs in Unity’s Editor Play mode while Cluewren captures frames for the agent. Both builds had P95 around 53 ms, and the platform reports as WindowsEditor. Editor and capture overhead may affect the measurement, but the cause of individual spikes was not established. Use this for relative comparisons between builds under identical conditions, not for absolute player numbers. For measuring standalone player builds, see Measure the build you ship.
  • Keep conditions identical: run both builds under the same conditions, with the same request, on the same machine, and with the same warm harness.
  • API key handling: set the Ingest key only in the game’s launch environment; never paste keys into the agent chat (Cluewren follows this same rule for its TypeSafe key).

Summary

The agent executes the same request across two builds while Framedash records frame time. The perf-diff command and the dashboard Regression page reveal which build slowed down, and querying position samples or viewing the top-down heatmap pinpoints where in the level the regression occurred. To learn more about Cluewren, visit the Cluewren website.