diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 53d81bdf..495ecde7 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -41,6 +41,7 @@ The launcher sets these for a Proton or Wine launch. A value you set yourself is | --- | --- | --- | | `TUXBOX_RUNTIME_SHADERS` | on | `0` stops translating shaders during play | | `TUXBOX_RUNTIME_SHADER_JOBS` | half the CPU cores, at least 2 where there are two, at most 32 | Compiler jobs during play, 1 to 32 | +| `TUXBOX_PROFILE_SHADERS` | `0` | Set to `1` for aggregate host shader-stage timing in the log (preparation and runtime). No title identifiers are included; `--profile-pipelines` enables runtime timing unless explicitly disabled. | | `TUXBOX_SHADER_PREP_JOBS` | one per CPU core, at most 32 | Compiler jobs for ProjectScarlett preparation | | `TUXBOX_SHADER_PREP` | `chase` | Frosty preparation: `0`, `1`, `menu` or `chase` | | `TUXBOX_SHADER_PREP_UI` | on for ProjectScarlett | `1` shows a desktop progress window | @@ -93,3 +94,51 @@ All are off by default. Capture variables write the game's data to disk, so don' ## Build and test tools `TUXBOX_XSHADER` selects the shader compiler for launcher preparation and `DXC` selects the DirectX Shader Compiler. `TUXBOX_BLESS_PROFILES`, `TUXBOX_ORACLE_*`, `TUXBOX_TEST_*` and the probe and replay variables in `tools/` belong to individual checks. `TUXBOX_PROVIDER`, `TUXBOX_SHADER_SESSION` and `TUXBOX_WINE_*` are internal; don't set them. + + +### Reading host shader stage timings + +For a cold and warm run, keep the same executable, prefix, compiler and settings, +and set `TUXBOX_PROFILE_SHADERS=1` for both launches. The aggregate JSON lines +labelled `Shader stage timings (preparation)` and `(runtime)` separate the +work done before the title starts from that done by the live compiler. The +runtime profile is also enabled by `--profile-pipelines`, unless explicitly +disabled. Keep the existing game log if the results need to be compared later. + +`requests.compiled` counts newly published source entries (including reuse of +identical DXIL); `reuse.content` counts those that did not need DXC again. +`reuse.source` counts exact cached entries served by the host. A warm guest +can read its cache without sending a request at all, so an empty runtime +profile is valid. Refused, cached-refusal and failed requests stay separate. +Stage outcomes count tool attempts, not shaders: a timeout and its successful +fallback are separate calls. Stage totals sum concurrent worker wall times +and can exceed the elapsed session time; they are not CPU time. The existing +vkd3d-proton pipeline trace measures driver-side calls separately. + +On Linux, when GNU `time` is installed, `process_memory` reports the +peak resident set size (RSS, in KiB) from child resource accounting. +`attempts` includes launch failures and timeouts; `measured` counts +completed measurements. A missing measurement is null, not zero. +The maximum is per CLI invocation, not the combined memory of simultaneous +compiles. Persistent DXC, combined descendant memory, guest/driver memory +and VRAM are not included. Other platforms and Linux without GNU time +retain timings without memory data. GNU time is optional, and is not +invoked when profiling is disabled. + +These host measurements cover dispatched requests, not guest-side cache +lookups or compiler discovery. They contain no shader hashes, title names +or raw error text. A forcibly killed launcher may not finish writing its +summary. + + +With `--profile-pipelines`, the capture directory also gets `stage-summary.json` +containing the host runtime compiler aggregate and the vkd3d-proton PSO event +aggregate from the same launch. The latter reports summed event durations, +wall-time coverage (the union of observed intervals), and peak overlapping +events. Overlap includes nesting and is not a worker count. These PSO events +can include translation, lookup and driver work; they do not isolate driver +compilation or measure GPU execution. Do not add host and PSO totals, since they +can overlap. Missing host profiling or a missing trace is represented by null, +not zero. The separate preparation aggregate remains in the launch log. +Keep the raw timeline and detailed pipeline summary local; the combined +aggregate does not include title or shader identifiers. diff --git a/project_tuxbox/host.py b/project_tuxbox/host.py index 01db82c5..f465abac 100644 --- a/project_tuxbox/host.py +++ b/project_tuxbox/host.py @@ -455,9 +455,11 @@ def run_game(self, executable, arguments, log, *, package=None, mangohud=False, configure_console_cbv(self.backend, env, executable, log.status) capture = performance_capture(self.backend, env, executable, log) if mangohud else nullcontext() pipelines = pipeline_capture(self.backend, env, log) if profile_pipelines else nullcontext() - with capture, pipelines, runtime_shader_compiler(self.backend, env, executable, log.status), \ + with capture, pipelines as timings, runtime_shader_compiler(self.backend, env, executable, log.status) as profile, \ game_diagnostics(self.backend, env, executable.parent, log.stderr_bytes, log_path=log.path) as stderr: + if timings is not None: + timings["host_runtime"] = profile return log.run([*self.command, str(executable), *arguments], cwd=executable.parent, env=env, stderr_bytes=stderr) finally: diff --git a/project_tuxbox/pipeline_profile.py b/project_tuxbox/pipeline_profile.py index de11c454..22650aba 100644 --- a/project_tuxbox/pipeline_profile.py +++ b/project_tuxbox/pipeline_profile.py @@ -11,10 +11,36 @@ from .pipeline_prep import winpath +def event_activity(intervals): + """Report summed event durations and their wall-time coverage separately. + + Overlapping (including nested) vkd3d events do not imply separate + compiler threads. This is coverage of observed PSO events, not GPU + execution time or exclusively driver work. + """ + boundaries = [] + for start, end in intervals: + if end > start: + boundaries.extend(((start, 1), (end, -1))) + active = peak = 0 + covered = 0.0 + previous = None + for at, delta in sorted(boundaries): + if previous is not None and active: + covered += at - previous + active += delta + peak = max(peak, active) + previous = at + return dict(event_count=len(intervals), + summed_ms=round(math.fsum(end - start for start, end in intervals) / 1000, 3), + covered_ms=round(covered / 1000, 3), peak_overlapping_events=peak) + + def summarize(trace): totals = {} pipeline_kinds = {} slowest = [] + intervals = [] with trace.open(encoding="utf-8", errors="replace") as stream: # vkd3d writes one event per line and can exit without closing the array. for index, line in enumerate(stream): @@ -36,12 +62,15 @@ def summarize(trace): if any(type(value) not in (int, float) for value in (duration, timestamp)): continue try: - duration /= 1000 - timestamp /= 1_000_000 + duration, timestamp = float(duration), float(timestamp) + end = timestamp + duration + if duration < 0 or not all(math.isfinite(v) for v in (duration, timestamp, end)): + continue except OverflowError: continue - if not math.isfinite(duration) or not math.isfinite(timestamp): - continue + intervals.append((timestamp, end)) + duration /= 1000 + timestamp /= 1_000_000 key, operation = match.groups() label = operation.split()[0] if label in ("GFX", "COMP", "LINK"): @@ -58,7 +87,8 @@ def summarize(trace): heapq.heappop(slowest) for group in totals.values(): group["total_ms"] = round(group["total_ms"], 3) - return dict(groups=totals, slowest=[item[2] for item in sorted(slowest, reverse=True)]) + return dict(groups=totals, activity=event_activity(intervals), + slowest=[item[2] for item in sorted(slowest, reverse=True)]) @contextmanager @@ -68,10 +98,13 @@ def pipeline_capture(backend, env, log): directory = Path(mkdtemp(prefix="pipelines-", dir=log.capture_parent())).resolve() trace = directory / "timeline.json" env.update(VKD3D_QUEUE_PROFILE=winpath(trace), VKD3D_QUEUE_PROFILE_ABSOLUTE="1") + env.setdefault("TUXBOX_PROFILE_SHADERS", "1") log.status(f"Pipeline timing capture: {trace}") + capture = {} try: - yield + yield capture finally: + result = None if trace.is_file(): try: result = summarize(trace) @@ -82,6 +115,20 @@ def pipeline_capture(backend, env, log): log.status(f"Could not summarize pipeline timings: {error}") else: log.status(f"The backend did not produce a pipeline trace at {trace}") + # Runtime workers are joined before this outer context exits. The + # report has no pipeline keys, raw names, paths, or game identifiers. + profile = capture.get("host_runtime") + try: + combined = directory / "stage-summary.json" + combined.write_text(json.dumps({ + "schema": 1, + "host_runtime": profile.summary() if profile is not None else None, + "vkd3d_pipeline_events": ({k: result[k] for k in ("groups", "activity")} + if result is not None else None), + }, indent=2) + "\n") + log.status(f"Shader and pipeline stage timings: {combined}") + except (OSError, ValueError) as error: + log.status(f"Could not write stage timings: {error}") if __name__ == "__main__": diff --git a/project_tuxbox/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index a6a6f710..00b08e62 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -18,6 +18,7 @@ from .inspect import digest from .persistent_dxc import PersistentDxc from .shader_diagnostics import refusal_line +from .shader_profile import ShaderProfile, timed, count_reuse from .shader_prep import SOURCE_CACHE, ToolFailure, compiler_tools, run_tool @@ -161,15 +162,17 @@ def compile_lock(cache, key, timeout=90): with os.fdopen(os.open(directory / key, flags, 0o600), "r+b") as stream: if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): raise ValueError("shader cache lock is not a regular file") - deadline = monotonic() + timeout - while True: - try: - fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except BlockingIOError: - if monotonic() >= deadline: - raise TimeoutError("shader cache lock wait timed out") - sleep(min(.025, max(0, deadline - monotonic()))) + def acquire(): + deadline = monotonic() + timeout + while True: + try: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except BlockingIOError: + if monotonic() >= deadline: + raise TimeoutError("shader cache lock wait timed out") + sleep(min(.025, max(0, deadline - monotonic()))) + timed("source_cache_lock", acquire) try: yield finally: @@ -234,7 +237,7 @@ def o0_timeout(hlsl): def validated_dxil(dxv, output, stage): """Return bounded, stage-correct output bytes after DXV accepts the file.""" - run_tool([dxv, output], timeout=10) + timed("dxv", run_tool, [dxv, output], timeout=10) data = bounded_shader(output) if portable_stage(data) != stage: raise ValueError("compiler returned invalid DXIL or a different shader stage") @@ -254,7 +257,7 @@ def compile_dxil(dxc, dxv, target, hlsl, output, store, request, stage): dispatched = target != "cs_6_6" and DISPATCHER in hlsl.read_bytes() if dispatched or target == "ps_6_6" and hlsl.stat().st_size >= (256 << 10): try: - run_tool([dxc, "-T", target, *entry, "-disable-lifetime-markers", + timed("dxc_no_lifetime", run_tool, [dxc, "-T", target, *entry, "-disable-lifetime-markers", "-Fo", output, hlsl], timeout=15) if not output.exists(): raise ValueError("compiler returned no DXIL output") @@ -264,13 +267,13 @@ def compile_dxil(dxc, dxv, target, hlsl, output, store, request, stage): # A dispatched program whose candidate failed, or a request that timed out # before, goes straight to -O0 rather than spending the cap again. if dispatched or (store and store.is_slow(request, target)): - run_tool(unoptimised, timeout=o0_timeout(hlsl)) + timed("dxc_o0", run_tool, unoptimised, timeout=o0_timeout(hlsl)) return validated_dxil(dxv, output, stage) # See `COMPUTE_FLAGS`. -O0 remains the fallback: the largest programs still # compile that way when the optimiser fails or runs out of time. if target == "cs_6_6": try: - run_tool([dxc, "-T", target, *entry, *COMPUTE_FLAGS, "-Fo", output, hlsl], timeout=COMPUTE_TIMEOUT) + timed("dxc_compute", run_tool, [dxc, "-T", target, *entry, *COMPUTE_FLAGS, "-Fo", output, hlsl], timeout=COMPUTE_TIMEOUT) if not output.exists(): raise ValueError("compiler returned no DXIL output") return validated_dxil(dxv, output, stage) @@ -280,19 +283,26 @@ def compile_dxil(dxc, dxv, target, hlsl, output, store, request, stage): except ValueError: pass output.unlink(missing_ok=True) - run_tool(unoptimised, timeout=o0_timeout(hlsl)) + timed("dxc_o0", run_tool, unoptimised, timeout=o0_timeout(hlsl)) return validated_dxil(dxv, output, stage) try: - run_tool([dxc, "-T", target, *entry, "-Fo", output, hlsl], timeout=15) + timed("dxc_default", run_tool, [dxc, "-T", target, *entry, "-Fo", output, hlsl], timeout=15) except subprocess.TimeoutExpired: if store: store.mark_slow(request, target) output.unlink(missing_ok=True) - run_tool(unoptimised, timeout=o0_timeout(hlsl)) + timed("dxc_o0", run_tool, unoptimised, timeout=o0_timeout(hlsl)) return validated_dxil(dxv, output, stage) -def compile_request(source, key, tools, cache, session, *, remember=None, persistent=None): +def compile_request(source, key, tools, cache, session, *, remember=None, persistent=None, profile=None): + if profile is not None: + return profile.request(_compile_request, ShaderRefused, source, key, tools, cache, session, + remember=remember, persistent=persistent) + return _compile_request(source, key, tools, cache, session, remember=remember, persistent=persistent) + + +def _compile_request(source, key, tools, cache, session, *, remember=None, persistent=None): linked = source.suffix == ".link" xshader, dxc, dxv = tools with TemporaryDirectory(dir=cache) as tmp: @@ -342,8 +352,9 @@ def compile_request(source, key, tools, cache, session, *, remember=None, persis stages &= {expected_stage} del source_data def reuse(): - cached = cache_snapshot(dest, checksum, stages) + cached = timed("source_cache_lookup", cache_snapshot, dest, checksum, stages) if cached is not None: + count_reuse("source") # Prelaunch hits need no temporary DXIL copy. if session is not None: reply.write_bytes(cached) @@ -364,9 +375,9 @@ def reuse(): return False hlsl, output, profile = (work / name for name in ("shader.hlsl", "out.cso", "profile")) if linked: - run_tool([dxv, order], timeout=10) + timed("dxv_input", run_tool, [dxv, order], timeout=10) try: - run_tool([xshader, cooked, *flags, "--hlsl-out", hlsl, "--profile-out", profile], timeout=30) + timed("xshader", run_tool, [xshader, cooked, *flags, "--hlsl-out", hlsl, "--profile-out", profile], timeout=30) except ToolFailure as error: # xshader reserves this status for the in-process HLSL emitter. DXC, DXV, # input parsing, tool startup and filesystem failures remain retryable. @@ -394,13 +405,15 @@ def reuse(): # compiler policy changes deliberately leave warm cache entries valid. store = DxilStore.for_cache(cache) content = store.key(hlsl.read_bytes(), target) if store else None - data = bounded_shader(output) if store and store.fetch(content, output) else None - if data is None or portable_stage(data) != target_stage: + data = bounded_shader(output) if store and timed("content_cache_lookup", store.fetch, content, output) else None + if data is not None and portable_stage(data) == target_stage: + count_reuse("content") + else: output.unlink(missing_ok=True) data = None if (persistent is not None and target == "cs_6_0" and not (store and store.is_slow(key, target)) - and persistent.compile(dxc, hlsl, output)): + and timed("dxc_persistent", persistent.compile, dxc, hlsl, output)): try: data = validated_dxil(dxv, output, target_stage) except (OSError, ValueError, subprocess.SubprocessError) as error: @@ -409,7 +422,7 @@ def reuse(): if data is None: data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage) if store: - store.save(content, output) + timed("content_cache_publish", store.save, content, output) stamp = work / "sha256" stamp.write_text(hashlib.sha256(data).hexdigest()) if session is not None: @@ -428,7 +441,7 @@ def remove_request(path): path.unlink(missing_ok=True) -def serve(session, stop, report, archive=None, jobs=1, *, dxc_helper=None): +def serve(session, stop, report, archive=None, jobs=1, *, dxc_helper=None, profile=None): # Cargo can replace the release executable while another title is running. # Keep the executable we fingerprint private to this host worker. with TemporaryDirectory(prefix="tuxbox-xshader-") as tmp, request_notifications(session / "requests", stop) as wait: @@ -442,7 +455,7 @@ def serve(session, stop, report, archive=None, jobs=1, *, dxc_helper=None): except OSError as error: report(f"Could not stage persistent DXC, using the CLI: {error}") with PersistentDxc(pinned, jobs, report) if pinned else nullcontext() as persistent: - _serve_requests(session, stop, report, Path(tmp) / "xshader", wait, archive, jobs, persistent=persistent) + _serve_requests(session, stop, report, Path(tmp) / "xshader", wait, archive, jobs, persistent=persistent, profile=profile) @contextmanager @@ -537,7 +550,7 @@ def ordered_requests(directory): return [source for _, _, source in sorted(entries)] -def _serve_requests(session, stop, report, xshader, wait, archive, jobs=1, *, persistent=None): +def _serve_requests(session, stop, report, xshader, wait, archive, jobs=1, *, persistent=None, profile=None): def bind_cache(): options = {"dxc_helper": persistent.helper} if persistent is not None else {} tools, cache = snapshot_compiler_cache(xshader, session.parent, **options) @@ -574,6 +587,8 @@ def compile_one(source, key, bound_tools, bound_cache): options = {"remember": remember} if record_requests else {} if persistent is not None: options["persistent"] = persistent + if profile is not None: + options["profile"] = profile return compile_request(source, key, bound_tools, bound_cache, session, **options) def complete(source, key, future=None, error=None): @@ -664,8 +679,8 @@ def runtime_shader_compiler(backend, env, executable, report): except OSError as exc: report(f"Could not open ProjectScarlett's shader inputs: {exc}") archive = None - with shader_session(cache, env, report, archive=archive): - yield + with shader_session(cache, env, report, archive=archive) as profile: + yield profile @contextmanager @@ -678,12 +693,17 @@ def shader_session(cache, env, report, *, archive=None): stop = Event() helper = env.get("TUXBOX_PERSISTENT_DXC") options = {"dxc_helper": helper} if helper else {} + profile = ShaderProfile() if env.get("TUXBOX_PROFILE_SHADERS") == "1" else None + if profile is not None: + options["profile"] = profile worker = Thread(target=serve, args=(session, stop, report, archive, runtime_jobs(env, report)), kwargs=options, name="shader-compiler", daemon=True) worker.start() try: - yield + yield profile finally: stop.set() worker.join() env.pop("TUXBOX_SHADER_SESSION", None) + if profile is not None: + profile.report("runtime", report) diff --git a/project_tuxbox/scarlett_prep.py b/project_tuxbox/scarlett_prep.py index 1746841b..f140120a 100644 --- a/project_tuxbox/scarlett_prep.py +++ b/project_tuxbox/scarlett_prep.py @@ -16,6 +16,7 @@ from .runtime_shaders import REQUEST_PATTERNS, ShaderRefused, compile_request, snapshot_compiler_cache from .shader_prep import SOURCE_CACHE from .shader_diagnostics import normalize_refusal +from .shader_profile import ShaderProfile from .shader_pack import seed_requests from .scarlett_report import aggregate, refusal_bucket, failure_bucket @@ -118,9 +119,12 @@ def prepare_scarlett(executable, host): tools, cache = snapshot_compiler_cache(Path(tmp) / "xshader", cache_root) phase = PrepPhase(progress, "Previously used Xbox shaders", len(sources)) + profile = ShaderProfile() if host.env.get("TUXBOX_PROFILE_SHADERS") == "1" else None + options = {"profile": profile} if profile is not None else {} + def compile_one(source): try: - compiled = compile_request(source, source.stem, tools, cache, None) + compiled = compile_request(source, source.stem, tools, cache, None, **options) return ("compiled" if compiled else "cached"), None, None, source.suffix, None except ShaderRefused as exc: return "unsupported", None, refusal_bucket(exc), source.suffix, normalize_refusal(str(exc)) if exc.reason_known else None @@ -146,6 +150,8 @@ def compile_one(source): unsupported=totals["unsupported"], failed=totals["failed"]) finally: workers.shutdown(cancel_futures=True) + if profile is not None: + profile.report("preparation", lambda message: report_progress(None, message)) elapsed = monotonic() - started unsupported = totals["unsupported"] diff --git a/project_tuxbox/shader_prep.py b/project_tuxbox/shader_prep.py index 474d6b44..694ce2fc 100644 --- a/project_tuxbox/shader_prep.py +++ b/project_tuxbox/shader_prep.py @@ -14,6 +14,7 @@ from .inspect import digest from .prep_progress import PrepPhase, desktop_progress, report_progress from .shader_inventory import decoder +from .shader_profile import run_profiled_tool ROOT = Path(__file__).resolve().parents[1] @@ -82,8 +83,7 @@ def __init__(self, tool, returncode, detail): def run_tool(command, *, timeout=None): - result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, - text=True, errors="replace", timeout=timeout) + result = run_profiled_tool(command, timeout=timeout) if result.returncode: raise ToolFailure(command[0], result.returncode, result.stderr[-600:].strip()) diff --git a/project_tuxbox/shader_profile.py b/project_tuxbox/shader_profile.py new file mode 100644 index 00000000..badaaa45 --- /dev/null +++ b/project_tuxbox/shader_profile.py @@ -0,0 +1,195 @@ +"""Opt-in aggregate timing of the host shader pipeline; never store title identifiers.""" +from collections import Counter +from contextvars import ContextVar +from functools import lru_cache +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +from tempfile import TemporaryDirectory +from threading import Lock +from time import monotonic_ns + + +_active = ContextVar("shader_profile", default=None) +_stage = ContextVar("shader_profile_stage", default=None) + + +class ShaderProfile: + def __init__(self): + self._start = monotonic_ns() + self._lock = Lock() + self._requests = Counter() + self._stages = {} + self._reuse = Counter() + self._memory = {} + + def record(self, stage, elapsed, outcome): + with self._lock: + stats = self._stages.setdefault(stage, [0, 0, Counter()]) + stats[0] += elapsed + stats[1] = max(stats[1], elapsed) + stats[2][outcome] += 1 + + def request(self, function, refusal_type, *args, **kwargs): + token = _active.set(self) + started = monotonic_ns() + outcome = "failed" + try: + result = function(*args, **kwargs) + outcome = "compiled" if result else "cached" + return result + except refusal_type as error: + outcome = "cached_refusal" if error.cached else "refused" + raise + finally: + _active.reset(token) + elapsed = monotonic_ns() - started + with self._lock: + self._requests[outcome] += 1 + self.record("request_total", elapsed, outcome) + + def reused(self, kind): + with self._lock: + self._reuse[kind] += 1 + + def record_memory(self, stage, peak): + with self._lock: + stats = self._memory.setdefault(stage, { + "attempts": 0, "measured": 0, "max_peak_rss_kib": None, + }) + stats["attempts"] += 1 + if peak is not None: + stats["measured"] += 1 + stats["max_peak_rss_kib"] = max(stats["max_peak_rss_kib"] or 0, peak) + + def summary(self): + with self._lock: + return { + "schema": 1, + "elapsed_ms": round((monotonic_ns() - self._start) / 1e6, 3), + "requests": dict(self._requests), + "reuse": dict(self._reuse), + "process_memory": {name: dict(stats) for name, stats in sorted(self._memory.items())}, + "stages": { + name: { + "calls": sum(counts.values()), + "total_ms": round(total / 1e6, 3), + "max_ms": round(maximum / 1e6, 3), + "outcomes": dict(counts), + } + for name, (total, maximum, counts) in sorted(self._stages.items()) + }, + } + + def report(self, label, emit): + emit(f"Shader stage timings ({label}): " + + json.dumps(self.summary(), sort_keys=True, separators=(",", ":"))) + + +def timed(stage, function, *args, **kwargs): + profile = _active.get() + if profile is None: + return function(*args, **kwargs) + started = monotonic_ns() + outcome = "error" + token = _stage.set(stage) + try: + result = function(*args, **kwargs) + outcome = "ok" + return result + except (TimeoutError, subprocess.TimeoutExpired): + outcome = "timeout" + raise + finally: + _stage.reset(token) + profile.record(stage, monotonic_ns() - started, outcome) + + +def count_reuse(kind): + profile = _active.get() + if profile is not None: + profile.reused(kind) + + +@lru_cache(maxsize=1) +def gnu_time(): + """GNU time reaps the tool in a small independent process.""" + executable = shutil.which("time") + if executable: + try: + result = subprocess.run([executable, "--version"], capture_output=True, timeout=2) + if result.returncode == 0 and b"GNU Time" in result.stdout + result.stderr: + return executable + except (OSError, subprocess.SubprocessError): + pass + return None + + +def read_usage(path, status): + """GNU time reports KiB and exit status; signalled tools have %x=0.""" + try: + peak, code = map(int, path.read_text(encoding="ascii").split()) + if peak < 0 or not 0 <= code <= 255: + return None, status + if status >= 128 and code == 0: + return peak, -(status - 128) + if code == status: + return peak, status + except (OSError, ValueError): + pass + return None, status + + +def run_profiled_tool(command, *, timeout=None): + """Measure CLI peak RSS using Linux child resource accounting, when enabled. + + Running wait4 in our Python process can inherit its high-water RSS into + the child on Linux. GNU time execs first, then waits for the tool itself. + No tool is rerun, and a timed-out wrapper and its descendants are killed + together. An unavailable measurement is reported as null. + """ + options = dict(stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + text=True, errors="replace") + profile, stage = _active.get(), _stage.get() + if profile is None or stage is None or sys.platform != "linux": + return subprocess.run(command, timeout=timeout, **options) + peak = None + try: + timer = gnu_time() + # Let subprocess report an absent or inaccessible executable in the + # usual way, rather than turning a launch error into a tool exit code. + if timer is None or shutil.which(os.fspath(command[0])) is None: + return subprocess.run(command, timeout=timeout, **options) + with TemporaryDirectory(prefix="tuxbox-rss-") as directory: + receipt = Path(directory) / "usage" + wrapped = [timer, "-q", "-f", "%M %x", "-o", str(receipt), "--", *command] + try: + process = subprocess.Popen(wrapped, start_new_session=True, **options) + except OSError: + # The optional timer may have disappeared after discovery. + # Popen did not start a child, so running the tool is safe. + return subprocess.run(command, timeout=timeout, **options) + with process: + try: + stdout, stderr = process.communicate(timeout=timeout) + except BaseException as error: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if isinstance(error, subprocess.TimeoutExpired): + raise subprocess.TimeoutExpired(command, timeout, + output=error.output, stderr=error.stderr) from error + raise + peak, code = read_usage(receipt, process.returncode) + # GNU time uses 126/127 when exec fails. The compiler's own + # errors with these codes are also retryable; neither may + # become a persistent unsupported translation. + return subprocess.CompletedProcess(command, code, stdout, stderr) + finally: + profile.record_memory(stage, peak) diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index 44f9ff17..88476ad5 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -51,12 +51,12 @@ def run_tool(self, args, *, timeout): raise subprocess.TimeoutExpired(args, timeout) args[args.index("-Fo") + 1].write_bytes(container(args[-1].read_bytes()[:4])) - def compile(self, cache, data=b"shader"): + def compile(self, cache, data=b"shader", *, profile=None): key = hashlib.sha256(data).hexdigest() source = self.root / (key + ".dxbc") source.write_bytes(data) with patch("project_tuxbox.runtime_shaders.run_tool", side_effect=self.run_tool): - self.assertTrue(compile_request(source, key, self.tools, cache, None)) + self.assertTrue(compile_request(source, key, self.tools, cache, None, profile=profile)) return (cache / (key + ".cso")).read_bytes() def test_output_built_with_other_compute_flags_is_not_reused(self): @@ -73,6 +73,16 @@ def test_new_translator_with_same_hlsl_skips_dxc(self): self.assertEqual((self.root / "runtime/b" / (hashlib.sha256(b"shader").hexdigest() + ".sha256")).read_text(), hashlib.sha256(second).hexdigest()) + def test_profile_counts_content_reuse_separately_from_compilation(self): + from project_tuxbox.shader_profile import ShaderProfile + first, second = ShaderProfile(), ShaderProfile() + self.assertEqual(self.compile(self.cache("a"), profile=first), + self.compile(self.cache("b"), profile=second)) + self.assertEqual(first.summary()["stages"]["dxc_default"]["calls"], 1) + self.assertEqual(second.summary()["requests"], {"compiled": 1}) + self.assertEqual(second.summary()["reuse"], {"content": 1}) + self.assertNotIn("dxc_default", second.summary()["stages"]) + def test_changed_hlsl_profile_or_toolchain_recompiles(self): self.compile(self.cache("a")) self.hlsl = "void main() { }" diff --git a/tests/test_performance.py b/tests/test_performance.py index d3e75909..c8c95d03 100644 --- a/tests/test_performance.py +++ b/tests/test_performance.py @@ -18,6 +18,7 @@ def test_pipeline_timings_group_driver_retries_and_read_partial_traces(self): with pipeline_capture("proton", env, log): first = Path(env["VKD3D_QUEUE_PROFILE"].removeprefix("Z:").replace("\\", "/")) self.assertEqual(env["VKD3D_QUEUE_PROFILE_ABSOLUTE"], "1") + self.assertEqual(env["TUXBOX_PROFILE_SHADERS"], "1") events = [ ("pso", "0000000000000001 GFX MISS", 100), ("pso", "0000000000000001 FALLBACK OK", 155_500), @@ -37,8 +38,36 @@ def test_pipeline_timings_group_driver_retries_and_read_partial_traces(self): self.assertEqual(result["groups"]["driver_internal"]["calls"], 1) self.assertEqual(result["slowest"][0]["wine_seconds"], 2) self.assertEqual(result["slowest"][0]["operation"], "FALLBACK OK") + env["TUXBOX_PROFILE_SHADERS"] = "0" with pipeline_capture("proton", env, log): self.assertNotIn(first.parent.name, env["VKD3D_QUEUE_PROFILE"]) + self.assertEqual(env["TUXBOX_PROFILE_SHADERS"], "0") + + def test_pipeline_stage_report_keeps_overlapping_time_and_missing_host_separate(self): + from project_tuxbox.shader_profile import ShaderProfile + with TemporaryDirectory() as tmp: + log = Mock(path=Path(tmp) / "run.log") + log.capture_parent.return_value = Path(tmp) + env = {} + profile = ShaderProfile() + profile.record("dxc_compute", 12_000_000, "ok") + with pipeline_capture("proton", env, log) as capture: + capture["host_runtime"] = profile + trace = Path(env["VKD3D_QUEUE_PROFILE"].removeprefix("Z:").replace("\\", "/")) + events = [(1000, 10000), (2000, 4000), (15000, 3000), (18000, 0), (1000, -1)] + trace.write_text("[\n" + "".join(json.dumps(dict(name="0000000000000001 COMP MISS", + pid="pso", ph="X", ts=ts, dur=dur)) + ",\n" for ts, dur in events)) + stages = json.loads(trace.with_name("stage-summary.json").read_text()) + self.assertEqual(stages["host_runtime"]["stages"]["dxc_compute"]["total_ms"], 12) + self.assertEqual(stages["vkd3d_pipeline_events"]["activity"], + {"event_count": 4, "summed_ms": 17, "covered_ms": 13, "peak_overlapping_events": 2}) + self.assertNotIn("slowest", stages["vkd3d_pipeline_events"]) + self.assertNotIn("0000000000000001", json.dumps(stages)) + with pipeline_capture("proton", env, log): + trace = Path(env["VKD3D_QUEUE_PROFILE"].removeprefix("Z:").replace("\\", "/")) + missing = json.loads(trace.with_name("stage-summary.json").read_text()) + self.assertIsNone(missing["host_runtime"]) + self.assertIsNone(missing["vkd3d_pipeline_events"]) def test_managed_capture_uses_its_own_config_and_finalizes_after_game_error(self): with TemporaryDirectory(prefix="hud test ") as tmp, patch("shutil.which", return_value="/usr/bin/mangohud"), \ diff --git a/tests/test_runtime_shader_links.py b/tests/test_runtime_shader_links.py index b72041ef..0e3c50ee 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -356,6 +356,56 @@ def run(args, *, timeout): self.assertIn("-O0", dxc_calls[1].args[0]) self.assertEqual((self.session / (key + ".cso")).read_bytes(), dxil) + def test_profile_distinguishes_cold_warm_and_fallback_attempts(self): + from project_tuxbox.shader_profile import ShaderProfile + data = b"synthetic program for profiling" + key = hashlib.sha256(data).hexdigest() + source = self.requests / (key + ".dxbc") + source.write_bytes(data) + expected = portable_program(5, b"result") + + def tool(args, *, timeout): + if args[0] == "xshader": + args[args.index("--hlsl-out") + 1].write_text("shader") + args[args.index("--profile-out") + 1].write_text("cs_6_0") + elif args[0] == "dxc": + if "-O0" not in args: + raise subprocess.TimeoutExpired("dxc", timeout) + args[args.index("-Fo") + 1].write_bytes(expected) + + profile = ShaderProfile() + with patch("project_tuxbox.runtime_shaders.run_tool", side_effect=tool): + self.assertTrue(compile_request(source, key, self.tools, self.cache, self.session, profile=profile)) + self.assertFalse(compile_request(source, key, self.tools, self.cache, self.session, profile=profile)) + summary = profile.summary() + self.assertEqual(summary["requests"], {"compiled": 1, "cached": 1}) + for stage, status in (("xshader", "ok"), ("dxc_default", "timeout"), + ("dxc_o0", "ok"), ("dxv", "ok")): + self.assertEqual(summary["stages"][stage]["outcomes"], {status: 1}) + self.assertNotIn(key, str(summary)) + self.assertEqual((self.session / (key + ".cso")).read_bytes(), expected) + + def test_profile_does_not_hide_refusals_or_retryable_errors(self): + from project_tuxbox.shader_profile import ShaderProfile + profile = ShaderProfile() + data = b"synthetic refused program" + key = hashlib.sha256(data).hexdigest() + source = self.requests / (key + ".dxbc") + source.write_bytes(data) + with patch("project_tuxbox.runtime_shaders.run_tool", + side_effect=ToolFailure("xshader", 65, "private reason")): + for cached in (False, True): + with self.assertRaises(ShaderRefused) as result: + compile_request(source, key, self.tools, self.cache, self.session, profile=profile) + self.assertEqual(result.exception.cached, cached) + source.write_bytes(b"corrupt") + with self.assertRaises(ValueError): + compile_request(source, key, self.tools, self.cache, self.session, profile=profile) + summary = profile.summary() + self.assertEqual(summary["requests"], {"refused": 1, "cached_refusal": 1, "failed": 1}) + self.assertEqual(summary["stages"]["xshader"]["outcomes"], {"error": 1}) + self.assertNotIn("private reason", str(summary)) + def test_large_pixel_candidate_precedes_slow_marker_and_validates_once(self): """Cold large ps_6_6 requests validate the candidate before publication.""" program = b"Xbox pixel shader" diff --git a/tests/test_shader_profile.py b/tests/test_shader_profile.py new file mode 100644 index 00000000..0a8ae6e5 --- /dev/null +++ b/tests/test_shader_profile.py @@ -0,0 +1,156 @@ +"""Bounded aggregate statistics across multiple simultaneous shader requests.""" +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory +from time import sleep +import unittest +from unittest.mock import patch + +from project_tuxbox.runtime_shaders import ShaderRefused +from project_tuxbox.shader_profile import ShaderProfile, timed, count_reuse, gnu_time +from project_tuxbox.shader_prep import run_tool, ToolFailure + + +class ProfileTests(unittest.TestCase): + def test_concurrent_requests_have_independent_profiles(self): + first, second = ShaderProfile(), ShaderProfile() + + def run(): + timed("xshader", lambda: None) + count_reuse("content") + return True + + with ThreadPoolExecutor(max_workers=8) as pool: + jobs = [pool.submit(profile.request, run, ShaderRefused) + for profile in (first, second) for _ in range(100)] + self.assertTrue(all(job.result() for job in jobs)) + # Neither an unprofiled request nor a previous context leaks into these. + run() + for profile in (first, second): + result = profile.summary() + self.assertEqual(result["requests"], {"compiled": 100}) + self.assertEqual(result["reuse"], {"content": 100}) + self.assertEqual(result["stages"]["xshader"]["calls"], 100) + self.assertEqual(result["stages"]["request_total"]["calls"], 100) + self.assertGreaterEqual(result["stages"]["request_total"]["total_ms"], + result["stages"]["xshader"]["total_ms"]) + + +@unittest.skipUnless(sys.platform == "linux", "Linux child resource accounting") +class ProcessMemoryTests(unittest.TestCase): + def request(self, profile, code, timeout=5, stage="dxc_default"): + return profile.request( + lambda: timed(stage, run_tool, [sys.executable, "-c", code], timeout=timeout), + ShaderRefused) + + def test_peak_memory_is_measured_per_tool_not_across_children(self): + profile = ShaderProfile() + if not gnu_time(): + self.skipTest("GNU time not installed") + self.request(profile, "import time; data = bytearray(48 * 1024**2); time.sleep(.15)") + self.request(profile, "import time; data = bytearray(2 * 1024**2); time.sleep(.15)", + stage="dxv") + memory = profile.summary()["process_memory"] + large, small = memory["dxc_default"], memory["dxv"] + self.assertEqual((large["attempts"], large["measured"]), (1, 1)) + self.assertGreaterEqual(large["max_peak_rss_kib"], 48 * 1024) + self.assertGreater(large["max_peak_rss_kib"], small["max_peak_rss_kib"] + 30 * 1024) + + def test_failed_and_timed_out_tools_preserve_exception_and_measurement(self): + if not gnu_time(): + self.skipTest("GNU time not installed") + profile = ShaderProfile() + with self.assertRaises(ToolFailure) as result: + self.request(profile, "import sys; print('expected error', file=sys.stderr); sys.exit(65)") + self.assertEqual(result.exception.returncode, 65) + self.assertIn("expected error", str(result.exception)) + with self.assertRaises(subprocess.TimeoutExpired): + self.request(profile, "import time; time.sleep(10)", timeout=.12) + memory = profile.summary()["process_memory"]["dxc_default"] + self.assertEqual(memory["attempts"], 2) + self.assertGreaterEqual(memory["measured"], 1) + self.assertEqual(profile.summary()["stages"]["dxc_default"]["outcomes"], + {"error": 1, "timeout": 1}) + + def test_unavailable_timer_does_not_change_tool_result(self): + profile = ShaderProfile() + with patch("project_tuxbox.shader_profile.gnu_time", return_value=None): + self.request(profile, "pass") + memory = profile.summary()["process_memory"]["dxc_default"] + self.assertEqual(memory, {"attempts": 1, "measured": 0, + "max_peak_rss_kib": None}) + + def test_parallel_processes_do_not_share_peak_rss(self): + if not gnu_time(): + self.skipTest("GNU time not installed") + large, small = ShaderProfile(), ShaderProfile() + with ThreadPoolExecutor(max_workers=2) as pool: + one = pool.submit(self.request, large, + "import time; data = bytearray(64 * 1024**2); time.sleep(.2)") + two = pool.submit(self.request, small, + "import time; data = bytearray(2 * 1024**2); time.sleep(.2)") + one.result() + two.result() + high = large.summary()["process_memory"]["dxc_default"] + low = small.summary()["process_memory"]["dxc_default"] + self.assertEqual(high["attempts"], 1) + self.assertEqual(low["attempts"], 1) + self.assertGreater(high["max_peak_rss_kib"], low["max_peak_rss_kib"] + 45 * 1024) + + def test_disabled_profile_does_not_start_timer(self): + with patch("project_tuxbox.shader_profile.gnu_time") as probe: + run_tool([sys.executable, "-c", "pass"], timeout=5) + probe.assert_not_called() + + def test_tool_startup_failure_counts_unsampled_attempt(self): + profile = ShaderProfile() + with self.assertRaises(FileNotFoundError): + profile.request(lambda: timed("xshader", run_tool, + ["/nonexistent-tuxbox-test-tool"], timeout=1), + ShaderRefused) + self.assertEqual(profile.summary()["process_memory"]["xshader"], + {"attempts": 1, "measured": 0, + "max_peak_rss_kib": None}) + + def test_short_process_and_signal_status_are_measured(self): + if not gnu_time(): + self.skipTest("GNU time not installed") + profile = ShaderProfile() + # A large allocation in the Python parent must not become the short + # child's peak just because Linux reports inherited RSS on wait4. + parent = bytearray(96 * 1024**2) + self.request(profile, "pass") + self.assertLess(profile.summary()["process_memory"]["dxc_default"]["max_peak_rss_kib"], + len(parent) // 1024) + with self.assertRaises(ToolFailure) as result: + self.request(profile, "import os, signal; os.kill(os.getpid(), signal.SIGTERM)") + self.assertEqual(result.exception.returncode, -15) + with self.assertRaises(ToolFailure) as result: + self.request(profile, "raise SystemExit(143)") + self.assertEqual(result.exception.returncode, 143) + + + def test_disappearing_optional_timer_keeps_compiler_available(self): + profile = ShaderProfile() + with patch("project_tuxbox.shader_profile.gnu_time", return_value="/nonexistent-tuxbox-time"): + self.request(profile, "pass") + self.assertEqual(profile.summary()["process_memory"]["dxc_default"]["measured"], 0) + + def test_timeout_terminates_tool_descendants(self): + if not gnu_time(): + self.skipTest("GNU time not installed") + profile = ShaderProfile() + with TemporaryDirectory() as tmp: + launched, survived = Path(tmp) / "launched", Path(tmp) / "survived" + child = f"import time; from pathlib import Path; time.sleep(1); Path({str(survived)!r}).touch()" + code = (f"import subprocess, sys, time; from pathlib import Path; " + f"subprocess.Popen([sys.executable, '-c', {child!r}]); " + f"Path({str(launched)!r}).touch(); time.sleep(10)") + with self.assertRaises(subprocess.TimeoutExpired): + self.request(profile, code, timeout=.5) + self.assertTrue(launched.exists()) + sleep(.7) + self.assertFalse(survived.exists()) + self.assertEqual(profile.summary()["process_memory"]["dxc_default"]["measured"], 0)