-
Notifications
You must be signed in to change notification settings - Fork 408
feat(pi-tui): add opt-in render profiler #1462
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
liruifengv
wants to merge
1
commit into
main
Choose a base branch
from
experiment/windows-render-stutter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@moonshot-ai/pi-tui": patch | ||
| --- | ||
|
|
||
| Add an opt-in render profiler that records per-frame render cost and stdout write timing for diagnosing terminal render stutter. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| /** | ||
| * Opt-in render profiler for diagnosing TUI render and stdout-write cost. | ||
| * | ||
| * Enabled via the `PI_TUI_RENDER_PROFILE` environment variable: | ||
| * - unset / empty -> disabled (near-zero overhead) | ||
| * - "1" / "true" -> write JSONL to ~/.pi/agent/pi-render-profile.jsonl | ||
| * - any other value -> treated as the output file path | ||
| * | ||
| * Records every terminal write (duration, byte size, backpressure signal) and a | ||
| * per-frame summary (build time, line count, full-redraw flag, event-loop lag). | ||
| * Used to investigate streaming render stutter, especially on Windows where | ||
| * ConPTY / Windows Terminal stdout writes are significantly more expensive than | ||
| * on Unix pseudoterminals. | ||
| */ | ||
|
|
||
| import * as fs from "node:fs"; | ||
| import * as os from "node:os"; | ||
| import * as path from "node:path"; | ||
| import { monitorEventLoopDelay } from "node:perf_hooks"; | ||
|
|
||
| type EventLoopHistogram = ReturnType<typeof monitorEventLoopDelay>; | ||
|
|
||
| const FLUSH_RECORD_THRESHOLD = 100; | ||
|
|
||
| function resolveProfilePath(envValue: string): string { | ||
| if (envValue === "1" || envValue.toLowerCase() === "true") { | ||
| return path.join(os.homedir(), ".pi", "agent", "pi-render-profile.jsonl"); | ||
| } | ||
| return envValue; | ||
| } | ||
|
|
||
| function roundMs(value: number): number { | ||
| return Math.round(value * 1000) / 1000; | ||
| } | ||
|
|
||
| function nsToMs(ns: number): number { | ||
| return Math.round((ns / 1e6) * 1000) / 1000; | ||
| } | ||
|
|
||
| export class RenderProfiler { | ||
| readonly enabled: boolean; | ||
| private readonly filePath: string; | ||
| private pending: string[] = []; | ||
| private histogram: EventLoopHistogram | undefined; | ||
| private closed = false; | ||
|
|
||
| constructor(envValue: string | undefined) { | ||
| this.enabled = Boolean(envValue); | ||
| if (!this.enabled) { | ||
| this.filePath = ""; | ||
| return; | ||
| } | ||
| this.filePath = resolveProfilePath(envValue as string); | ||
| try { | ||
| fs.mkdirSync(path.dirname(this.filePath), { recursive: true }); | ||
| // Start each profiled run with a clean file so sessions do not interleave. | ||
| fs.writeFileSync(this.filePath, ""); | ||
| } catch { | ||
| // Best-effort: if the file cannot be prepared, profiling silently no-ops. | ||
| } | ||
| try { | ||
| const histogram = monitorEventLoopDelay({ resolution: 20 }); | ||
| histogram.enable(); | ||
| this.histogram = histogram; | ||
| } catch { | ||
| this.histogram = undefined; | ||
| } | ||
| } | ||
|
|
||
| /** Record a single stdout write: how long it took, its size, and whether the | ||
| * stream signalled backpressure (`write` returned false). */ | ||
| recordWrite(durationMs: number, bytes: number, ok: boolean): void { | ||
| this.record({ | ||
| kind: "write", | ||
| ms: roundMs(durationMs), | ||
| bytes, | ||
| ok, | ||
| }); | ||
| } | ||
|
|
||
| /** Record a completed render frame with build cost and a since-last-frame | ||
| * event-loop lag snapshot. */ | ||
| recordFrame(fields: { | ||
| fullRedraw: boolean; | ||
| lines: number; | ||
| height: number; | ||
| buildMs: number; | ||
| totalMs: number; | ||
| }): void { | ||
| this.record({ | ||
| kind: "frame", | ||
| fullRedraw: fields.fullRedraw, | ||
| lines: fields.lines, | ||
| height: fields.height, | ||
| buildMs: roundMs(fields.buildMs), | ||
| totalMs: roundMs(fields.totalMs), | ||
| el: this.snapshotEventLoop(), | ||
| }); | ||
| } | ||
|
|
||
| private record(entry: Record<string, unknown>): void { | ||
| if (!this.enabled || this.closed) return; | ||
| this.pending.push(`${JSON.stringify({ t: Date.now(), ...entry })}\n`); | ||
| if (this.pending.length >= FLUSH_RECORD_THRESHOLD) { | ||
| this.flushAsync(); | ||
| } | ||
| } | ||
|
|
||
| private snapshotEventLoop(): { meanMs: number; maxMs: number } | undefined { | ||
| if (!this.histogram) return undefined; | ||
| // `mean` is NaN while the histogram has no samples yet (e.g. the very | ||
| // first frame); coerce to 0 so the JSONL stays numeric for parsers. | ||
| const mean = this.histogram.mean; | ||
| const snapshot = { | ||
| meanMs: Number.isFinite(mean) ? nsToMs(mean) : 0, | ||
| maxMs: nsToMs(this.histogram.max), | ||
| }; | ||
| this.histogram.reset(); | ||
| return snapshot; | ||
| } | ||
|
|
||
| private flushAsync(): void { | ||
| if (this.pending.length === 0) return; | ||
| const chunk = this.pending.join(""); | ||
| this.pending = []; | ||
| fs.promises.appendFile(this.filePath, chunk).catch(() => {}); | ||
| } | ||
|
|
||
| /** Synchronously flush any buffered records. Safe to call at shutdown. */ | ||
| flush(): void { | ||
| if (!this.enabled || this.pending.length === 0) return; | ||
| try { | ||
| fs.appendFileSync(this.filePath, this.pending.join("")); | ||
| } catch { | ||
| // Ignore flush errors | ||
| } | ||
| this.pending = []; | ||
| } | ||
|
|
||
| close(): void { | ||
| if (this.closed) return; | ||
| this.closed = true; | ||
| this.flush(); | ||
| this.histogram?.disable(); | ||
| this.histogram = undefined; | ||
| } | ||
| } | ||
|
|
||
| let singleton: RenderProfiler | undefined; | ||
|
|
||
| export function getRenderProfiler(): RenderProfiler { | ||
| if (!singleton) { | ||
| singleton = new RenderProfiler(process.env["PI_TUI_RENDER_PROFILE"]); | ||
| } | ||
| return singleton; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import assert from "node:assert"; | ||
| import * as fs from "node:fs"; | ||
| import * as os from "node:os"; | ||
| import * as path from "node:path"; | ||
| import { afterEach, beforeEach, describe, it } from "node:test"; | ||
| import { RenderProfiler } from "../src/render-profiler.ts"; | ||
|
|
||
| describe("RenderProfiler", () => { | ||
| let tmpDir: string; | ||
|
|
||
| beforeEach(() => { | ||
| tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-rp-test-")); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| try { | ||
| fs.rmSync(tmpDir, { recursive: true, force: true }); | ||
| } catch { | ||
| // ignore cleanup errors | ||
| } | ||
| }); | ||
|
|
||
| it("is disabled and writes nothing when env is unset", () => { | ||
| const file = path.join(tmpDir, "nope.jsonl"); | ||
| const profiler = new RenderProfiler(undefined); | ||
| assert.equal(profiler.enabled, false); | ||
| profiler.recordWrite(1.2, 100, true); | ||
| profiler.recordFrame({ fullRedraw: false, lines: 10, height: 5, buildMs: 0.1, totalMs: 0.2 }); | ||
| profiler.close(); | ||
| assert.equal(fs.existsSync(file), false); | ||
| }); | ||
|
|
||
| it("records writes and frames as JSONL when enabled via a custom path", () => { | ||
| const file = path.join(tmpDir, "profile.jsonl"); | ||
| const profiler = new RenderProfiler(file); | ||
| assert.equal(profiler.enabled, true); | ||
| profiler.recordWrite(1.2345, 5678, true); | ||
| profiler.recordFrame({ fullRedraw: false, lines: 42, height: 24, buildMs: 0.567, totalMs: 3.1234 }); | ||
| profiler.close(); | ||
|
|
||
| const lines = fs.readFileSync(file, "utf8").trim().split("\n"); | ||
| assert.equal(lines.length, 2); | ||
|
|
||
| const write = JSON.parse(lines[0]!); | ||
| assert.equal(write.kind, "write"); | ||
| assert.equal(write.ok, true); | ||
| assert.equal(write.bytes, 5678); | ||
| // duration is rounded to millisecond precision | ||
| assert.equal(write.ms, 1.235); | ||
|
|
||
| const frame = JSON.parse(lines[1]!); | ||
| assert.equal(frame.kind, "frame"); | ||
| assert.equal(frame.fullRedraw, false); | ||
| assert.equal(frame.lines, 42); | ||
| assert.equal(frame.height, 24); | ||
| assert.equal(frame.buildMs, 0.567); | ||
| assert.equal(frame.totalMs, 3.123); | ||
| assert.equal(typeof frame.el.meanMs, "number"); | ||
| assert.equal(typeof frame.el.maxMs, "number"); | ||
| }); | ||
|
|
||
| it("creates the parent directory when it does not exist", () => { | ||
| const nested = path.join(tmpDir, "a", "b", "profile.jsonl"); | ||
| const profiler = new RenderProfiler(nested); | ||
| profiler.recordWrite(0.1, 1, true); | ||
| profiler.close(); | ||
| assert.equal(fs.existsSync(nested), true); | ||
| }); | ||
|
|
||
| it("records backpressure via the write ok flag", () => { | ||
| const file = path.join(tmpDir, "bp.jsonl"); | ||
| const profiler = new RenderProfiler(file); | ||
| profiler.recordWrite(10, 4096, false); | ||
| profiler.close(); | ||
| const rec = JSON.parse(fs.readFileSync(file, "utf8").trim()); | ||
| assert.equal(rec.ok, false); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a profiling run reaches 100 records, this drops the chunk from
pendingand starts a fire-and-forgetappendFile;close()only sync-flushes the currentpendingarray, while the normal Kimi shutdown path callsTUI.stop()and thenprocess.exit()fromapps/kimi-code/src/cli/run-shell.ts. In sessions long enough to cross the threshold, records already handed to this async write can therefore be lost or written out of order before the process exits, which makes the opt-in profile incomplete exactly for the long render-stutter captures it is meant to diagnose.Useful? React with 👍 / 👎.