RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
scene graph plan, stage 3: repeatable cost gate, hardware checklist, leftovers
oxydizer35acc85c3864
diff --git a/TESTING.md b/TESTING.mdindex 2912299..0596f51 100644--- a/TESTING.md+++ b/TESTING.md@@ -59,6 +59,14 @@ compiler, `wayland-scanner` and wayland-protocols; D-Bus suites need PyGObject,builds/tests stopped. Both counters and timers are enabled, so compare theseruns with each other, not the harness's `clean` mode. Read the saved resultswith `--report /tmp/scene-cost.json`.+- `python3 tests/scene_ab.py --binary <measurement build>`: the stage 3 cost+ gate. One compositor alternates the legacy and owned output presenters every+ 32 frames, so both share clocks and thermal state; it reports legacy → owned+ build CPU, build + commit and GPU time per scale and repaint and exits 1 if any+ cell exceeds the tolerance (`--tolerance`, default +5 %). Needs a build with+ `tests/scene_ab.patch` applied to a throwaway copy of the tree (the hook must+ never ship); the docstring has the exact steps. Use it instead of the paired+ mode for differences under about 10 %. Keep AC power and stop other work.- `REDIWM_*_PREVIEW=/tmp/...` (lock, greeter, OSD, settings, switcher, tray,notification): keep the compositor's own screenshots.- GLES2 at a fractional scale can differ by one level depending on renderdiff --git a/docs/plans/scene-graph-stage3.md b/docs/plans/scene-graph-stage3.mdindex 0648cde..e1ba892 100644--- a/docs/plans/scene-graph-stage3.md+++ b/docs/plans/scene-graph-stage3.md@@ -371,6 +371,21 @@ The CPU margin is thin (0.6 points; run-to-run noise on the ratio is about 1.5points), so repeat the frame-block A/B whenever the pass or the entry loop changes.Later stages are judged against the stage 0 baseline, not this tolerance.+**Repeating the check.** `tests/scene_ab.patch` adds the alternation hook to a+throwaway copy of the tree (it is a test hook, so it is never applied to the real+one) and `tests/scene_ab.py` drives it and applies the tolerance:++```sh+mkdir /tmp/ab && git archive HEAD | tar -x -C /tmp/ab+(cd /tmp/ab && git apply <repo>/tests/scene_ab.patch && zig build -Doptimize=ReleaseSafe)+WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128 python3 tests/scene_ab.py --binary /tmp/ab/zig-out/bin/rediwm+```++The procedure was checked on a fresh export of the committed tree: it builds+without further setup, the runner refuses an unpatched binary, and a scale 1.5 /+glass cell read build CPU +3.5 %, GPU +0.3 % (pass), in line with the figures+above on a machine now in the balanced power profile.+## Remaining stage 3 work* Cost is settled by the **Gate decision** above. Batching clip rectangles into@@ -378,8 +393,45 @@ Later stages are judged against the stage 0 baseline, not this tolerance.headroom.* Hardware qualification remains: an actual DRM plane and out-timeline release,and hotplug on that backend. A nested or headless session cannot show either,- and the live session holds DRM master. NV12 through the external program is- covered on this Intel node (see Verification); other drivers' YUV conversion- and tiled or compressed modifiers are not.+ and the live session holds DRM master, so it has to be run from a spare VT+ (checklist below). NV12 through the external program is covered on this Intel+ node (see Verification); other drivers' YUV conversion and tiled or compressed+ modifiers are not.+* Per-surface dmabuf feedback tranches are still absent, exactly as in the legacy+ presenter (stage 0 inventory); adding them is a feature, not parity, and waits+ for stage 6.+* Failures that also occur on HEAD stay out of this stage: the `window_corners`+ focus-border flake, the lock protocol test, the Xwayland titlebar 41 vs 35,+ desktop zoom's client coordinate, the screencast log message, `glass_hold`'s+ drag/reference comparison and the ReleaseSafe D-Bus unit test. Stage 4 rewrites+ the border and footer paths several of them test, so fix them there.* Keep the selector until the remaining migration stages have passed. Stage 4adds clip groups and primitives; stage 5 moves backdrop blur into this pass.++## Hardware qualification checklist++Not run: it needs DRM master. From a spare VT (Ctrl+Alt+F3), log in as the same+user and start the compositor with a copy of the config that adds+`scene_renderer = "owned"` under `[compositor]` (point `REDIWM_CONFIG` at the+copy). Logs are at debug level, so everything below is in the compositor log.++1. **Starts and draws.** The log says `scene renderer: owned GLES2 output pass`+ and no `scene commit failed`; wallpaper, taskbar, a Files window and glass+ render as on the legacy path.+2. **Plane scanout.** Run a fullscreen opaque client (a video player or `vkcube`):+ `Direct scan-out enabled` appears, and `disabled` again when a translucent+ window or the cursor-over-UI case breaks the condition. Check the picture does+ not tear or freeze across the switch.+3. **Out-timeline release.** While scanning out, the client keeps its frame rate+ (it would stall at two buffers if release points were lost); a 60 s run with+ `vkcube` or a video should finish without the client blocking.+4. **Hotplug.** Plug and unplug an external display, and change its mode and+ scale from Settings: windows move, the other output keeps drawing, and+ neither `scene commit failed` nor a crash appears.+5. **Lock and suspend.** Lock, suspend and resume once; the lock covers every+ output before anything else is shown.+6. **Idle.** After a minute untouched, `rediwm-msg perf` shows no commits, as on+ the legacy path.++Record the result here when done. Any failure on the owned path that the legacy+path does not show blocks making `owned` the default.diff --git a/tests/scene_ab.patch b/tests/scene_ab.patchnew file mode 100644index 0000000..c4fbbb0--- /dev/null+++ b/tests/scene_ab.patch@@ -0,0 +1,198 @@+diff --git a/src/Output.zig b/src/Output.zig+index 1f5a431..2fdf8a7 100644+--- a/src/Output.zig++++ b/src/Output.zig+@@ -1280,6 +1280,7 @@ fn runFrame(output: *Output) void {+ const mini_map_animating = output.server.world.mini_map.tick(output, now_ms);+ // GPU timestamps enclose glass capture/blur plus the scene submission.+ // Polling happens later; no glFinish or synchronous query-result reads.++ @import("ab.zig").advance();+ const gpu_active = if (output.server.gpu_timer) |timer| timer.begin() else false;+ const glass_started = stats.nowNs();+ const lock_animating = output.lock_view.sync(output);+@@ -1328,6 +1329,7 @@ fn runFrame(output: *Output) void {+ }+ const commit_duration = stats.nowNs() -% started;+ stats.global_stats.scene_commit_cpu.record(commit_duration);++ if (should_commit) @import("ab.zig").recordCommit(commit_duration);+ if (!committed) {+ log.err("handleFrame: scene commit failed for {s}", .{output.wlr_output.name});+ stats.recordFailedCommit();+diff --git a/src/Server.zig b/src/Server.zig+index dd3b562..b35f248 100644+--- a/src/Server.zig++++ b/src/Server.zig+@@ -458,7 +458,8 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:+ // measurements; every glass call already accepts a null engine.+ server.glass_engine = if (environ.getPosix("REDIWM_NO_GLASS") != null) null else glass.Engine.create(renderer, wlr_allocator, scene, server.read_fence);+ errdefer glass.Engine.destroy(server.glass_engine);+- if (loaded.compositor.scene_renderer == .owned) {++ if (environ.getPosix("REDIWM_TEST_AB") != null) @import("ab.zig").enabled = true;++ if (loaded.compositor.scene_renderer == .owned or @import("ab.zig").enabled) {+ server.output_renderer = scene_output_mod.Renderer.create(renderer) orelse return error.RendererInitFailed;+ log.info("scene renderer: owned GLES2 output pass", .{});+ }+@@ -1041,9 +1042,19 @@ pub fn deinit(server: *Server) void {+ /// All output builds, including capture between frames, use the selected+ /// presenter and the same swapchain/damage history. Commits stay on Output.+ pub fn buildOutputState(server: *Server, output: *wlr.SceneOutput, state: *wlr.Output.State) bool {+- if (server.output_renderer) |renderer|+- return renderer.buildState(server.world.projection, output, state);+- return output.buildState(state, null);++ const ab = @import("ab.zig");++ const use_owned = if (ab.enabled) ab.cur == 1 else server.output_renderer != null;++ const w0 = @import("ipc/stats.zig").nowNs();++ const c0 = ab.threadCpuNs();++ const ok = if (use_owned)++ server.output_renderer.?.buildState(server.world.projection, output, state)++ else++ output.buildState(state, null);++ if (ab.enabled and ab.warm) {++ ab.record(.build_cpu, ab.cur, ab.threadCpuNs() -% c0);++ ab.record(.build_wall, ab.cur, @import("ipc/stats.zig").nowNs() -% w0);++ }++ return ok;+ }++ pub fn beginRenderPass(server: *Server, buffer: *wlr.Buffer, options: ?*const wlr.Renderer.BufferPassOptions) !*wlr.RenderPass {+diff --git a/src/ab.zig b/src/ab.zig+new file mode 100644+index 0000000..d382bf6+--- /dev/null++++ b/src/ab.zig+@@ -0,0 +1,78 @@++// MEASUREMENT PATCH, never part of a production build (see tests/scene_ab.py).++// Applied to a throwaway copy of the tree, it makes one compositor build++// alternate frames between the legacy and the owned output presenter in blocks++// of `block` frames, drops the first `warmup` frames of every block, and records++// per presenter: thread CPU and wall time of the build call, wall time of build++// plus commit, and GPU elapsed (the timer's generation word carries the tag).++// Both arms share the process, clocks, thermal and power state, so drift cancels.++// One summary of `cap` samples per presenter and metric is logged at warn level,++// as "AB <metric>: legacy mean .. | owned mean .. (ns, n=..)". Selected by++// REDIWM_TEST_AB, which only a patched build reads.++const std = @import("std");++const log = std.log.scoped(.ab);++++pub var enabled = false;++var frame: u64 = 0;++pub var cur: u1 = 0; // 1 = owned, 0 = legacy++pub var warm = false;++pub const mask: u64 = 0x0fff_ffff_ffff_ffff;++pub const Kind = enum { build_cpu, build_wall, commit_wall, gpu };++const cap = 3000;++var samples: [4][2][cap]u32 = undefined;++var counts = [_][2]usize{.{ 0, 0 }} ** 4;++var reported = false;++++const block = 32;++const warmup = 6;++++/// Call once per frame before the GPU timer begins.++pub fn advance() void {++ if (!enabled) return;++ frame += 1;++ cur = @intCast((frame / block) % 2);++ warm = frame % block >= warmup;++}++++/// Build plus commit wall time of a frame that committed.++pub fn recordCommit(ns: u64) void {++ if (enabled and warm) record(.commit_wall, cur, ns);++}++pub fn tag() u64 {++ if (!enabled) return 0;++ return (@as(u64, cur) | (@as(u64, @intFromBool(warm)) << 1)) << 60;++}++pub fn threadCpuNs() u64 {++ var ts: std.posix.timespec = undefined;++ _ = std.posix.system.clock_gettime(std.posix.CLOCK.THREAD_CPUTIME_ID, &ts);++ return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec));++}++pub fn record(kind: Kind, presenter: u1, ns: u64) void {++ const k = @intFromEnum(kind);++ const n = &counts[k][presenter];++ if (n.* >= cap) return;++ samples[k][presenter][n.*] = @intCast(@min(ns, std.math.maxInt(u32)));++ n.* += 1;++ maybeReport();++}++fn maybeReport() void {++ if (reported) return;++ for (counts) |c| if (c[0] < cap or c[1] < cap) return;++ reported = true;++ inline for (.{ .build_cpu, .build_wall, .commit_wall, .gpu }) |kind| {++ const k = @intFromEnum(@as(Kind, kind));++ var stat: [2][4]u64 = undefined;++ for (0..2) |p| {++ const s = samples[k][p][0..cap];++ std.mem.sort(u32, s, {}, std.sort.asc(u32));++ var sum: u64 = 0;++ for (s) |v| sum += v;++ stat[p] = .{ sum / cap, s[cap / 2], s[cap / 10], s[cap * 9 / 10] };++ }++ log.warn("AB {s}: legacy mean {d} med {d} p10 {d} p90 {d} | owned mean {d} med {d} p10 {d} p90 {d} (ns, n={d})", .{++ @tagName(@as(Kind, kind)),++ stat[0][0], stat[0][1], stat[0][2], stat[0][3],++ stat[1][0], stat[1][1], stat[1][2], stat[1][3],++ cap,++ });++ }++}+diff --git a/src/gpu_timing.c b/src/gpu_timing.c+index 22a95c7..d329c13 100644+--- a/src/gpu_timing.c++++ b/src/gpu_timing.c+@@ -143,8 +143,8 @@ size_t rediwm_gpu_timer_collect(struct gpu_timer *timer, uint64_t generation,+ for (unsigned i = 0; i < SLOTS; ++i) {+ struct query_pair *pair = &timer->slots[i];+ if (!pair->pending) continue;+- if (disjoint || pair->generation != generation || ++pair->age > 120) {+- if (pair->generation == generation) ++*dropped;++ if (disjoint || (pair->generation & 0x0fffffffffffffffULL) != generation || ++pair->age > 120) {++ if ((pair->generation & 0x0fffffffffffffffULL) == generation) ++*dropped;+ recycle(timer, pair);+ continue;+ }+@@ -167,7 +167,7 @@ size_t rediwm_gpu_timer_collect(struct gpu_timer *timer, uint64_t generation,+ count = 0;+ for (unsigned i = 0; i < SLOTS; ++i) {+ if (timer->slots[i].pending) {+- if (timer->slots[i].generation == generation) ++*dropped;++ if ((timer->slots[i].generation & 0x0fffffffffffffffULL) == generation) ++*dropped;+ recycle(timer, &timer->slots[i]);+ }+ }+diff --git a/src/gpu_timing.zig b/src/gpu_timing.zig+index 9137fa3..6f431f8 100644+--- a/src/gpu_timing.zig++++ b/src/gpu_timing.zig+@@ -1,5 +1,6 @@+ const wlr = @import("wlroots");+ const stats = @import("ipc/stats.zig");++const ab = @import("ab.zig");+ const Sample = extern struct { ns: u64, generation: u64 };++ pub const Timer = opaque {+@@ -13,7 +14,7 @@ pub const Timer = opaque {+ pub const end = rediwm_gpu_timer_end;++ pub fn begin(self: *Timer) bool {+- const ok = rediwm_gpu_timer_begin(self, stats.global_stats.generation);++ const ok = rediwm_gpu_timer_begin(self, stats.global_stats.generation | ab.tag());+ if (!ok) stats.global_stats.gpu_samples_dropped +%= 1;+ return ok;+ }+@@ -23,8 +24,11 @@ pub const Timer = opaque {+ const n = rediwm_gpu_timer_collect(self, stats.global_stats.generation, &samples, &dropped);+ stats.global_stats.gpu_samples_dropped +%= dropped;+ for (samples[0..n]) |sample| {+- if (sample.generation == stats.global_stats.generation)++ if (sample.generation & ab.mask == stats.global_stats.generation) {+ stats.global_stats.gpu_elapsed.record(sample.ns);++ const t = sample.generation >> 60;++ if (ab.enabled and t & 2 != 0) ab.record(.gpu, @intCast(t & 1), sample.ns);++ }+ }+ }+ };diff --git a/tests/scene_ab.py b/tests/scene_ab.pynew file mode 100644index 0000000..38154f6--- /dev/null+++ b/tests/scene_ab.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""Frame-block A/B of the legacy and owned output presenters (scene graph stage 3 gate).++Session-level pairs (`scene_baseline.py --modes paired`) cannot resolve a few+microseconds: two sessions of the same presenter differ by up to 12 %. This runs+ONE compositor that alternates presenters every 32 frames, so both arms share the+process, clocks, thermal and power state. It needs a measurement build, because+the alternation is a test hook that production must not carry:++ git worktree add /tmp/ab HEAD # or: git archive HEAD | tar -x -C /tmp/ab+ cd /tmp/ab && git apply <repo>/tests/scene_ab.patch+ zig build -Doptimize=ReleaseSafe+ WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128 python3 <repo>/tests/scene_ab.py \\+ --binary /tmp/ab/zig-out/bin/rediwm++Per cell (clear repaint / repaint under glass, at each scale) it collects 3000+samples per presenter of the build call's thread CPU time, its wall time, build+plus commit wall time and GPU elapsed, and compares means against the tolerance+(docs/plans/scene-graph.md, stage 3: +5 % on build CPU and GPU elapsed). Exit+status is 1 if any cell is over. Differences under about 1.5 points are noise;+absolute values move between runs, only the within-run difference means anything.+Keep the machine on AC power and run nothing else: the harness refuses battery.+"""+import argparse+import json+import os+from pathlib import Path+import re+import sys+import tempfile+import time++sys.path.insert(0, str(Path(__file__).resolve().parent))+import scene_baseline as sb+from desktop_zoom import build_client++REPORT = re.compile(r"AB (\w+): legacy mean (\d+) med (\d+) p10 (\d+) p90 (\d+) \| "+ r"owned mean (\d+) med (\d+) p10 (\d+) p90 (\d+) \(ns, n=(\d+)\)")+GATED = ("build_cpu", "gpu")+++def parse_reports(text):+ cells = {}+ for match in REPORT.finditer(text):+ v = [int(x) for x in match.groups()[1:]]+ cells[match.group(1)] = {+ "n": v[8], "legacy": dict(mean=v[0], median=v[1], p10=v[2], p90=v[3]),+ "owned": dict(mean=v[4], median=v[5], p10=v[6], p90=v[7])}+ return cells+++def run_cell(binary, config, scenario, timeout):+ with tempfile.TemporaryDirectory(prefix="rediwm-scene-ab-") as directory:+ tmp = Path(directory)+ build_client(tmp)+ session = sb.Session(tmp, config, binary, "gles2", False, False, 4.0)+ try:+ for key in ("a", "b", "c"):+ session.start_client(key)+ session.raise_b()+ session.settle(1.0)+ glass, clear = session.spinner_rects()+ session.start_client("c", "damage", glass if scenario == "glass" else clear)+ session.raise_b()+ session.settle(1.0)+ session.ipc.reset_perf() # the GPU timer exists only after a perf request+ power = sb.power_state()+ log = tmp / "compositor.log"+ deadline = time.monotonic() + timeout+ cells = {}+ while time.monotonic() < deadline:+ time.sleep(5)+ cells = parse_reports(log.read_text(errors="replace"))+ if len(cells) == 4:+ break+ return cells, power, sb.power_state()+ finally:+ session.close()+++def main():+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--binary", type=Path, required=True, help="measurement build (tests/scene_ab.patch applied)")+ parser.add_argument("--configs", default="scale1,scale1.5,mixed")+ parser.add_argument("--scenarios", default="clear,glass", help="clear repaint, repaint under glass")+ parser.add_argument("--tolerance", type=float, default=5.0, help="allowed increase of owned over legacy, percent")+ parser.add_argument("--timeout", type=float, default=420, help="seconds to wait per cell")+ parser.add_argument("--cpus", default="auto", help="'auto' (P-cores) or 'none'")+ parser.add_argument("--allow-battery", action="store_true")+ parser.add_argument("--out", type=Path, help="write the raw statistics here")+ args = parser.parse_args()++ if b"REDIWM_TEST_AB" not in args.binary.read_bytes():+ parser.error(f"{args.binary} is not a measurement build: apply tests/scene_ab.patch and rebuild")+ unknown = [c for c in args.configs.split(",") if c not in sb.CONFIGS]+ if unknown:+ parser.error(f"unknown config {unknown}")+ if args.cpus == "auto" and sb.p_core_cpus():+ os.sched_setaffinity(0, sb.p_core_cpus())+ power = sb.power_state()+ if power["ac_online"] is False and not args.allow_battery:+ parser.error("AC power is not online: clocks differ on battery (use --allow-battery to measure anyway)")+ os.environ["REDIWM_TEST_AB"] = "1"+ os.environ.pop("REDIWM_TEST_SCENE_RENDERER", None)+ print(f"power: {power}", flush=True)++ results, failures = {}, []+ for config in args.configs.split(","):+ for scenario in args.scenarios.split(","):+ name = f"{config}/{scenario}"+ cells, before, after = run_cell(args.binary, config, scenario, args.timeout)+ if len(cells) != 4:+ failures.append(f"{name}: only {sorted(cells)} reported before the timeout")+ print(f"{name:16s} INCOMPLETE ({sorted(cells)})", flush=True)+ continue+ results[name] = {"cells": cells, "power_before": before, "power_after": after}+ row, bad = [], []+ for metric in ("build_cpu", "commit_wall", "gpu"):+ legacy, owned = cells[metric]["legacy"]["mean"], cells[metric]["owned"]["mean"]+ delta = (owned - legacy) / legacy * 100+ row.append(f"{metric} {legacy / 1e3:6.1f} -> {owned / 1e3:6.1f} us ({delta:+5.1f}%)")+ if metric in GATED and delta > args.tolerance:+ bad.append(f"{metric} {delta:+.1f}%")+ if before != after:+ row.append("POWER CHANGED")+ print(f"{name:16s} " + " ".join(row) + (" OVER: " + ", ".join(bad) if bad else " ok"), flush=True)+ failures += [f"{name}: {b} over +{args.tolerance:g}%" for b in bad]+ if args.out:+ args.out.write_text(json.dumps(results, indent=1) + "\n")+ if failures:+ print("\nFAIL:\n " + "\n ".join(failures))+ sys.exit(1)+ print(f"\nPASS: every cell within +{args.tolerance:g}% on {' and '.join(GATED)}")+++if __name__ == "__main__":+ main()