Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Agent Note: MCP performance readouts

Status: implemented

## Problem

Coding agents driving or inspecting a running NSGo game over `nsgo mcp` (see [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md)) can query scenes, layers, entities and components, but cannot observe live frame timing, update and draw costs, draw statistics, per-frame heap allocations, GC pauses, or named profiler zones. Without structured readouts backed by the same counters as `game/debug`'s on-screen overlay, agents cannot verify frame-budget compliance or diagnose spikes and allocation regressions programmatically.

## Decision

Add a dedicated `perf` tool group (`packages/game/mcp/perf.go`) exposing `game_perf_readout`, `game_perf_zones`, and `game_perf_reset` via `Bridge.Tools()`, reading directly from `debug.Overlay`, `debug.Profiler`, `debug.GCMonitor`, `debug.MemoryTracker` and `debug.DrawStats`, plus 3D statistics a game supplies as `mcp.PerfRender3DStats`. Extend `packages/game/debug` minimally so `GCMonitor` also samples per-frame heap allocations with zero steady-state allocations, `Overlay` supports optional `DrawStats`, and `Overlay`/`Profiler`/`GCMonitor` expose clean reset helpers shared by both the HUD and MCP.

## Architecture and contract

- **Single source of truth with `debug.Overlay`**: `game_perf_readout` reads `FPS()`, `Average()`, `Latest()`, `Samples()`, `DrawStats()`, `Profiler()`, `GC()`, and `Memory()` directly from `Config.Overlay` (using the same `float64(d) / float64(time.Millisecond)` conversion as `debug/overlay.go`). Values returned by MCP match the on-screen debug overlay bit-for-bit, and `game_perf_reset` refreshes the visible overlay HUD via `Overlay.ResetStats()`.
- **Zero-alloc per-frame allocation tracking in `debug.GCMonitor`**: `GCMonitor` extends its pre-allocated `runtime/metrics` sample buffer from 3 to 5 entries to read `/gc/heap/allocs:objects` and `/gc/heap/allocs:bytes` alongside `/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, and `/memory/classes/heap/objects:bytes`. Running window totals (`recentAllocs`, `recentAllocBytes`) are updated in O(1) as the ring buffer advances, preserving `debug.AssertZeroAllocs` in steady state while exposing `AllocsPerFrame()` and `AllocBytesPerFrame()` to both the overlay and MCP.
- **2D and 3D draw statistics**: `debug.DrawStats` (`DrawCalls`, `Sprites`, `Batches`, `Triangles`, `Vertices`) can be supplied via `debug.Options.DrawStats`, pushed with `Overlay.SetDrawStats`, or overridden via `mcp.Config.DrawStatsFunc`. Optional `mcp.Config.RenderStatsFunc` attaches full 3D telemetry under `render3d` as `mcp.PerfRender3DStats`, a struct with the same fields as `render3d.RenderStats` so a game converts with `mcp.PerfRender3DStats(stats)` while `game/mcp` never imports `game/render3d` (which would link `nsgo/gpu`, `scene3d`, `particles` and `ktx2` into every 2D game that attaches the bridge), and populates top-level `draw_calls`, `batches`, `triangles`, and `vertices` automatically when no 2D draw-stats source is configured.
- **Strict schemas and graceful degradation**: Every perf tool decodes arguments with `json.Decoder.DisallowUnknownFields()` and rejects negative limits. Calling `game_perf_readout` or `game_perf_reset` with no configured perf telemetry returns an explicit error rather than misleading zeros; configuring any subset of providers succeeds and reports active providers in `sources`. Calling `game_perf_zones` without a profiler returns an explicit error, while `game_perf_readout` with `include_zones: true` degrades cleanly when only an overlay is configured.
- **Release-build parity**: Every new method added to `packages/game/debug` (`DrawStats`, `SetDrawStats`, `HasDrawStats`, `ResetStats`, `Profiler.Reset`, `GCMonitor.AllocsPerFrame`, `GCMonitor.AllocBytesPerFrame`, `GCMonitor.Reset`) has a matching zero-cost no-op stub in the `//go:build release` files so `-tags release` builds remain unaffected.
- **Minimal merge footprint**: All tool schemas, response structs, and handlers live in `packages/game/mcp/perf.go`, with only additive `Config` fields and `b.perfTools()` hookup in `packages/game/mcp/mcp.go` so it conflicts with the other MCP tool groups (#462–#469) only where each appends to `Config`, `Tools()` and the tool lists.

## Alternatives considered

### Sampling `runtime.ReadMemStats` inside `mcp` on every `game_perf_readout` call

Reading `runtime.ReadMemStats` directly in `mcp` would avoid extending `debug.GCMonitor` and would report heap/allocation numbers even when `Config.GC` is nil. This was rejected because `runtime.ReadMemStats` triggers a stop-the-world pause (distorting the very frame times being measured), produces ad-hoc inter-call deltas rather than per-frame averages, and would diverge from the numbers displayed in `debug.Overlay`.

### Keeping `DrawStats` exclusively inside `packages/game/mcp`

Defining `DrawStats` only inside `mcp` would avoid touching `packages/game/debug`. This was rejected because issue #468 requires MCP performance readouts to match the debug overlay's values; placing `DrawStats` on `debug.Overlay` lets games report draw counts once and have both the on-screen HUD and `game_perf_readout` reflect identical numbers.

### Returning all-zero readouts when no performance providers are configured

Returning a zeroed `PerfReadoutResult` on an empty `mcp.Config{}` avoids errors in unconfigured games. This was rejected because zero `fps`, zero `draw_calls`, and zero `allocs_per_frame` are indistinguishable from a paused or idle game; returning an explicit error when no provider is configured matches `game_entities_list` and `game_layers_list` in `inspect.go`.

## Consequences

- **Benefits**: Agents can inspect live FPS, average/latest/percentile frame timings, update/draw splits, 2D and 3D draw counts, per-frame heap allocations, GC pauses/hitches, asset memory budgets, chronological frame history, and profiler zones with guaranteed parity against `debug.Overlay`. Resetting metrics via MCP keeps the visible HUD synchronized.
- **Costs**: `packages/game/debug` gains a small additive API surface (`DrawStats`, `GCMonitor` allocation averages, and `Reset` methods) that must remain mirrored in its `release` build stubs. `packages/game/mcp` now imports `packages/game/debug` (both are Experimental packages, so Stable packages remain unaffected); it does not import `packages/game/render3d`.

## Verification

Verified with `gofmt`, `go run ./cmd/gameschema -check`, `go tool nsgo check -target macos,windows,linux,android,web`, `go tool nsgo test ./mcp`, `go tool nsgo test ./debug`, `go tool nsgo test -tags release ./debug`, `go tool nsgo test -run TestStabilityTable .`, `go run ./tools/changelog check`, and `bun run verify-notes`.
4 changes: 4 additions & 0 deletions changelog.d/mcp-perf-readouts-468.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Added

- `game/mcp`: add `game_perf_readout`, `game_perf_zones`, and `game_perf_reset` MCP tools exposing frame timings, percentiles, draw statistics, per-frame allocations, GC/heap telemetry, asset memory, and 3D render statistics matching the debug overlay (#468).
- `game/debug`: track per-frame heap allocations (`/gc/heap/allocs:objects` and `/gc/heap/allocs:bytes`) in `GCMonitor`, add `DrawStats` support to `Overlay`, and add `Reset` methods on `Profiler`, `GCMonitor`, and `Overlay.ResetStats` (#468).
25 changes: 25 additions & 0 deletions docs/en/debug.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,31 @@ Convenience shortcuts `overlay.DrawBox`, `overlay.DrawCircle`, `overlay.DrawSpri
overlay.DrawFighterBoxes(d, p1, core.RGB(0x38bdf8), core.RGB(0xef4444))
```

## Draw statistics

Report each frame's draw submissions in either of two ways, and the overlay shows them as a `Draw: N calls · N sprites · N batches` line, followed by `· N tris · N verts` once either count is non-zero:

1. **Pull via `Options.DrawStats`**: a `func() debug.DrawStats` called whenever the overlay refreshes.
2. **Push via `overlay.SetDrawStats(stats)`**: used when `Options.DrawStats` is nil; call it once per frame after drawing.

```go
overlay := debug.New(debug.Options{
DrawStats: func() debug.DrawStats {
return debug.DrawStats{DrawCalls: r.drawCalls, Sprites: len(actorsBatch.Sprites), Batches: r.batches}
},
})
```

`overlay.DrawStats()` returns the current values and `overlay.HasDrawStats()` reports whether either source is set; the line stays hidden until one is. [`game/mcp`](mcp.md)'s `game_perf_readout` reports the same values.

## Resetting the readouts

- `overlay.ResetStats()` clears the frame-time ring buffer and any pushed draw statistics and refreshes the HUD. An `Options.DrawStats` callback keeps reporting.
- `GCMonitor.Reset()` clears the GC frame history, hitch count, pause peaks and per-frame allocation averages, and re-reads the runtime counters so the next frame is measured from that point (see [GC and frame allocations](gc-and-allocations.md)).
- `Profiler.Reset()` clears every timing scope's accumulated timings and history. Scope names keep their IDs, so a scope still open across the reset is charged to its own name, and a trace recording started with `StartRecording` keeps running and keeps its events.

[`game/mcp`](mcp.md)'s `game_perf_reset` calls all three.

## Scene inspector

Supply live scene structure in either of two ways:
Expand Down
4 changes: 3 additions & 1 deletion docs/en/gc-and-allocations.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Keep `Loop.Update`, `Loop.Draw`, and `Canvas.Draw` callbacks free of steady-stat

### Runtime Overlay (`GCMonitor`)

Wire `debug.NewGCMonitor` into `debug.Options.GC` to sample `runtime/metrics` (`/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, `/memory/classes/heap/objects:bytes`) once per frame with zero steady-state allocations:
Wire `debug.NewGCMonitor` into `debug.Options.GC` to sample `runtime/metrics` (`/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, `/memory/classes/heap/objects:bytes`, `/gc/heap/allocs:objects`, `/gc/heap/allocs:bytes`) once per frame with zero steady-state allocations:

```go
gcMon := debug.NewGCMonitor(debug.FrameHistory)
Expand All @@ -49,6 +49,8 @@ overlay := debug.New(debug.Options{

Frames where a GC cycle or pause occurred are flagged (`GCFrameSample.Hitched == true`) and marked directly on the overlay's frame-time graph, alongside cycle count, last/max pause, live heap bytes, and recent hitch count.

Each `GCFrameSample` also carries the heap objects and bytes allocated during that frame (`AllocsDelta`, `AllocBytesDelta`). `gcMon.AllocsPerFrame()` and `gcMon.AllocBytesPerFrame()` average them over the retained history, and the overlay shows them under the GC summary as `allocs 12.0/f (1.5 KB/f)`. A value that stays above zero in steady gameplay means a hot path allocates every frame. Call `gcMon.Reset()` after a loading screen or level change to drop the history and measure from that point.

### CI Regression Checks (`AssertZeroAllocs`)

Use `debug.AssertZeroAllocs` (wrapping `testing.AllocsPerRun`) in unit tests to guard hot paths from accidental allocations in pull requests:
Expand Down
41 changes: 27 additions & 14 deletions docs/en/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,22 @@ Call `mcp.Attach` (or `mcp.New` followed by `bridge.Attach`) on the engine gorou

```go
bridge, err := mcp.Attach(cx, mcp.Config{
Scenes: g.scenes,
SceneName: func(c *scene.Controller) string { return g.sceneNames[c] },
SceneFunc: func() *scene.Scene { return g.activeScene },
NamedScenes: map[string]*scene.Scene{"title": g.titleScene},
WorldFunc: func() *entities.World { return g.world },
EntityName: func(e entities.Entity) string { return g.names[e] },
EntityTags: func(e entities.Entity) []string { return g.tags[e] },
EntityLayer: func(e entities.Entity) string { return g.layers[e] },
Loop: g.loop,
RandomStreams: g.rng,
Actions: g.actions,
Viewport: &g.viewport,
ViewSizeFunc: g.currentViewSize,
Console: g.console,
Scenes: g.scenes,
SceneName: func(c *scene.Controller) string { return g.sceneNames[c] },
SceneFunc: func() *scene.Scene { return g.activeScene },
NamedScenes: map[string]*scene.Scene{"title": g.titleScene},
WorldFunc: func() *entities.World { return g.world },
EntityName: func(e entities.Entity) string { return g.names[e] },
EntityTags: func(e entities.Entity) []string { return g.tags[e] },
EntityLayer: func(e entities.Entity) string { return g.layers[e] },
Loop: g.loop,
RandomStreams: g.rng,
Actions: g.actions,
Viewport: &g.viewport,
ViewSizeFunc: g.currentViewSize,
Console: g.console,
Overlay: g.debugOverlay,
RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) },
})
if err != nil {
return err
Expand Down Expand Up @@ -117,6 +119,9 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r
| `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps` (`1..3600`), `reset` (default `true` when `ResetFunc` or a seed target is configured) | Resets to the recording's seed and starts deterministic playback via `replay.Player`, optionally advancing all (`run_to_end`, recordings up to `3600` steps) or `steps` frames synchronously via `StepFunc` or the game loop's `StepNow`. A recording whose `rate` differs from the game's fixed step rate is refused. |
| `game_replay_stop` | `{}` | Stops an active replay playback cleanly and reports how many frames were played. |
| `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. |
| `game_perf_readout` | `include_history` (optional, default `false`), `history_limit` (optional), `include_zones` (optional, default `false`), `zones_limit` (optional) | Live performance readout matching the debug overlay: `fps`, rolling average and latest `frame_ms`/`update_ms`/`draw_ms`, min/max/p50/p95/p99 frame times, draw stats (`draw_calls`, `sprites`, `batches`, `triangles`, `vertices`), per-frame heap allocations (`allocs_per_frame`, `alloc_bytes_per_frame`, `last_frame_allocs`, `last_frame_alloc_bytes`), `heap_bytes`, `gc_count`, GC pause/hitch metrics, optional `render3d` and `asset_memory` breakdowns, and optional chronological `history` and profiler `zones`. |
| `game_perf_zones` | `limit` (optional) | Named timing zones from `debug.Profiler` sorted by recent frame cost (`name`, `last_ms`, `avg_ms`, `max_ms`, `calls`), plus `recording`, `recorded_frames` and `total`. |
| `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zone timings, and `debug.GCMonitor` history. A profiler trace recording started with `StartRecording` keeps running and keeps its events. |

All tools reject unknown argument fields.

Expand Down Expand Up @@ -187,6 +192,14 @@ bridge, err := mcp.Attach(cx, mcp.Config{
- `game_replay_play` accepts either a stored `name` or inline `yaml` text and replays either synchronously (`run_to_end: true` or `steps: N`) or frame by frame as the game loop advances. Without `StepFunc`, synchronous playback advances the Bridge's loop with `Loop.StepNow`, so `game_loop_status` counts the replayed steps and game time. Like `game_loop_step`, a single call advances at most `MaxLoopSteps` (`3600`) steps.
- After the final recorded step, the next `ctrl.Step()` is a trailing playback step that releases actions still held at the end of the recording (firing `JustReleased` once); the step after it returns to live input and calls `OnReplayStop`.

## Performance readouts

Pass your [`debug.Overlay`](debug.md) via `Config.Overlay` to expose the exact same frame timings, draw statistics (`debug.Options.DrawStats` or `Overlay.SetDrawStats`), GC/allocation counters (`debug.GCMonitor`), asset memory (`debug.MemoryTracker`) and timing scopes (`debug.Profiler`) shown by the on-screen debug HUD.

- `Config.Profiler`, `Config.GC`, `Config.Memory` and `Config.DrawStatsFunc` override (or work standalone without) `Config.Overlay`.
- `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](render3d.md) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. `mcp.PerfRender3DStats` has the same fields as `render3d.RenderStats`, so `mcp.PerfRender3DStats(stats)` converts one; `game/mcp` does not import `game/render3d`, so a 2D game that attaches the bridge does not link the 3D renderer.
- `game_perf_readout` always includes a `sources` object indicating which telemetry providers are active (`overlay`, `profiler`, `gc`, `memory`, `draw_stats`, `render3d`).

## Stable entity references

Every live entity receives a generational reference formatted as `"entity:<index>:<generation>"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`:
Expand Down
25 changes: 25 additions & 0 deletions docs/zh/debug.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,31 @@ d.Restore()
overlay.DrawFighterBoxes(d, p1, core.RGB(0x38bdf8), core.RGB(0xef4444))
```

## 绘制统计

可以用以下两种方式提供每帧的绘制提交数,浮层会显示一行 `Draw: N calls · N sprites · N batches`,三角形数或顶点数不为零时再追加 `· N tris · N verts`:

1. **通过 `Options.DrawStats` 拉取**:一个 `func() debug.DrawStats`,浮层每次刷新时调用。
2. **通过 `overlay.SetDrawStats(stats)` 推送**:在 `Options.DrawStats` 为 nil 时使用,每帧绘制完成后调用一次。

```go
overlay := debug.New(debug.Options{
DrawStats: func() debug.DrawStats {
return debug.DrawStats{DrawCalls: r.drawCalls, Sprites: len(actorsBatch.Sprites), Batches: r.batches}
},
})
```

`overlay.DrawStats()` 返回当前数值,`overlay.HasDrawStats()` 表示两种来源是否设置了其一;都未设置时不显示这一行。[`game/mcp`](mcp.md) 的 `game_perf_readout` 报告的是同一组数值。

## 重置读数

- `overlay.ResetStats()` 清空帧耗时环形缓冲区和已推送的绘制统计,并刷新 HUD。`Options.DrawStats` 回调会继续提供数值。
- `GCMonitor.Reset()` 清空 GC 帧历史、卡顿计数、停顿峰值和每帧分配均值,并重新读取运行时计数器,下一帧从此刻开始计量(见 [GC 与帧分配预算](gc-and-allocations.md))。
- `Profiler.Reset()` 清空每个计时区间累积的耗时和历史。区间名保留原有 ID,因此跨越重置仍未结束的区间会计入它自己的名字;通过 `StartRecording` 开始的追踪录制会继续进行,已录制的事件也会保留。

[`game/mcp`](mcp.md) 的 `game_perf_reset` 会依次调用这三者。

## 场景检查器

提供实时场景结构有两种方式:
Expand Down
4 changes: 3 additions & 1 deletion docs/zh/gc-and-allocations.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func configureGC() {

### 运行时覆盖层(`GCMonitor`)

将 `debug.NewGCMonitor` 传入 `debug.Options.GC`,每帧以零稳态分配采样 `runtime/metrics`(`/gc/pauses:seconds`、`/gc/cycles/total:gc-cycles`、`/memory/classes/heap/objects:bytes`):
将 `debug.NewGCMonitor` 传入 `debug.Options.GC`,每帧以零稳态分配采样 `runtime/metrics`(`/gc/pauses:seconds`、`/gc/cycles/total:gc-cycles`、`/memory/classes/heap/objects:bytes`、`/gc/heap/allocs:objects`、`/gc/heap/allocs:bytes`):

```go
gcMon := debug.NewGCMonitor(debug.FrameHistory)
Expand All @@ -49,6 +49,8 @@ overlay := debug.New(debug.Options{

当某帧内发生 GC 周期或停顿时,该帧会被标记为 `GCFrameSample.Hitched == true`,并直接在调试覆盖层的帧耗时柱状图上高亮标出,同时显示累计周期数、最近/最大停顿、存活堆大小以及近期卡顿帧数。

每个 `GCFrameSample` 还记录该帧内分配的堆对象数与字节数(`AllocsDelta`、`AllocBytesDelta`)。`gcMon.AllocsPerFrame()` 与 `gcMon.AllocBytesPerFrame()` 给出它们在保留历史内的平均值,浮层在 GC 摘要下以 `allocs 12.0/f (1.5 KB/f)` 的形式显示。稳定游玩时这个值始终大于零,说明某条热路径每帧都在分配。在加载画面或切换关卡之后调用 `gcMon.Reset()`,即可丢弃历史,从此刻重新计量。

### CI 分配回归检查(`AssertZeroAllocs`)

在单元测试中使用 `debug.AssertZeroAllocs`(封装 `testing.AllocsPerRun`),防止后续改动在热路径引入意外的堆分配:
Expand Down
Loading
Loading