Add pre-release frame-regression profiling

Ensures the app never generates frames without a cause (frame emission
is event-driven; a spinner would burn CPU/battery for the app's entire
idle life). Verified on the emulator and the phone: healthy runs show
ZERO frames across all idle windows (PERF-PRESENT fps < 1).

- perf: rows whose previous frame is >= 100ms away are idle gaps, not
  slow frames — flagged in the CSV (new gap column) and kept out of the
  logcat summary's latency percentiles (reported as gaps=N maxGap=...).
  A frame >= 2s after the previous one flushes the CSV, so a burst's
  rows are persisted the moment the next burst starts (an idle tail or
  force-stop no longer loses the last burst).
- editor: debug 'open <path>' command (cmd-file poller, perf mode):
  opens a file from any page via the same OpenFile path as a browser
  tap — deterministic, no pixel tapping.
- e2e: TestNoFramesWhileIdle (browser + editor after load/scroll/find)
  asserts the logic emits ZERO frames across an idle window once
  settled — the headless contract, in the regular go-test suite.
- scripts/profile_emulator.sh: drives launch, 8s idle, open (seeded
  4000-line file), 16s idle, 3 scrolls on a device/emulator; groups the
  CSV into phases at idle gaps >= 2s and FAILs on a phase over its frame
  budget (1/s spinner exceeds a 16s idle budget; faster ones balloon a
  phase or show in PERF-PRESENT). Validated both ways: PASS on a healthy
  build (emulator + phone), FAIL on an injected 500ms frame spinner.
- doc: architecture.md §11 updated (gap handling, burst flush, debug
  open, frame-regression guard, 2026-08 measurements).
This commit is contained in:
gmp
2026-08-20 14:18:08 -04:00
parent c789de4b44
commit ac1c32e4c0
5 changed files with 360 additions and 21 deletions
+22 -7
View File
@@ -358,7 +358,8 @@ func (l *Logic) emitFrame() {
}
// EnableDebugCmdPoll starts a background poller (debug-only) that watches
// <dir>/cmd for a one-shot scroll command and forwards it to the owner for
// <dir>/cmd for a one-shot debug command (see applyDebugCmd) and forwards
// it to the owner for
// application. Used to jump the editor to specific scroll offsets for
// performance/clamping validation. The poller does the (blocking) file read
// off the owner and sends the command via debugCmdC; the owner applies it.
@@ -396,18 +397,32 @@ func (l *Logic) EnableDebugCmdPoll(dir string) {
}
// applyDebugCmd applies a one-shot debug scroll command from the cmd-file
// poller. Commands: "top", "bottom", "frac <0..1>", "dp <int>". Must be
// called on the logic goroutine.
// poller. Commands: "open <path>" (any page), and, on the editor page,
// "top", "bottom", "frac <0..1>", "dp <int>". Must be called on the logic
// goroutine.
func (l *Logic) applyDebugCmd(cmd string) {
s := l.state
if s.page != EditorPage {
log.Printf("DebugCmd: %q ignored (not on editor page)", cmd)
return
}
fields := strings.Fields(cmd)
if len(fields) == 0 {
return
}
// "open <path>" works from any page: it opens the file and switches to
// the editor. The pre-release frame profile (scripts/profile_emulator.sh)
// uses it to open a known scrollable file deterministically instead of
// pixel-tapping the browser list.
if fields[0] == "open" {
if len(fields) < 2 {
log.Printf("DebugCmd: open needs a path")
return
}
OpenFile(fields[1])
l.emitFrame() // OpenFile only mutates state (the tap path emits via its handler)
return
}
if s.page != EditorPage {
log.Printf("DebugCmd: %q ignored (not on editor page)", cmd)
return
}
var target ui.Dp
switch fields[0] {
case "top":
+39 -8
View File
@@ -39,8 +39,16 @@ type Row struct {
TotalLines int
VisStart int
VisEnd int
Gap bool // DeltaMs is an idle gap, not frame latency (see gapThreshold)
}
// gapThreshold separates "the app was idle" from "a frame was slow": a
// gap of this length or more means no frames were emitted for that whole
// time, so the first frame of the next burst carries the entire idle period
// in DeltaMs. A genuinely slow frame on a real device is at most a few
// tens of ms.
const gapThreshold = 100 * time.Millisecond
// Profiler records logic-frame cadence plus context. All methods must be
// called from the owning goroutine only (no locks).
type Profiler struct {
@@ -110,6 +118,7 @@ func (p *Profiler) Record(ctx Ctx) {
TotalLines: ctx.TotalLines,
VisStart: ctx.VisStart,
VisEnd: ctx.VisEnd,
Gap: delta >= gapThreshold,
})
if now.Sub(p.lastLog) >= time.Second {
@@ -120,18 +129,40 @@ func (p *Profiler) Record(ctx Ctx) {
p.flush()
p.lastFlush = now
}
// Burst ended: persist immediately. The periodic flush above only runs
// inside Record, so without this an idle tail (or a force-stopped app)
// would lose the last burst's rows; the frame that opens a new burst is
// the moment the previous burst's rows become final.
if delta >= 2*time.Second {
p.flush()
p.lastFlush = now
}
}
// logSummary prints a rolling percentile summary of the frames buffered since
// the last flush to logcat.
// the last flush to logcat. Idle gaps are kept OUT of the latency
// percentiles (they are pauses between bursts of activity, not slow frames)
// and reported separately.
func (p *Profiler) logSummary() {
n := len(p.buf)
if n == 0 {
return
}
ds := make([]float64, n)
for i, r := range p.buf {
ds[i] = r.DeltaMs
gaps, maxGap := 0, 0.0
ds := make([]float64, 0, n)
for _, r := range p.buf {
if r.Gap {
gaps++
if r.DeltaMs > maxGap {
maxGap = r.DeltaMs
}
continue
}
ds = append(ds, r.DeltaMs)
}
if len(ds) == 0 {
log.Printf("PERF frames=%d (all idle gaps; max=%.0f ms)", n, maxGap)
return
}
p50, p90, p99, mx := percentiles(ds)
over16, over33 := 0, 0
@@ -143,16 +174,16 @@ func (p *Profiler) logSummary() {
over33++
}
}
log.Printf("PERF frames=%d p50=%.1f p90=%.1f p99=%.1f max=%.1f ms over16.7=%.0f%% over33.4=%.0f%%",
n, p50, p90, p99, mx, pct(over16, n), pct(over33, n))
log.Printf("PERF frames=%d p50=%.1f p90=%.1f p99=%.1f max=%.1f ms over16.7=%.0f%% over33.4=%.0f%% gaps=%d maxGap=%.0fms",
n, p50, p90, p99, mx, pct(over16, len(ds)), pct(over33, len(ds)), gaps, maxGap)
}
// flush appends the buffered rows to the CSV file and clears the buffer.
func (p *Profiler) flush() {
if len(p.buf) > 0 && p.file != nil {
for _, r := range p.buf {
fmt.Fprintf(p.file, "%d,%.3f,%.3f,%s,%.1f,%.1f,%d,%d,%d\n",
r.Seq, r.Tms, r.DeltaMs, r.Page, r.ScrollDP, r.MaxScrollDP, r.TotalLines, r.VisStart, r.VisEnd)
fmt.Fprintf(p.file, "%d,%.3f,%.3f,%s,%.1f,%.1f,%d,%d,%d,%v\n",
r.Seq, r.Tms, r.DeltaMs, r.Page, r.ScrollDP, r.MaxScrollDP, r.TotalLines, r.VisStart, r.VisEnd, r.Gap)
}
}
p.buf = p.buf[:0]
+111
View File
@@ -0,0 +1,111 @@
package e2e_test
import (
"strings"
"testing"
"time"
"pad/internal/editor"
"pad/internal/test/e2e"
"pad/internal/ui"
)
// TestNoFramesWhileIdle is the pre-release frame-regression guard. Frame
// emission is event-driven (architecture.md §2): once the logic goroutine
// has settled — every async result applied, every wrap-settle pass done —
// it must emit ZERO further frames while no input arrives. A non-zero
// delta means something is spinning (a ticker, a re-emission loop, a
// feedback ping-pong between layout and state) and would burn CPU and
// battery on a real device for the app's entire idle lifetime.
//
// The main-loop side (Gio presents) is measured by the same contract's
// on-device instrument: PERF-PRESENT logcat lines (cmd/pad, enabled by
// touching <sd>/PadPerf/enable; see scripts/profile_emulator.sh).
// waitFrameSettle returns the frame count once it has been unchanged for
// quietFor (the logic is quiescent). Fatals if it never settles.
func waitFrameSettle(t *testing.T, h *e2e.Harness, quietFor time.Duration) int {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
last := h.FrameCount()
lastChanged := time.Now()
for time.Now().Before(deadline) {
time.Sleep(50 * time.Millisecond)
if n := h.FrameCount(); n != last {
last, lastChanged = n, time.Now()
continue
}
if time.Since(lastChanged) >= quietFor {
return last
}
}
t.Fatal("frame count never settled within 10s")
return 0
}
// assertIdleFrames requires the frame count to be unchanged across an
// idleFor window that follows a settled (quietFor-stable) state.
func assertIdleFrames(t *testing.T, h *e2e.Harness, quietFor, idleFor time.Duration, phase string) {
t.Helper()
before := waitFrameSettle(t, h, quietFor)
time.Sleep(idleFor)
if after := h.FrameCount(); after != before {
t.Fatalf("%s: logic emitted %d frame(s) while idle (before=%d after=%d); emission must be event-driven",
phase, after-before, before, after)
}
}
// TestNoFramesWhileIdle_Browser: the file-browser page, fully loaded, must
// go completely quiet.
func TestNoFramesWhileIdle_Browser(t *testing.T) {
h := e2e.NewHarness()
h.Run()
defer h.Cleanup()
h.SendConfig(1080, 2400)
if _, err := h.WaitForFrameCount(1, 5*time.Second); err != nil {
t.Fatalf("no frames: %v", err)
}
assertIdleFrames(t, h, 300*time.Millisecond, time.Second, "browser")
}
// TestNoFramesWhileIdle_Editor: an open file after a load, a scroll, and a
// full find cycle (scan + navigate + close) must go completely quiet —
// the find settle machinery in particular must terminate, not re-trigger.
func TestNoFramesWhileIdle_Editor(t *testing.T) {
// 300 long lines: enough to scroll and to match a query at several
// positions.
var sb strings.Builder
for i := 0; i < 300; i++ {
sb.WriteString("line number 000: the quick brown fox jumps over the lazy dog by the river\n")
}
h, _ := realFileHarness(t, "idle.txt", sb.String())
defer h.Cleanup()
h.SendConfig(1080, 2400)
// Scroll (HandleScroll swallows input for 300ms after open).
time.Sleep(400 * time.Millisecond)
h.SendInput([]ui.InputEvent{{Handler: editor.HandleScroll, Data: 2000}})
// A full find cycle: open the bar, query, navigate, close.
h.SendInput([]ui.InputEvent{{Handler: editor.ToggleFind, Data: nil}})
h.Logic().FindQueryChan() <- "quick"
deadline := time.Now().Add(5 * time.Second)
for {
v, err := h.Inspect(func(st *editor.State) any { return len(st.Editor.Find.Matches) })
if err != nil {
t.Fatalf("Inspect: %v", err)
}
if v.(int) > 0 {
break
}
if time.Now().After(deadline) {
t.Fatal("find never matched")
}
time.Sleep(20 * time.Millisecond)
}
h.SendInput([]ui.InputEvent{{Handler: editor.FindNext, Data: nil}})
time.Sleep(100 * time.Millisecond)
h.SendInput([]ui.InputEvent{{Handler: editor.ToggleFind, Data: nil}})
assertIdleFrames(t, h, 300*time.Millisecond, time.Second, "editor")
}