perf: default-off in-app profiler + debug scroll jumps; verify scroll perf & clamping

internal/perf: single-goroutine profiler (no locks). When enabled by the
/storage/emulated/0/PadPerf/enable marker it records one CSV row per logic
frame (seq, ms, frame delta, page, scroll Dp, max-scroll Dp, total lines,
visible byte range), logs a rolling ~1/s summary, and on Stop reports
nearest-rank p50/p90/p99/max. Flushes per row-batch but never fsyncs per
flush (avoids periodic hitches in the logic path).

editor: PerfRecord package-level hook (nil when off) + ProbeRecord;
Logic.emitFrame() now centralizes every frame emission so the profiler sees
each logic frame exactly once, on the owner goroutine. State gains
VisibleStart/VisibleEnd so the probe can confirm shaping stays
viewport-bounded.

logic: optional debug cmd poller (off by default) watches <dir>/cmd as a
one-shot file (top/bottom/frac <0..1>/dp <int>) and the owner applies a
clamped [0,MaxScroll] jump + frame. Enables deterministic large-offset scroll
tests without pixel taps.

main: wires the profiler when the marker file exists; logs present-fps
every 2s; stops the profiler on Destroy.

docs: README package inventory (add internal/perf); architecture §11
profiler facility; spec §5 invariant 7 (scroll always clamped to
[0,maxScroll]) + §6 measured rows; development_plan v5 + Phase 6 results.

Verified: go build/vet + full -race green. On-device 10 MB file:
logic-frame cadence flat across offsets 0.02->1.0 (no large-offset
degradation), visible byte range <=4.3 KB at every offset, clamping exact
across 2->130,955-line files, PSS plateaus ~250 MB (bounded, no leak);
profiler overhead negligible.
This commit is contained in:
gmp
2026-08-16 16:53:28 -04:00
parent 5271092c21
commit be48ad8157
10 changed files with 627 additions and 46 deletions
+158 -27
View File
@@ -2,6 +2,10 @@ package editor
import (
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
@@ -51,23 +55,25 @@ type ResultEvent struct {
// the channels below. The only exception is Inspect, a test-only request
// channel whose fn still executes on the owner.
type Logic struct {
state *State
browserManager *browser.BrowserManager
configChan chan ConfigUpdate
frameChan chan Frame // frames carry the view-state snapshot
inputChan chan []ui.InputEvent
layoutChan chan ui.GlyphLayout
resultChan chan ResultEvent
searchQueryChan chan string
openFileChan chan string
retryChan chan string // auto-save retries
autosaveChan chan struct{} // auto-save debounce ticks (timer -> owner)
inspectChan chan *inspectReq
workerPool *pool.WorkerPool
mockFS pool.FileSystem
done chan struct{}
exitWg sync.WaitGroup
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
state *State
browserManager *browser.BrowserManager
configChan chan ConfigUpdate
frameChan chan Frame // frames carry the view-state snapshot
inputChan chan []ui.InputEvent
layoutChan chan ui.GlyphLayout
resultChan chan ResultEvent
searchQueryChan chan string
openFileChan chan string
retryChan chan string // auto-save retries
autosaveChan chan struct{} // auto-save debounce ticks (timer -> owner)
inspectChan chan *inspectReq
workerPool *pool.WorkerPool
mockFS pool.FileSystem
done chan struct{}
exitWg sync.WaitGroup
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
lastEmit time.Time // time of the last frame emission (profiler cadence)
debugCmdC chan string // one-shot debug commands from the cmd-file poller; nil = disabled
}
// NewLogic creates a new Logic instance, accepting an optional mockFS.
@@ -127,8 +133,6 @@ func (l *Logic) FrameChan() <-chan Frame {
return l.frameChan
}
// InputChan returns the input channel for the logic goroutine.
func (l *Logic) InputChan() chan<- []ui.InputEvent {
return l.inputChan
@@ -169,7 +173,7 @@ func (l *Logic) Run() {
case update := <-l.configChan:
log.Printf("Logic: ConfigEvent")
update.apply(l.state)
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
case layout := <-l.layoutChan:
// Store the full GlyphLayout on editor state.
// Derive LastLineY from it for scroll clamping.
@@ -181,14 +185,14 @@ func (l *Logic) Run() {
}
if derivedLastLineY != l.state.LastLineY {
l.state.LastLineY = derivedLastLineY
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
}
case events := <-l.inputChan:
log.Printf("Logic: InputEvents")
for _, evt := range events {
evt.Handler(evt.Data)
}
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
case query := <-l.searchQueryChan:
log.Printf("Logic: SearchQuery")
if query != l.state.Browser.Query {
@@ -197,7 +201,7 @@ func (l *Logic) Run() {
browser.HandleSearch(&l.state.Browser, query)
}
}
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
case path := <-l.openFileChan:
log.Printf("Logic: OpenFileChan %s", path)
// Create chunked buffer for virtual scrolling
@@ -241,11 +245,138 @@ func (l *Logic) Run() {
case res := <-l.workerPool.ResultChan():
l.handleWorkerResult(res)
case <-l.resultChan:
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
case cmd := <-l.debugCmdC:
l.applyDebugCmd(cmd)
}
}
}
// emitFrame computes the current frame, records a profiler probe (if enabled),
// and hands it to the main goroutine. Centralizing emission here ensures the
// in-app profiler (PerfRecord) sees every frame exactly once, on the owner
// goroutine. Must be called on the logic goroutine.
func (l *Logic) emitFrame() {
elems := l.state.layout(l.browserManager)
now := time.Now()
if PerfRecord != nil {
var delta time.Duration
if !l.lastEmit.IsZero() {
delta = now.Sub(l.lastEmit)
}
l.lastEmit = now
s := l.state
rec := ProbeRecord{T: now, DeltaMs: float64(delta.Nanoseconds()) / 1e6, Page: pageName(s.page)}
if s.page == EditorPage {
rec.ScrollDP = float32(s.ScrollOffset)
rec.MaxScrollDP = float32(s.MaxScroll)
rec.VisStart = s.VisibleStart
rec.VisEnd = s.VisibleEnd
if cb := s.Editor.ChunkedBuffer; cb != nil {
if li := cb.LineIndex; li != nil {
rec.TotalLines = li.LineCount()
}
}
} else {
rec.ScrollDP = float32(s.Browser.ScrollOffset)
}
PerfRecord(rec)
}
l.frameChan <- l.frameOf(elems)
}
// EnableDebugCmdPoll starts a background poller (debug-only) that watches
// <dir>/cmd for a one-shot scroll command 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.
func (l *Logic) EnableDebugCmdPoll(dir string) {
l.debugCmdC = make(chan string, 1)
l.exitWg.Add(1)
go func() {
defer l.exitWg.Done()
t := time.NewTicker(120 * time.Millisecond)
defer t.Stop()
cmdPath := filepath.Join(dir, "cmd")
for {
select {
case <-l.done:
return
case <-t.C:
b, err := os.ReadFile(cmdPath)
if err != nil {
continue
}
cmd := strings.TrimSpace(string(b))
if cmd == "" {
continue
}
// Consume the command so it is applied exactly once.
_ = os.WriteFile(cmdPath, nil, 0o644)
select {
case l.debugCmdC <- cmd:
case <-l.done:
return
}
}
}
}()
}
// 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.
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
}
var target ui.Dp
switch fields[0] {
case "top":
target = 0
case "bottom":
target = s.MaxScroll
case "frac":
if len(fields) < 2 {
return
}
f, err := strconv.ParseFloat(fields[1], 64)
if err != nil || f < 0 || f > 1 {
log.Printf("DebugCmd: bad frac %q", fields[1])
return
}
target = ui.Dp(float64(f) * float64(s.MaxScroll))
case "dp":
if len(fields) < 2 {
return
}
n, err := strconv.Atoi(fields[1])
if err != nil {
log.Printf("DebugCmd: bad dp %q", fields[1])
return
}
target = ui.Dp(n)
default:
log.Printf("DebugCmd: unknown %q", cmd)
return
}
if target < 0 {
target = 0
}
if target > s.MaxScroll {
target = s.MaxScroll
}
s.ScrollOffset = target
log.Printf("DebugCmd: %q -> scroll=%d maxScroll=%d", cmd, int(s.ScrollOffset), int(s.MaxScroll))
l.emitFrame()
}
// fullContentBytes reconstructs the full file content from the chunked
// buffer (or the deprecated full Buffer). Returns ok=false on error.
// Must be called on the logic goroutine.
@@ -330,7 +461,7 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
l.state.Editor.TooLarge = true
l.state.Editor.TooLargeSize = stat.Size
log.Printf("Logic: %s is %d bytes, exceeds the %d-byte edit limit", stat.Path, stat.Size, MaxEditableFileSize)
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
return
}
if l.state.Editor.ChunkedBuffer != nil {
@@ -375,7 +506,7 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
})
}
}
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
l.emitFrame()
}
// applyBuildIndexResult applies a completed BuildIndexTask result to browser state.
@@ -405,7 +536,7 @@ func (l *Logic) PruneMaps() {
return
}
// Simply clear the maps for now. A true LRU would require
// Simply clear the maps for now. A true LRU would require
// tracking access times.
l.state.Editor.fileVersion = make(map[string]int)
l.state.Editor.lastWriteVersion = make(map[string]int)
+30
View File
@@ -0,0 +1,30 @@
package editor
import "time"
// ProbeRecord captures per-frame context for the in-app profiler (see
// internal/perf). It is filled on the logic goroutine and handed to the
// PerfRecord hook once per frame emission. Debug-only: PerfRecord is nil
// unless the app enables profiling (cmd/pad), so the per-frame cost is a
// single nil check.
type ProbeRecord struct {
T time.Time
DeltaMs float64 // ms since the previous frame emission
Page string // "editor" | "browser"
ScrollDP float32 // editor scroll offset (Dp); browser scroll when on browser
MaxScrollDP float32 // editor max scroll (Dp)
TotalLines int
VisStart int // visible byte range start
VisEnd int // visible byte range end (exclusive)
}
// PerfRecord is an optional per-frame probe hook, set by the app when in-app
// profiling is enabled. It is called on the logic goroutine, once per frame.
var PerfRecord func(ProbeRecord)
func pageName(p Page) string {
if p == EditorPage {
return "editor"
}
return "browser"
}
+19 -10
View File
@@ -133,15 +133,20 @@ func (e *EditorState) IncrementRetryAttempts(filename string) int {
// State holds all application state owned by the logic goroutine.
type State struct {
PixelWidth int // raw pixel width from Gio ConfigEvent
PixelHeight int // raw pixel height from Gio ConfigEvent
scale float32
page Page // current page (Browser or Editor)
WordWrap bool
ScrollOffset ui.Dp // vertical scroll position in Dp
ByteOffset int // Byte offset of the first visible line
LastLineY ui.Dp // last line baseline offset from text origin, from renderer
MaxScroll ui.Dp // max scroll offset (content height - viewport height)
PixelWidth int // raw pixel width from Gio ConfigEvent
PixelHeight int // raw pixel height from Gio ConfigEvent
scale float32
page Page // current page (Browser or Editor)
WordWrap bool
ScrollOffset ui.Dp // vertical scroll position in Dp
ByteOffset int // Byte offset of the first visible line
LastLineY ui.Dp // last line baseline offset from text origin, from renderer
MaxScroll ui.Dp // max scroll offset (content height - viewport height)
// VisibleStart/VisibleEnd are the byte range the last editor layout shaped
// for the viewport. Set by EditorLayout each frame; read by the profiler
// probe to confirm the shaped range stays viewport-bounded (not the file).
VisibleStart int
VisibleEnd int
FocusedElementID string // ID of the currently focused element
Elems []ui.Element
lastEvictionTime time.Time // Throttles chunk eviction
@@ -929,13 +934,17 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
// Content() will load chunks immediately needed by the viewport.
cb.Prefetch(scrollChunk, 1)
} else {
fmt.Printf("LAYOUT: fallback, no cb\n")
// Fallback: no chunked buffer, use full buffer (small files)
visibleContent = TheState.Editor.Buffer
visibleCursorPos = TheState.Editor.CursorPosition
visibleScrollOffset = TheState.ScrollOffset
}
// Record the shaped visible range for the profiler probe (confirms the
// virtual-scroll window stays viewport-bounded, not the whole file).
TheState.VisibleStart = start
TheState.VisibleEnd = end
// Record the visible window for IME: the snippet is this window, so an
// EditEvent.Range (relative to the window) is offset by IMEWindowStartByte
// to address the buffer. start is 0 for small (string) files, so the