diff --git a/cmd/groundstation-display/main_test.go b/cmd/groundstation-display/main_test.go index 1dcd471..f2e52dc 100644 --- a/cmd/groundstation-display/main_test.go +++ b/cmd/groundstation-display/main_test.go @@ -1,8 +1,13 @@ package main import ( + "bytes" + "context" "errors" + "fmt" "path/filepath" + "strings" + "sync" "testing" "time" @@ -162,6 +167,190 @@ func TestFormatDiagnosticRendersStructuredFields(t *testing.T) { } } +// harnessOpener mirrors the real opener's diagnostic contract: it emits +// the role's open record at Open and hands back a session that emits the +// first-redraw record on its first flush and the summary on close — all +// through the one shared emitter under test. +type harnessOpener struct { + diag *display.Diag + role string + session *harnessSession +} + +func (o harnessOpener) Open(context.Context) (display.Session, error) { + o.diag.Emit("open", o.role, "window=0x1") + return o.session, nil +} + +type harnessSession struct { + diag *display.Diag + role string + firstRed sync.Once +} + +func (s *harnessSession) Canvas() display.Canvas { return s } +func (s *harnessSession) Size() (int, int) { return 800, 600 } +func (s *harnessSession) Clear() {} +func (s *harnessSession) Text(int, int, string) {} +func (s *harnessSession) Flush() { + s.firstRed.Do(func() { s.diag.Emit("first_redraw", s.role, "trigger=initial") }) +} + +func (s *harnessSession) Draw(display.Canvas) { + s.Flush() +} + +func (s *harnessSession) WaitEvent(ctx context.Context) (bool, error) { + <-ctx.Done() + return false, ctx.Err() +} + +func (s *harnessSession) Close() error { + s.diag.EmitForced("summary", s.role, "flushes=1") + return nil +} + +// stalledOpener reproduces the device evidence: the open sequence emits +// its progress markers (open_begin, the stage marker for the next +// potentially blocking operation) and then never returns, while the other +// layer completes normally through the same shared emitter. +type stalledOpener struct { + diag *display.Diag + role string + stall chan struct{} + stages func(*display.Diag, string) +} + +func (o stalledOpener) Open(ctx context.Context) (display.Session, error) { + o.diag.Emit("open_begin", o.role) + o.stages(o.diag, o.role) + <-o.stall + return nil, fmt.Errorf("stalled open never returned") +} + +func TestRunLayersEmitsProgressRecordsBeforeAStalledOpen(t *testing.T) { + var buf bytes.Buffer + diag := display.NewDiag(&buf) + + stall := make(chan struct{}) + stalled := &harnessSession{diag: diag, role: "stalled"} + live := &harnessSession{diag: diag, role: "canvas"} + + progress := func(d *display.Diag, role string) { + d.Emit("open_begin", role) + d.Emit("open_stage", role, "stage=map_confirm") + } + layers := []display.Layer{ + { + Name: "stalled-osd", + Opener: stalledOpener{diag: diag, role: "osd", stall: stall, stages: progress}, + Template: stalled, + }, + { + Name: "fallback-canvas", + Opener: harnessOpener{diag: diag, role: "canvas", session: live}, + Template: live, + }, + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + display.RunLayers(ctx, layers) + close(done) + }() + + // The stall evidence must already be visible while the stalled open is + // in progress, and the collector must stay bounded. + waitForRecords(t, diag, func(records []string) bool { + return hasDiag(records, "kind=open_begin", "role=osd") && + hasDiag(records, "kind=open_stage", "role=osd", "stage=map_confirm") && + hasDiag(records, "kind=open", "role=canvas") && + hasDiag(records, "kind=first_redraw", "role=canvas") + }) + if len(diag.Records()) > 70 { + t.Fatalf("collector unbounded: %d distinct records", len(diag.Records())) + } + + close(stall) + cancel() + <-done +} + +func TestRunLayersCarriesOneSharedDiagToBothRoles(t *testing.T) { + // The value-copy regression pin: the same emitter wired into both + // real target layer structs must survive the RunLayers boundary so + // both roles' open, first-redraw and summary records reach one + // writer. Mirrors the real layer flow: the template draws through the + // session canvas, so one session instance owns the diagnostics. + var buf bytes.Buffer + diag := display.NewDiag(&buf) + + canvas := &harnessSession{diag: diag, role: "canvas"} + osd := &harnessSession{diag: diag, role: "osd"} + layers := []display.Layer{ + { + Name: "fallback-canvas", + Opener: harnessOpener{diag: diag, role: "canvas", session: canvas}, + Template: canvas, + }, + { + Name: "osd-overlay", + Opener: harnessOpener{diag: diag, role: "osd", session: osd}, + Template: osd, + }, + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + display.RunLayers(ctx, layers) + close(done) + }() + + waitForRecords(t, diag, func(records []string) bool { + return hasDiag(records, "kind=open", "role=canvas") && + hasDiag(records, "kind=open", "role=osd") && + hasDiag(records, "kind=first_redraw", "role=canvas") && + hasDiag(records, "kind=first_redraw", "role=osd") + }) + cancel() + <-done + + waitForRecords(t, diag, func(records []string) bool { + return hasDiag(records, "kind=summary", "role=canvas") && + hasDiag(records, "kind=summary", "role=osd") + }) +} + +// hasDiag reports whether one captured record line carries both tokens. +func hasDiag(records []string, tokens ...string) bool { + for _, line := range records { + match := true + for _, token := range tokens { + if !strings.Contains(line, token) { + match = false + } + } + if match { + return true + } + } + return false +} + +func waitForRecords(t *testing.T, diag *display.Diag, satisfied func([]string) bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if satisfied(diag.Records()) { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("records never reached the shared writer in the required combination: %v", diag.Records()) +} + func TestWireDiagnosticsTagsEveryLayerWithItsName(t *testing.T) { layers, err := buildTarget("x11", filepath.Join(t.TempDir(), "osd-state.bin"), nil) if err != nil { diff --git a/internal/display/diag.go b/internal/display/diag.go index 7e5cf48..0e7b195 100644 --- a/internal/display/diag.go +++ b/internal/display/diag.go @@ -89,9 +89,10 @@ func (d *Diag) emit(kind, role string, forced bool, fields ...string) { if d.last[key] == line { return } - d.last[key] = line } d.count++ + key := kind + "|" + role + d.last[key] = line if d.out != nil { fmt.Fprintln(d.out, line) } @@ -116,6 +117,18 @@ func diagValue(text string) string { // never bloat the journal stream. const diagValueMaxLen = 160 +// Records returns the most recent distinct record per key, for tests +// asserting what reached the writer. +func (d *Diag) Records() []string { + d.mu.Lock() + defer d.mu.Unlock() + out := make([]string, 0, len(d.last)) + for _, line := range d.last { + out = append(out, line) + } + return out +} + // VCSRevision returns the VCS revision the binary was built from, or // unknown when the build carried none. No other build or environment // metadata is exposed. diff --git a/internal/display/diag_test.go b/internal/display/diag_test.go index e3644b9..88dc1aa 100644 --- a/internal/display/diag_test.go +++ b/internal/display/diag_test.go @@ -24,6 +24,49 @@ func TestFormatDiagLineRendersTheExactStableSchema(t *testing.T) { } } +func TestDiagCapBudgetCoversBothRolesWorstCase(t *testing.T) { + // Worst-case record budget for both roles through one shared emitter: + // start, per role one open_begin, open, eight open stages, forced + // first_redraw, four query stages, query, up to three snapshot + // transitions, two video transitions, two stack targets, and the + // forced summary — everything distinct, nothing deduplicated. The + // total must stay under the cap so no stage, transition or summary is + // ever dropped in normal operation. + var buf bytes.Buffer + d := NewDiag(&buf) + + d.EmitForced("start", "", "pid=4321", "vcs=0123abcd") + for _, role := range []string{"canvas", "osd"} { + d.Emit("open_begin", role) + d.Emit("open", role, "window=0x600001") + for _, stage := range []string{"cursor", "window", "shapes", "map_confirm", + "presence", "wmctrl", "font_list", "font_query"} { + d.Emit("open_stage", role, "stage="+stage) + } + d.EmitForced("first_redraw", role, "trigger=initial") + for _, stage := range []string{"query_shape", "query_geom", "query_parent", "query_stack"} { + d.Emit("open_stage", role, "stage="+stage) + } + d.EmitForced("query", role, "shape=0x0+0+0") + d.Emit("snap", role, "state=none") + d.Emit("snap", role, "state=fresh") + d.Emit("snap", role, "state=stale") + d.Emit("video", role, "state=off") + d.Emit("video", role, "state=on") + d.Emit("stack", role, "target=top") + d.Emit("stack", role, "target=video/0x2c00002") + d.EmitForced("summary", role, "flushes=1") + } + + emitted := strings.Count(buf.String(), "\n") + if emitted != 49 { + t.Fatalf("emitted=%d want the full 49-record worst case within the cap", emitted) + } + if emitted > DiagCap { + t.Fatalf("emitted=%d exceeds the cap %d", emitted, DiagCap) + } +} + func TestDiagCollectCommandTargetsTheStableTagWithATailCap(t *testing.T) { // The documented collection command must filter the journal on the // stable tag and cap the output, so it stays pasteable. diff --git a/internal/display/x11.go b/internal/display/x11.go index 5556baa..e4ba2fe 100644 --- a/internal/display/x11.go +++ b/internal/display/x11.go @@ -430,6 +430,30 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { conn.Close() return nil, fmt.Errorf("allocate window: %w", err) } + // The open_begin marker is deduplicated by the emitter, so it is + // bounded to once per process and role no matter how often the layer + // reconnects. + if o.Diag != nil { + o.Diag.Emit("open_begin", roleName(o.Role)) + } + // Stage markers run through the same emitter; the session is not built + // until Open completes, so the pre-session stages close over the + // opener's emitter directly. + stage := func(name string) { + if o.Diag != nil { + o.Diag.Emit("open_stage", roleName(o.Role), "stage="+name) + } + } + stageDone := func(name string, err error) { + if o.Diag == nil { + return + } + if err != nil { + o.Diag.Emit("open_stage_done", roleName(o.Role), "stage="+name, "err="+diagValue(err.Error())) + return + } + o.Diag.Emit("open_stage_done", roleName(o.Role), "stage="+name, "ok") + } // The OSD overlay selects no device input even before its empty input // shape exists; the canvas keeps its legacy exposure-only mask. @@ -443,19 +467,24 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { // and the window still maps with the server default cursor — an // always-visible main window takes priority over cursor hiding, and a // cursor failure must never destroy or reconnect the display. + stage("cursor") cursor, cursorErr := blankCursor(conn, screen) if cursorErr != nil { + stageDone("cursor", cursorErr) log.Printf("blank cursor unavailable (%v); mapping with the default cursor", cursorErr) cursor = 0 + } else { } valueMask, values := createWindowValues(screen.BlackPixel, eventMask, cursor) // The window creation is checked at its own operation: a failure here // is reported exactly, and no dependent request — properties, shapes, // map, liveness — ever runs against an invalid window. + stage("window") if err := xproto.CreateWindowChecked(conn, screen.RootDepth, window, screen.Root, 0, 0, screen.WidthInPixels, screen.HeightInPixels, 0, xproto.WindowClassInputOutput, screen.RootVisual, valueMask, values).Check(); err != nil { + stageDone("window", err) // The window was never created: reclaim the connection (and the // live cursor with a best-effort free) exactly like the other // open failures, so reconnect attempts cannot leak either. @@ -509,7 +538,9 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { // server without the shape extension never gets the overlay at all, so // it can never present an unshaped frame over pilot video. if o.Role == RoleAbove { + stage("shapes") if err := applyTransparentShapes(conn, window); err != nil { + stageDone("shapes", err) conn.Close() return nil, err } @@ -520,10 +551,19 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { // destroy is video end. WFB and launcher processes are never consulted. xproto.ChangeWindowAttributes(conn, screen.Root, xproto.CwEventMask, []uint32{xproto.EventMaskSubstructureNotify}) + // The open record is emitted the moment the core window is created and + // mapped, from already-known identifiers and configured geometry: the + // actual client geometry and shape/parent/stack evidence follow in the + // first-flush query bundle. Emitting here guarantees the open evidence + // survives even if a later reply round trip stalls the open. + emitOpenRecord(o.Diag, o.Role, window, screen.Root, + screen.WidthInPixels, screen.HeightInPixels, o.RefreshInterval) // Round trip confirms the window is mapped and the server is alive; // the reply-bearing cookie is resolved with Reply (see // connLivenessProbe). + stage("map_confirm") if err := confirmMapped(connLivenessProbe(conn)); err != nil { + stageDone("map_confirm", err) conn.Close() return nil, err } @@ -531,6 +571,7 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { // A layer reconnect must never cover running video: if video windows // are already presented, record presence and take our side relative to // the topmost one before anything is drawn. + stage("presence") presence := o.presence() typeAtom := internWindowTypeAtom(conn) videoWindows := scanVideoWindows(conn, screen.Root, window, typeAtom, markerAtom) @@ -549,8 +590,11 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { // raises itself only after video ends, to bring the fallback back; the // OSD overlay is already above video. A missing wmctrl only degrades to // a plain window and must not kill the layer. - if err := o.applyFullscreen(x11FullscreenArgs(uint32(window), o.Role)); err != nil { - log.Printf("kiosk fullscreen state: %v (window stays a plain window)", err) + stage("wmctrl") + fullscreenErr := o.applyFullscreen(x11FullscreenArgs(uint32(window), o.Role)) + stageDone("wmctrl", fullscreenErr) + if fullscreenErr != nil { + log.Printf("kiosk fullscreen state: %v (window stays a plain window)", fullscreenErr) } gc, err := xproto.NewGcontextId(conn) @@ -565,6 +609,7 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { } // Prefer a Unicode font so the exact fallback text renders with its // diacritics; without one, drawn text degrades to ASCII. + stage("font_list") fontName, unicodeFont := selectFontName(conn) xproto.OpenFont(conn, font, uint16(len(fontName)), fontName) xproto.CreateGC(conn, gc, xproto.Drawable(window), @@ -575,11 +620,14 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { // needs the real glyph metrics; the canvas never punches shapes. ascent, descent, cell := osdFallbackFontMetrics() if o.Role == RoleAbove { + stage("font_query") if info, err := xproto.QueryFont(conn, xproto.Fontable(font)).Reply(); err == nil { ascent, descent = int16(info.FontAscent), int16(info.FontDescent) if width := int16(info.MaxBounds.CharacterWidth); width > 0 { cell = width } + } else { + stageDone("font_query", err) } } @@ -611,39 +659,36 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) { pollEvent: conn.PollForEvent, probe: connLivenessProbe(conn), } - s.recordOpen(o.RefreshInterval) return s, nil } -// recordOpen emits the one per-role open record: role, window and root -// identifiers, configured/root/client geometry, refresh interval, the EWMH -// type/state intent, and the initial shape intent. The one synchronous -// geometry round trip runs here, where first-open queries are allowed. -func (s *x11Session) recordOpen(refresh time.Duration) { - if s.diag == nil { +// emitOpenRecord emits the one per-role open record the moment the core +// window is created and mapped, from already-known identifiers, configured +// geometry and state intent. The actual client geometry and the +// shape/parent/stack evidence are deferred to the first-flush query +// bundle, so no extra blocking round trip is needed here and the open +// evidence survives even if a later reply round trip stalls the open. +func emitOpenRecord(diag *Diag, role LayerRole, window, root xproto.Window, width, height uint16, refresh time.Duration) { + if diag == nil { return } - clientGeom := "unknown" - if reply, err := xproto.GetGeometry(s.conn, xproto.Drawable(s.window)).Reply(); err == nil { - clientGeom = fmt.Sprintf("%dx%d+%d+%d", reply.Width, reply.Height, reply.X, reply.Y) - } - wmType := ewmhWindowTypeName(s.role) + wmType := ewmhWindowTypeName(role) if wmType == "" { wmType = "none" } shapeInit := "unshaped" - if s.role == RoleAbove { + if role == RoleAbove { shapeInit = "empty/empty" } - s.diag.Emit("open", roleName(s.role), - fmt.Sprintf("window=0x%x", s.window), - fmt.Sprintf("root=0x%x", s.root), - fmt.Sprintf("cfg=%dx%d", s.width, s.height), - fmt.Sprintf("root_geom=%dx%d", s.width, s.height), - "client_geom="+clientGeom, + diag.Emit("open", roleName(role), + fmt.Sprintf("window=0x%x", window), + fmt.Sprintf("root=0x%x", root), + fmt.Sprintf("cfg=%dx%d", width, height), + fmt.Sprintf("root_geom=%dx%d", width, height), + "client_geom=deferred", "refresh="+refresh.String(), "type="+wmType, - "wm_state="+strings.Join(fullscreenStateAtoms(s.role), "+"), + "wm_state="+strings.Join(fullscreenStateAtoms(role), "+"), "shape_init="+shapeInit, ) } @@ -918,16 +963,17 @@ type x11Session struct { // the snapshot state reported by the template, per-pass template // operation counts, bounded counters, and the last announced stack // target. All fields are touched only on the layer's own goroutine. - diag *Diag - queries xquery - lastTrigger string - diagSnap string - passOps int - flushes int - redraws int - errors int - firstFlush bool - lastStack string + diag *Diag + queries xquery + lastTrigger string + diagSnap string + passOps int + flushes int + redraws int + errors int + firstFlush bool + queryBundleDone bool + lastStack string // fontAscent, fontDescent and fontCell describe the drawn font so the // OSD overlay can punch its output shape around each text's glyph cell. fontAscent int16 @@ -1048,7 +1094,7 @@ func (s *x11Session) recordFlush(shapeErr error) { } else { fields = append(fields, "ok") } - s.diag.Emit("first_redraw", roleName(s.role), fields...) + s.diag.EmitForced("first_redraw", roleName(s.role), fields...) s.emitQueryBundle(roleName(s.role)) } @@ -1057,34 +1103,43 @@ func (s *x11Session) recordFlush(shapeErr error) { // records them with any errors attached. Best-effort: failures become // diagnostic fields, never layer failures. func (s *x11Session) emitQueryBundle(role string) { - if s.queries == nil { + if s.queries == nil || s.queryBundleDone { return } + s.queryBundleDone = true var fields, errs []string + s.stage("query_shape") if v, err := s.queries.ShapeExtents(s.window); err != nil { errs = append(errs, err.Error()) + s.stageDone("query_shape", err) } else { fields = append(fields, "shape="+v) } + s.stage("query_geom") if v, err := s.queries.Geometry(s.window); err != nil { errs = append(errs, err.Error()) + s.stageDone("query_geom", err) } else { fields = append(fields, "geom="+v) } + s.stage("query_parent") if v, err := s.queries.Parent(s.window); err != nil { errs = append(errs, err.Error()) + s.stageDone("query_parent", err) } else { fields = append(fields, "parent="+v) } + s.stage("query_stack") if pos, of, err := s.queries.StackPosition(s.window); err != nil { errs = append(errs, err.Error()) + s.stageDone("query_stack", err) } else { fields = append(fields, "stack="+pos+"/"+of) } if len(errs) > 0 { fields = append(fields, "err="+diagValue(strings.Join(errs, "; "))) } - s.diag.Emit("query", role, fields...) + s.diag.EmitForced("query", role, fields...) } // osdRegionBounds returns the union bounds of the drawn regions in @@ -1209,6 +1264,33 @@ func (s *x11Session) stackTarget() string { return fmt.Sprintf("video/0x%x", sibling) } +// openBegin announces a new open attempt for the role; the emitter +// deduplicates it, so it is bounded to once per process per role. +func (s *x11Session) openBegin() { + if s.diag != nil { + s.diag.Emit("open_begin", roleName(s.role)) + } +} + +// stage marks the start of one potentially blocking open operation, so a +// stalled open is identifiable from the journal by its last stage marker. +func (s *x11Session) stage(name string) { + if s.diag != nil { + s.diag.Emit("open_stage", roleName(s.role), "stage="+name) + } +} + +// stageDone records a FAILED stage completion; a stage that returns +// without error needs no completion record — success is implied by the +// next stage marker (or the final record). The error value is sanitized +// and bounded by the emitter. +func (s *x11Session) stageDone(name string, err error) { + if s.diag == nil || err == nil { + return + } + s.diag.Emit("open_stage_done", roleName(s.role), "stage="+name, "err="+diagValue(err.Error())) +} + // roleName names a layer role in diagnostics. func roleName(role LayerRole) string { if role == RoleAbove { diff --git a/internal/display/x11_test.go b/internal/display/x11_test.go index 76dfd59..0613261 100644 --- a/internal/display/x11_test.go +++ b/internal/display/x11_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "slices" "strconv" "strings" "sync/atomic" @@ -527,6 +528,104 @@ func (q *scriptedQueries) StackPosition(xproto.Window) (string, string, error) { return q.pos, q.of, nil } +func TestOpenStageMarkersAndCompletionRecords(t *testing.T) { + var buf bytes.Buffer + session := &x11Session{role: RoleAbove, diag: NewDiag(&buf)} + + // One pre-operation marker per stage; a successful stage emits no + // completion record — success is implied by the next marker or the + // final record. + session.stage("font_list") + session.stageDone("font_list", nil) + session.stageDone("cursor", errors.New("bad\nthing")) + + lines := strings.Split(strings.TrimSpace(buf.String()), "\n") + if len(lines) != 2 { + t.Fatalf("lines=%v want the font_list marker and the sanitized cursor failure only", lines) + } + if !strings.Contains(lines[0], "display_diag kind=open_stage role=osd stage=font_list") { + t.Fatalf("marker=%q", lines[0]) + } + if !strings.Contains(lines[1], "kind=open_stage_done") || + !strings.Contains(lines[1], "stage=cursor") || !strings.Contains(lines[1], "err=bad thing") { + t.Fatalf("failure=%q want the sanitized error completion", lines[1]) + } +} + +func TestOpenBeginIsEmittedOncePerRole(t *testing.T) { + var buf bytes.Buffer + session := &x11Session{role: RoleAbove, diag: NewDiag(&buf)} + + session.openBegin() + session.openBegin() + session.openBegin() + + if strings.Count(buf.String(), "\n") != 1 { + t.Fatalf("buf=%q want one bounded open_begin record per role", buf.String()) + } + if !strings.Contains(buf.String(), "display_diag kind=open_begin role=osd") { + t.Fatalf("buf=%q want the open_begin record", buf.String()) + } +} + +func TestEmitQueryBundleStageMarksEachQueryOnce(t *testing.T) { + // Each bundle query can block on a reply: its stage marker must be + // emitted before the query, with failures recorded, and the whole + // bundle is once-only per session and deduplicated on repeat calls. + var buf bytes.Buffer + session := &x11Session{ + role: RoleAbove, + diag: NewDiag(&buf), + window: 0x600001, + queries: &scriptedQueries{shape: "0x0+0+0", geom: "1920x1080+0+26", parent: "0x1a00001", pos: "1", of: "3"}, + } + + session.emitQueryBundle("osd") + + for _, stage := range []string{"query_shape", "query_geom", "query_parent", "query_stack"} { + if !strings.Contains(buf.String(), "stage="+stage) { + t.Fatalf("buf=%q missing stage marker %q", buf.String(), stage) + } + } + session.emitQueryBundle("osd") + + // Bounded: one bundle emits four stage markers and one query record, + // and the once-only guard adds nothing on a second call. + if got := strings.Count(buf.String(), "kind=query"); got != 1 { + t.Fatalf("query records=%d want exactly one", got) + } + if got := strings.Count(buf.String(), "kind=open_stage"); got != 4 { + t.Fatalf("stage markers=%d want exactly four", got) + } +} + +func TestForcedEvidenceSurvivesACapFilledByReconnectStorms(t *testing.T) { + // Reconnect storms with varying error strings must never consume the + // evidence budget: first_redraw and the query bundle are forced and + // reach the writer even when every ordinary record slot is spent. + var buf bytes.Buffer + session := &x11Session{ + role: RoleAbove, + diag: NewDiag(&buf), + video: NewVideoPresence(), + lastTrigger: "initial", + queries: &scriptedQueries{shape: "0x0+0+0", geom: "1920x1080+0+26", parent: "0x1a00001", pos: "1", of: "3"}, + } + session.diag.cap = 4 + + for i := 0; i < 10; i++ { + session.diag.Emit("reconnect", "osd", fmt.Sprintf("event=open_failed"), fmt.Sprintf("error=variant %d", i)) + } + + session.recordFlush(nil) + session.emitQueryBundle("osd") + + lines := buf.String() + if !strings.Contains(lines, "kind=first_redraw") || !strings.Contains(lines, "kind=query") { + t.Fatalf("buf=%q must carry the forced first_redraw and query records", lines) + } +} + func TestRecordFlushEmitsFirstRedrawAndQueryBundleOnce(t *testing.T) { var buf bytes.Buffer presence := NewVideoPresence() @@ -552,19 +651,38 @@ func TestRecordFlushEmitsFirstRedrawAndQueryBundleOnce(t *testing.T) { session.recordFlush(nil) // the bundle and the first-redraw record are once-only lines := strings.Split(strings.TrimSpace(buf.String()), "\n") - if len(lines) != 2 { - t.Fatalf("lines=%v want exactly the first_redraw and query records", lines) - } + // Once-only per session: one first_redraw record, four query stage + // markers, one query record — successful stages emit no completion + // record (success is implied by the next marker/final record). wantFirst := "display_diag kind=first_redraw role=osd trigger=initial ops=0 regions=3 bounds=196x82+30+19 snap=none video=off stack=top ok" - if lines[0] != wantFirst { - t.Fatalf("first_redraw=%q want %q", lines[0], wantFirst) + if len(lines) != 6 || lines[0] != wantFirst { + t.Fatalf("lines=%v (n=%d) want the first flush evidence with %q first", lines, len(lines), wantFirst) + } + if strings.Count(buf.String(), "kind=query") != 1 { + t.Fatalf("buf=%q want exactly one query record", buf.String()) } wantQuery := "display_diag kind=query role=osd shape=196x106+28+15 geom=1920x1080+0+26 parent=0x1a00001 stack=1/3" - if lines[1] != wantQuery { - t.Fatalf("query=%q want %q", lines[1], wantQuery) + if !slices.Contains(lines, wantQuery) { + t.Fatalf("query=%q want %q among %v", lines[9], wantQuery, lines) } } +// hasDiag reports whether one captured record line carries all tokens. +func hasDiag(lines []string, tokens ...string) bool { + for _, line := range lines { + match := true + for _, token := range tokens { + if !strings.Contains(line, token) { + match = false + } + } + if match { + return true + } + } + return false +} + func TestRecordFlushReportsShapeErrorsWithoutBlockingTheLayer(t *testing.T) { var buf bytes.Buffer session := &x11Session{ @@ -577,19 +695,21 @@ func TestRecordFlushReportsShapeErrorsWithoutBlockingTheLayer(t *testing.T) { // The shape error arrives with the first flush: it must be carried by // the first_redraw record and the query bundle reports its own query - // failure alongside. + // failure alongside, with stage markers around every bundle query. session.recordFlush(errors.New("bounding shape: BadWindow")) session.recordFlush(nil) lines := strings.Split(strings.TrimSpace(buf.String()), "\n") - if len(lines) != 2 { - t.Fatalf("lines=%v want the first_redraw error record and the query error record", lines) - } if !strings.Contains(lines[0], "ok=no") || !strings.Contains(lines[0], "err=bounding shape: BadWindow") { t.Fatalf("first_redraw=%q must carry the shape error", lines[0]) } - if !strings.Contains(lines[1], "err=") { - t.Fatalf("query=%q must carry the query error", lines[1]) + if !hasDiag(lines, "kind=query", "err=BadWindow") { + t.Fatalf("lines=%v: the query record must carry the query error", lines) + } + for _, stage := range []string{"query_shape", "query_geom", "query_parent", "query_stack"} { + if !strings.Contains(buf.String(), "stage="+stage) { + t.Fatalf("buf=%q missing stage marker %q", buf.String(), stage) + } } }