RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
memory retention tests and fixes
oxydizer0d708437b0af
diff --git a/TESTING.md b/TESTING.mdindex cdf4099..12d53c7 100644--- a/TESTING.md+++ b/TESTING.md@@ -62,6 +62,31 @@ and [startup_perf.py](tests/startup_perf.py). Stats requests enable timers andadd overhead; keep CPU comparisons free of them. `frame_time_ms` is the commitinterval; CPU and GPU work overlap, so do not add their timings.+Audit memory retention with [memory_retention.py](tests/memory_retention.py):++```sh+python3 tests/memory_retention.py --app files --cycles 50 --out /tmp/files-retention.json+python3 tests/memory_retention.py --app control-center --cycles 50 --out /tmp/settings-retention.json+```++The default binary is `zig-out/release-safe/bin/rediwm`; apps come from the same+directory. Each run uses one private compositor, five warm-up cycles, then+repeatedly opens and closes the same app. It waits for client exit, close+animation teardown and frame barriers before recording PSS, private clean ++dirty memory, swap, scene-node counts, FDs and DRM fdinfo counters. JSON includes+every cycle, growth and slope, baseline/final smaps, binary hash and shutdown+logs. `--scale 1.5`, `--close-mode kill`, `--no-animations` and `--no-glass`+exercise other paths; `--settle` controls the post-close delay (default 1 s).+Scene counts must return to the warmed baseline. Optional+`--max-private-growth-kib` (last five samples' median minus baseline) and+`--max-pss-slope-kib` set machine-specific memory gates. Compare identical builds,+renderer, scale and workload settings: allocator/driver caches can retain a+bounded high-water mark, and PSS varies with other processes sharing pages.+DRM counters are per client (duplicate FDs removed); shared objects can still+appear in multiple clients, and PSS alone cannot establish GPU retention.+Restarting an app measures retention in the compositor, not leaks within a+long-lived app process. Use Debug separately to check shutdown leak reports.+Hardware, login, browser/OBS sharing and toolkit IME checks remain manual. See[rendering](docs/agent-notes/rendering.md), [tiling qualification](docs/plans/optional-tiling-qualification.md)and [printer qualification](docs/plans/printers-qualification.md).diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdindex 37088cc..ab9011c 100644--- a/docs/agent-notes/rendering.md+++ b/docs/agent-notes/rendering.md@@ -47,6 +47,11 @@ chrome, capture, or retained panel painting. General rules remain inhost `grim`. Brief vanishing after a startup scale mismatch is not a bug.* **GLES can NULL `wlr_scene_buffer.buffer`** after upload (the texturestays): persist raster sizes.+* **Owned buffer destructors call `base.finish()` before freeing or pooling.**+ wlroots 0.20 delegates the destroy event and addon cleanup to the producer.+ Skipping it leaves consumers attached to freed storage (or the old incarnation+ of a pooled buffer). This applies to chrome, images, taskbar, panels and desktop+ tiles; `zig build test-lifecycle` checks finalization after the last lock.* **Glass is drawn by the output pass** (stage 5, `docs/plans/scene-graph-stage5.md`).`glass.c` only registers effects: a bufferless node just below its target, towhich resolve gives the target's box. When an effect re-blurs, `scene_output_draw.c`diff --git a/src/ImageBuffer.zig b/src/ImageBuffer.zigindex 39e9333..0daf746 100644--- a/src/ImageBuffer.zig+++ b/src/ImageBuffer.zig@@ -127,6 +127,7 @@ fn resample(src: []const u32, src_w: i32, src_h: i32, dst_w: i32, dst_h: i32) ![}fn destroy(base: *wlr.Buffer) callconv(.c) void {+ base.finish();const image: *ImageBuffer = @fieldParentPtr("base", base);gpa.free(image.pixels);gpa.destroy(image);diff --git a/src/chrome.zig b/src/chrome.zigindex e20f942..1d768e9 100644--- a/src/chrome.zig+++ b/src/chrome.zig@@ -401,6 +401,7 @@ pub const ChromeBuffer = struct {}fn destroy(base: *wlr.Buffer) callconv(.c) void {+ base.finish();const frame: *ChromeBuffer = @fieldParentPtr("base", base);gpa.free(frame.pixels);gpa.destroy(frame);diff --git a/src/desktop/TileBuffer.zig b/src/desktop/TileBuffer.zignew file mode 100644index 0000000..9f49136--- /dev/null+++ b/src/desktop/TileBuffer.zig@@ -0,0 +1,64 @@+//! One tile's pixels, owned by wlroots once published. Released buffers+//! return to a small pool of mostly equal-sized tiles.++const std = @import("std");+const wlr = @import("wlroots");+const a = std.heap.c_allocator;+const TileBuffer = @This();++base: wlr.Buffer,+width: i32,+height: i32,+pixels: []u32,+pooled: bool,++const drm_format_argb8888: u32 = 0x34325241;+const impl = wlr.Buffer.Impl{+ .destroy = destroyBuffer,+ .get_dmabuf = null,+ .get_shm = null,+ .begin_data_ptr_access = beginDataPtrAccess,+ .end_data_ptr_access = endDataPtrAccess,+};+const max_pooled = 32;+var pool: std.ArrayList(*TileBuffer) = .empty;++pub fn acquire(width: i32, height: i32) !*TileBuffer {+ for (pool.items, 0..) |buf, i| {+ if (buf.width != width or buf.height != height) continue;+ _ = pool.swapRemove(i);+ buf.base.init(&impl, width, height);+ return buf;+ }+ return create(width, height, true);+}++pub fn create(width: i32, height: i32, pooled: bool) !*TileBuffer {+ const buf = try a.create(TileBuffer);+ errdefer a.destroy(buf);+ const pixels = try a.alloc(u32, @intCast(width * height));+ buf.* = .{ .base = undefined, .width = width, .height = height, .pixels = pixels, .pooled = pooled };+ buf.base.init(&impl, width, height);+ return buf;+}++fn destroyBuffer(base: *wlr.Buffer) callconv(.c) void {+ // Notify texture wrappers and finish addons before reusing the buffer.+ base.finish();+ const buf: *TileBuffer = @fieldParentPtr("base", base);+ if (buf.pooled and pool.items.len < max_pooled) {+ if (pool.append(a, buf)) return else |_| {}+ }+ a.free(buf.pixels);+ a.destroy(buf);+}++fn beginDataPtrAccess(base: *wlr.Buffer, _: u32, data: **anyopaque, format: *u32, stride: *usize) callconv(.c) bool {+ const buf: *TileBuffer = @fieldParentPtr("base", base);+ data.* = @ptrCast(buf.pixels.ptr);+ format.* = drm_format_argb8888;+ stride.* = @as(usize, @intCast(buf.width)) * @sizeOf(u32);+ return true;+}++fn endDataPtrAccess(_: *wlr.Buffer) callconv(.c) void {}diff --git a/src/desktop/embedded.zig b/src/desktop/embedded.zigindex 208a25c..6cf0747 100644--- a/src/desktop/embedded.zig+++ b/src/desktop/embedded.zig@@ -752,59 +752,4 @@ pub const Desktop = struct {/// One tile's pixels, owned by wlroots once published. Released buffers/// return to a small pool of mostly equal-sized tiles.-const TileBuffer = struct {- base: wlr.Buffer,- width: i32,- height: i32,- pixels: []u32,- pooled: bool,-- const drm_format_argb8888: u32 = 0x34325241;- const impl = wlr.Buffer.Impl{- .destroy = destroyBuffer,- .get_dmabuf = null,- .get_shm = null,- .begin_data_ptr_access = beginDataPtrAccess,- .end_data_ptr_access = endDataPtrAccess,- };- const max_pooled = 32;- var pool: std.ArrayList(*TileBuffer) = .empty;-- fn acquire(width: i32, height: i32) !*TileBuffer {- for (pool.items, 0..) |buf, i| {- if (buf.width != width or buf.height != height) continue;- _ = pool.swapRemove(i);- buf.base.init(&impl, width, height);- return buf;- }- return create(width, height, true);- }-- fn create(width: i32, height: i32, pooled: bool) !*TileBuffer {- const buf = try a.create(TileBuffer);- errdefer a.destroy(buf);- const pixels = try a.alloc(u32, @intCast(width * height));- buf.* = .{ .base = undefined, .width = width, .height = height, .pixels = pixels, .pooled = pooled };- buf.base.init(&impl, width, height);- return buf;- }-- fn destroyBuffer(base: *wlr.Buffer) callconv(.c) void {- const buf: *TileBuffer = @fieldParentPtr("base", base);- if (buf.pooled and pool.items.len < max_pooled) {- if (pool.append(a, buf)) return else |_| {}- }- a.free(buf.pixels);- a.destroy(buf);- }-- fn beginDataPtrAccess(base: *wlr.Buffer, _: u32, data: **anyopaque, format: *u32, stride: *usize) callconv(.c) bool {- const buf: *TileBuffer = @fieldParentPtr("base", base);- data.* = @ptrCast(buf.pixels.ptr);- format.* = drm_format_argb8888;- stride.* = @as(usize, @intCast(buf.width)) * @sizeOf(u32);- return true;- }-- fn endDataPtrAccess(_: *wlr.Buffer) callconv(.c) void {}-};+const TileBuffer = @import("TileBuffer.zig");diff --git a/src/lifecycle_tests.zig b/src/lifecycle_tests.zigindex c7c4e2b..2d88c3d 100644--- a/src/lifecycle_tests.zig+++ b/src/lifecycle_tests.zig@@ -31,3 +31,65 @@ test "lifecycle wait registration releases strings and timers at every allocatiotry std.testing.checkAllAllocationFailures(std.testing.allocator, registrationFailures, .{true});try std.testing.checkAllAllocationFailures(std.testing.allocator, registrationFailures, .{false});}++const wlr = @import("wlroots");++// Renderer wrappers attach listeners and addons without locking the producer.+// Both must be torn down while its pixels and embedded wlr.Buffer still exist.+fn bufferFinalization(base: *wlr.Buffer) !void {+ const Watch = struct {+ destroys: usize = 0,+ addons: usize = 0,+ listener: wl.Listener(void) = .init(notify),+ addon: wlr.Addon = undefined,++ const impl: wlr.Addon.Interface = .{ .name = "retention audit", .destroy = finishAddon };++ fn notify(listener: *wl.Listener(void)) void {+ const self: *@This() = @fieldParentPtr("listener", listener);+ self.destroys += 1;+ listener.link.remove();+ }++ fn finishAddon(addon: *wlr.Addon) callconv(.c) void {+ const self: *@This() = @fieldParentPtr("addon", addon);+ self.addons += 1;+ addon.deinit();+ }+ };+ var watch: Watch = .{};+ base.events.destroy.add(&watch.listener);+ watch.addon.init(&base.addons, &watch, &Watch.impl);+ _ = base.lock();+ base.drop();+ try std.testing.expectEqual(@as(usize, 0), watch.destroys);+ try std.testing.expectEqual(@as(usize, 0), watch.addons);+ base.unlock();+ try std.testing.expectEqual(@as(usize, 1), watch.destroys);+ try std.testing.expectEqual(@as(usize, 1), watch.addons);+}++test "lifecycle image buffer finalizes consumers after the last lock" {+ const image = try @import("ImageBuffer.zig").createSolid(16, 8, 0xff112233);+ try bufferFinalization(&image.base);+}++test "lifecycle chrome buffer finalizes consumers after the last lock" {+ const chrome = try @import("chrome.zig").ChromeBuffer.create(160, .{});+ try bufferFinalization(&chrome.base);+}++test "lifecycle taskbar buffer finalizes consumers after the last lock" {+ const bar = try @import("taskbar/types.zig").BarBuffer.create(16, 8, 1);+ try bufferFinalization(&bar.base);+}++test "lifecycle desktop tile finalizes consumers before freeing or reuse" {+ const TileBuffer = @import("desktop/TileBuffer.zig");+ const unpooled = try TileBuffer.create(16, 8, false);+ try bufferFinalization(&unpooled.base);+ for (0..3) |_| {+ const pooled = try TileBuffer.acquire(16, 8);+ try bufferFinalization(&pooled.base);+ }+}diff --git a/src/taskbar/types.zig b/src/taskbar/types.zigindex aad696c..8fa81e5 100644--- a/src/taskbar/types.zig+++ b/src/taskbar/types.zig@@ -291,6 +291,7 @@ pub const BarBuffer = struct {}pub fn destroyBuffer(base: *wlr.Buffer) callconv(.c) void {+ base.finish();const buf: *BarBuffer = @fieldParentPtr("base", base);gpa.free(buf.pixels);gpa.destroy(buf);diff --git a/tests/memory_retention.py b/tests/memory_retention.pynew file mode 100644index 0000000..4e42c2d--- /dev/null+++ b/tests/memory_retention.py@@ -0,0 +1,266 @@+#!/usr/bin/env python3+"""Repeated open/close retention audit in a private headless GLES2 compositor.++Records compositor PSS, private clean + dirty memory, swap, scene nodes, FDs,+and driver-reported DRM memory after every cycle. Warm-up cycles are recorded+but excluded from growth/slope calculations. PSS does not include all GPU memory;+missing DRM accounting is reported as null, never zero. No allocator trimming.++ python3 tests/memory_retention.py --cycles 50 --out /tmp/retention.json+ python3 tests/memory_retention.py --app files --scale 1.5 --out /tmp/files.json+ python3 tests/memory_retention.py --app control-center --out /tmp/settings.json++Use ReleaseSafe for memory comparisons; Debug's allocator has different retention.+Memory thresholds are opt-in and machine-specific. Scene counts must return to+the warmed baseline. Applications must exit on close (no background daemon).+"""++import argparse+from collections import Counter+import hashlib+import json+import math+import os+from pathlib import Path+import statistics+import subprocess+import tempfile+import time++from PIL import Image++from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process+++def drm_memory(proc):+ """Keep counters per DRM client; duplicated FDs must not double-count them."""+ clients = {}+ for path in (proc / "fdinfo").iterdir():+ try:+ fields = dict(line.split(":", 1) for line in path.read_text().splitlines() if ":" in line)+ except FileNotFoundError: # A short-lived FD can disappear during enumeration.+ continue+ fields = {key: value.strip() for key, value in fields.items()}+ if "drm-client-id" not in fields:+ continue+ identity = ":".join(fields.get(key, "") for key in ("drm-driver", "drm-pdev", "drm-client-id"))+ counters = {}+ for key, value in fields.items():+ if key.startswith(("drm-memory-", "drm-total-", "drm-shared-", "drm-resident-",+ "drm-active-", "drm-purgeable-")):+ parts = value.split()+ if len(parts) == 2 and parts[1] in ("KiB", "kB"):+ counters[key] = int(parts[0])+ clients[identity] = counters+ return clients or None+++def memory(pid):+ proc = Path(f"/proc/{pid}")+ fields = {}+ for line in (proc / "smaps_rollup").read_text().splitlines():+ parts = line.split()+ if len(parts) == 3 and parts[2] == "kB":+ fields[parts[0].removesuffix(":")] = int(parts[1])+ return {+ "pss_kib": fields["Pss"], "rss_kib": fields["Rss"],+ "private_kib": fields["Private_Clean"] + fields["Private_Dirty"],+ "private_clean_kib": fields["Private_Clean"], "private_dirty_kib": fields["Private_Dirty"],+ "pss_anon_kib": fields.get("Pss_Anon"), "pss_file_kib": fields.get("Pss_File"),+ "pss_shmem_kib": fields.get("Pss_Shmem"), "swap_kib": fields["Swap"],+ "swap_pss_kib": fields.get("SwapPss"),+ "fds": len(list((proc / "fd").iterdir())),+ "mappings": len((proc / "maps").read_text().splitlines()),+ "threads": len(list((proc / "task").iterdir())),+ "drm_clients_kib": drm_memory(proc),+ }+++def scene_counts(ipc):+ scene = ipc.get_scene_tree(max_depth=256)+ nodes = scene["nodes"]+ assert len(nodes) == scene["total_nodes"], "scene query truncated"+ return dict(sorted(Counter(f"{n['node_type']}:{n['role']}" for n in nodes).items()))+++def settle(ipc, seconds):+ # window_closed means unmapped, not destroyed: allow the close animation,+ # deferred teardown and renderer releases to finish before sampling.+ time.sleep(seconds)+ ipc.wait_for_frame()+ ipc.wait_for_frame()+++def sample(ipc, pid):+ assert not ipc.get_windows(), "a window survived closure"+ counts = scene_counts(ipc)+ return {**memory(pid), "scene_counts": counts, "scene_nodes": sum(counts.values())}+++def cycle(args, ipc, env, app_log):+ app = None+ try:+ if args.app == "control-center":+ ipc.open_control_center()+ ipc.wait_for("window_mapped", app_id="rediwm-settings")+ else:+ command = [str(args.binary.parent / f"rediwm-{args.app}")]+ if args.app == "files":+ command.append(env["HOME"])+ app = subprocess.Popen(command, env=env, stdout=app_log, stderr=app_log)+ ipc.wait_for("window_mapped", app_id=f"rediwm-{args.app}")+ windows = ipc.get_windows()+ assert len(windows) == 1, f"expected one window, got {windows}"+ window_id = windows[0]["id"]+ ipc.wait_for("window_geometry_settled", window_id=window_id)+ ipc.wait_for_frame()+ opened = memory(app.pid) if app else None+ if args.close_mode == "kill":+ app.kill()+ else:+ ipc.close_window(window_id)+ if app:+ code = app.wait(timeout=10)+ expected = -9 if args.close_mode == "kill" else 0+ assert code == expected, f"application exited {code}, expected {expected}"+ ipc.wait_for("window_closed", window_id=window_id)+ settle(ipc, args.settle)+ return opened+ finally:+ if app and app.poll() is None:+ stop_process(app)+++def summarize(baseline, rows):+ result = {}+ for key in ("pss_kib", "private_kib", "rss_kib", "swap_kib", "fds", "mappings", "scene_nodes"):+ values = [row[key] for row in rows]+ n = len(values)+ mean_x = (n - 1) / 2+ denominator = sum((i - mean_x) ** 2 for i in range(n))+ slope = sum((i - mean_x) * value for i, value in enumerate(values)) / denominator if denominator else 0+ tail = values[-min(5, n):]+ result[key] = {"baseline": baseline[key], "final": values[-1],+ "growth": values[-1] - baseline[key], "peak": max(values),+ "tail_median_growth": statistics.median(tail) - baseline[key],+ "slope_per_cycle": round(slope, 3)}+ return result+++def run(args, tmp, report):+ wallpaper = tmp / "wallpaper.png"+ Image.new("RGB", (64, 64), (32, 48, 64)).save(wallpaper)+ env = dict(HOME=str(tmp), XDG_CONFIG_HOME=str(tmp / "config"), XDG_DATA_HOME=str(tmp / "data"),+ XDG_CACHE_HOME=str(tmp / "cache"), XDG_STATE_HOME=str(tmp / "state"),+ XDG_RUNTIME_DIR=str(tmp), XDG_DATA_DIRS=str(tmp / "data"),+ DBUS_SESSION_BUS_ADDRESS=f"unix:path={tmp}/missing-session",+ DBUS_SYSTEM_BUS_ADDRESS=f"unix:path={tmp}/missing-system",+ PULSE_SERVER=f"unix:{tmp}/missing-pulse", PIPEWIRE_RUNTIME_DIR=str(tmp),+ REDIWM_DESKTOP_DIR=str(tmp / "desktop"), REDIWM_FILES_DEVICES="0",+ REDIWM_APP_SCOPES="0", REDIWM_SESSION_FD="", REDIWM_LOGIN_SESSION="",+ DISPLAY="", XAUTHORITY="", WLR_RENDERER_ALLOW_SOFTWARE="1",+ REDIWM_THEME=str(tmp / "rediwm-config.toml"))+ if args.no_glass:+ env["REDIWM_NO_GLASS"] = "1"+ config = (f'[compositor]\nxwayland = false\nfocus_zoom = "keep"\nwallpaper = "{wallpaper}"\n'+ '[desktop]\nenabled = false\n'+ f'[animations]\nenabled = {str(not args.no_animations).lower()}\n')+ compositor, log = spawn_compositor(tmp, binary=args.binary, renderer="gles2", scale=str(args.scale),+ config_content=config, env_extra=env)+ try:+ with IPCClient(tmp, timeout=20) as ipc, (tmp / "app.log").open("w") as app_log:+ ipc.wait_for("wallpaper_presented", timeout_ms=15000)+ ipc.wait_for("catalog_published", timeout_ms=15000)+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))+ app_env = dict(os.environ, **env, WAYLAND_DISPLAY=display,+ REDIWM_CONFIG=str(tmp / "rediwm-config.toml"))+ app_env.pop("REDIWM_SOCKET", None)+ ipc.move_cursor(0, 0)+ report["runtime"] = ipc.get_runtime()+ report["outputs"] = ipc.get_outputs()+ settle(ipc, args.settle)+ report["cold"] = sample(ipc, compositor.pid)+ for i in range(args.warmup + args.cycles):+ opened = cycle(args, ipc, app_env, app_log)+ row = {"cycle": i + 1, "warmup": i < args.warmup,+ "app_open": opened, **sample(ipc, compositor.pid)}+ report["samples"].append(row)+ print(f"{i + 1:3d} {'warm' if row['warmup'] else 'test'} "+ f"PSS={row['pss_kib']:8d} KiB private={row['private_kib']:8d} KiB "+ f"nodes={row['scene_nodes']} fds={row['fds']}", flush=True)+ if i == args.warmup - 1:+ report["baseline"] = row+ report["baseline_smaps"] = Path(f"/proc/{compositor.pid}/smaps").read_text()+ report["final_smaps"] = Path(f"/proc/{compositor.pid}/smaps").read_text()+ measured = report["samples"][args.warmup:]+ report["summary"] = summarize(report["baseline"], measured)+ failures = report["failures"]+ for row in measured:+ if row["scene_counts"] != report["baseline"]["scene_counts"]:+ failures.append(f"scene counts differ at cycle {row['cycle']}")+ if args.max_private_growth_kib is not None:+ if report["summary"]["private_kib"]["tail_median_growth"] > args.max_private_growth_kib:+ failures.append("private memory growth exceeded threshold")+ if args.max_pss_slope_kib is not None:+ if report["summary"]["pss_kib"]["slope_per_cycle"] > args.max_pss_slope_kib:+ failures.append("PSS slope exceeded threshold")+ finally:+ stop_process(compositor)+ log.close()+ report["compositor_exit"] = compositor.returncode+ report["compositor_log"] = Path(log.name).read_text(errors="replace")+ report["app_log"] = (tmp / "app.log").read_text(errors="replace") if (tmp / "app.log").exists() else ""+ if compositor.returncode != 0:+ report["failures"].append(f"compositor exited {compositor.returncode}")+ if "memory leaks reported" in report["compositor_log"]:+ report["failures"].append("Debug allocator reported leaks on shutdown")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--binary", type=Path, default=ROOT / "zig-out/release-safe/bin/rediwm")+ parser.add_argument("--app", choices=("calculator", "editor", "files", "control-center"), default="calculator")+ parser.add_argument("--cycles", type=int, default=30)+ parser.add_argument("--warmup", type=int, default=5)+ parser.add_argument("--settle", type=float, default=1.0, help="seconds after each close before frame barriers")+ parser.add_argument("--scale", type=float, default=1.0)+ parser.add_argument("--close-mode", choices=("graceful", "kill"), default="graceful")+ parser.add_argument("--no-animations", action="store_true")+ parser.add_argument("--no-glass", action="store_true")+ parser.add_argument("--max-private-growth-kib", type=float)+ parser.add_argument("--max-pss-slope-kib", type=float)+ parser.add_argument("--out", type=Path, required=True)+ args = parser.parse_args()+ if args.cycles < 2 or args.warmup < 1 or not math.isfinite(args.settle) or args.settle < 0:+ parser.error("need at least two measured cycles, one warm-up cycle and a nonnegative finite settle time")+ if not math.isfinite(args.scale) or args.scale <= 0:+ parser.error("scale must be positive and finite")+ for threshold in (args.max_private_growth_kib, args.max_pss_slope_kib):+ if threshold is not None and (not math.isfinite(threshold) or threshold < 0):+ parser.error("memory thresholds must be nonnegative and finite")+ if args.app == "control-center" and args.close_mode == "kill":+ parser.error("control-center is compositor-owned; use graceful closure")+ args.binary = args.binary.resolve()+ os.umask(0o077)+ os.environ.pop("REDIWM_NO_GLASS", None)+ report = {"schema": 1, "options": {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()},+ "revision": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),+ "dirty": bool(subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT)),+ "render_device": os.environ.get("WLR_RENDER_DRM_DEVICE"), "samples": [], "failures": []}+ with args.binary.open("rb") as binary:+ report["binary_sha256"] = hashlib.file_digest(binary, "sha256").hexdigest()+ try:+ with tempfile.TemporaryDirectory(prefix="rediwm-retention-") as directory:+ run(args, Path(directory), report)+ except Exception as error:+ report["failures"].append(f"{type(error).__name__}: {error}")+ finally:+ args.out.write_text(json.dumps(report, indent=2) + "\n")+ print(json.dumps(report.get("summary", {}), indent=2))+ print(f"Report: {args.out}")+ if report["failures"]:+ raise SystemExit("FAIL: " + "; ".join(report["failures"]))+++if __name__ == "__main__":+ main()