fix(desktop): preserve bounded Windows program diagnostics (#2695)

* fix(desktop): preserve bounded Windows program diagnostics

* fix(desktop): isolate stderr mirror failures from diagnostic file capture

* fix(desktop): continue stderr mirroring after diagnostic file limit

* fix(desktop): make diagnostic stderr messages best-effort
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-17 17:37:17 -05:00
1 parent eb5aa7a536
commit 868207baf8
7 files changed
+214 -22

No files matched your search

@@ -1234,25 +1234,7 @@ def wait_for(check, timeout, step=0.1):
def capped_log(path):
os.makedirs(os.path.dirname(path), exist_ok=True)
handle = open(path, "wb")
read, write = os.pipe()
def pump():
written = 0
with os.fdopen(read, "rb") as source:
while True:
chunk = source.read1(65536) if hasattr(source, "read1") else source.read(65536)
if not chunk:
break
if written < LOG_CAP:
handle.write(chunk[:LOG_CAP - written])
handle.flush()
written += len(chunk)
handle.close()
threading.Thread(target=pump, daemon=True).start()
return write
return GAME_DEBUG["capped_log"](path, LOG_CAP)[0]
class Session:
@@ -1,8 +1,11 @@
#!/usr/bin/python3
import contextlib
import json
import os
import re
import sys
import tempfile
import threading
from pathlib import Path
GAME_DEBUG_CHANNELS = (
@@ -69,3 +72,74 @@ def apply_game_debug_logs(env, config=None, debug_dir=None):
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
def capped_log(path, limit, mirror=False):
os.makedirs(os.path.dirname(path), exist_ok=True)
handle = open(path, "wb")
try:
read, write = os.pipe()
except OSError:
handle.close()
raise
def pump():
remaining = limit
mirror_ok = mirror
with os.fdopen(read, "rb") as source, handle:
while True:
chunk = source.read1(65536)
if not chunk:
break
saved = chunk[:remaining]
remaining -= len(saved)
if saved:
try:
handle.write(saved)
handle.flush()
except (OSError, ValueError):
remaining = 0
if mirror_ok:
try:
sys.stderr.write(chunk.decode("utf-8", "replace"))
sys.stderr.flush()
except (OSError, ValueError):
mirror_ok = False
thread = threading.Thread(target=pump, daemon=True)
thread.start()
return write, thread
@contextlib.contextmanager
def desktop_program_logs(env):
program = env.get("DROIDDECK_DESKTOP_PROGRAM")
if program:
env = dict(env)
env.pop("DROIDDECK_DESKTOP_PROGRAM", None)
if not program or env.get("PROTON_LOG", "0") not in ("", "0"):
yield env, None
return
folder = session_debug_dir(env)
try:
if not os.path.isabs(folder) or not os.path.isdir(folder):
raise OSError("session log directory unavailable")
fd, path = tempfile.mkstemp(prefix="desktop-program-", suffix=".log", dir=folder)
os.close(fd)
output, thread = capped_log(path, 1024 * 1024, mirror=True)
except OSError as error:
print("droiddeck-game-env: desktop diagnostics unavailable (%s)" % error, file=sys.stderr)
yield env, None
return
try:
if env.get("WINEDEBUG", "-all") in ("", "-all"):
env["WINEDEBUG"] = "-all,err+all,+mscoree,+loaddll"
try:
print("droiddeck-game-env: desktop program %s; first 1048576 diagnostic bytes: %s" % (program, path),
file=sys.stderr, flush=True)
except OSError:
pass
yield env, output
finally:
os.close(output)
thread.join(timeout=1)
@@ -1178,11 +1178,22 @@ def diagnostic_game_exit(app_id, raw_code, source=None, wrapper_status=None):
def start(launch, launch_env, digest, after=None, diagnostic_app_id=None):
with GAME_DEBUG["desktop_program_logs"](launch_env) as (env, output):
code = start_process(launch, env, digest, after, diagnostic_app_id, output)
if output is not None:
try:
print("droiddeck-game-env: desktop program exited with status %d" % code, file=sys.stderr, flush=True)
except OSError:
pass
return code
def start_process(launch, launch_env, digest, after=None, diagnostic_app_id=None, output=None):
if len(launch) > 1 and launch[1] == "waitforexitandrun":
ubisoft_composition_off(launch[0], launch_env)
launch, launch_env = system_graphics_launch(launch, launch_env)
if after or diagnostic_app_id is not None:
process = subprocess.Popen(launch, env=launch_env)
if after or diagnostic_app_id is not None or output is not None:
process = subprocess.Popen(launch, env=launch_env, stderr=output)
if diagnostic_app_id is not None:
diagnostic_game_event("game_start", diagnostic_app_id)
try:
@@ -417,7 +417,7 @@ def main(argv):
say("%s: %s" % (cmd[0], error))
if status != 0 and time.monotonic() - started < QUICK_FAILURE:
notify("%s did not start" % os.path.basename(path),
"It exited with status %d; the session's desktop.log says why." % status)
"desktop.log (%d)" % status)
if what == "windows":
try:
subprocess.call([sys.executable, PROGRAMS])
@@ -524,6 +524,8 @@ def main(argv):
os.makedirs(target.compatdata, exist_ok=True)
env = environment(os.environ, target, folder, root, window, game_id)
env.update(extra)
if app is None and verb == VERB:
env["DROIDDECK_DESKTOP_PROGRAM"] = program
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
", without the Steam client" if app is not None else ""))
try:
+2
View File
@@ -709,6 +709,7 @@ class ProtonRunTest(Temp):
self.assertEqual(entry, str(self.root / "compatibilitytools.d/droiddeck-proton-11-arm64/droiddeck-proton"))
self.assertEqual(argv, [entry, "waitforexitandrun", str(program), "-fullscreen"])
self.assertEqual(env["SteamAppId"], "413150")
self.assertEqual(env["DROIDDECK_DESKTOP_PROGRAM"], str(program))
self.assertTrue((self.root / "steamapps/compatdata/413150").is_dir())
def run_main(self, argv):
@@ -737,6 +738,7 @@ class ProtonRunTest(Temp):
self.assertEqual((env["SteamAppId"], env["STEAM_COMPAT_DATA_PATH"]),
("413150", str(self.root / "steamapps/compatdata/413150")))
self.assertEqual(dirs, [str(program.parent)])
self.assertNotIn("DROIDDECK_DESKTOP_PROGRAM", env)
def test_without_steam_a_game_steam_cannot_start_is_refused(self):
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
@@ -0,0 +1,121 @@
import contextlib
import io
import os
from pathlib import Path
import runpy
import subprocess
import sys
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
DEBUG = runpy.run_path(str(BIN / "droiddeck-game-debug"))
class DesktopProgramDiagnosticsTest(unittest.TestCase):
def launch(self, folder, desktop=True, **settings):
env = dict(os.environ, BL_DEBUG_DIR=folder, WINEDEBUG="-all", PROTON_LOG="0")
env.pop("DROIDDECK_DESKTOP_PROGRAM", None)
if desktop:
env["DROIDDECK_DESKTOP_PROGRAM"] = "managed.exe"
env.update(settings)
child = "import os,sys; print(os.environ['WINEDEBUG']); sys.stderr.write('err:mscoree:CLRRuntimeInfo_GetRuntimeHost Wine Mono is not installed\\n'); sys.exit(7)"
wrapper = "import runpy,sys; g=runpy.run_path(sys.argv[1]); sys.exit(g['start']([sys.executable,'-c',sys.argv[2]],dict(__import__('os').environ),None))"
return subprocess.run([sys.executable, "-c", wrapper, str(BIN / "droiddeck-game-env"), child],
env=env, capture_output=True, text=True, timeout=15)
def test_desktop_failure_keeps_reason_and_exit_status(self):
with tempfile.TemporaryDirectory() as folder:
result = self.launch(folder)
self.assertEqual(result.returncode, 7)
self.assertEqual(result.stdout.strip(), "-all,err+all,+mscoree,+loaddll")
logs = list(Path(folder).glob("desktop-program-*.log"))
self.assertEqual(len(logs), 1)
self.assertIn("Wine Mono is not installed", logs[0].read_text())
self.assertIn("Wine Mono is not installed", result.stderr)
self.assertIn("exited with status 7", result.stderr)
def test_games_and_explicit_debug_settings_stay_unchanged(self):
with tempfile.TemporaryDirectory() as folder:
ordinary = self.launch(folder, desktop=False)
self.assertEqual(ordinary.stdout.strip(), "-all")
self.assertEqual(list(Path(folder).glob("*.log")), [])
opted_in = self.launch(folder, PROTON_LOG="1", WINEDEBUG="+relay")
self.assertEqual(opted_in.stdout.strip(), "+relay")
self.assertEqual(list(Path(folder).glob("*.log")), [])
explicit = self.launch(folder, WINEDEBUG="-all,err+module")
self.assertEqual(explicit.stdout.strip(), "-all,err+module")
def test_unavailable_log_directory_does_not_stop_program(self):
with tempfile.TemporaryDirectory() as folder:
result = self.launch(str(Path(folder) / "missing"))
self.assertEqual(result.returncode, 7)
self.assertEqual(result.stdout.strip(), "-all")
self.assertIn("diagnostics unavailable", result.stderr)
def test_capped_log_drains_after_limit_and_preserves_following_output(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "program.log"
output, thread = DEBUG["capped_log"](str(path), 1024)
try:
child = subprocess.Popen([sys.executable, "-c",
"import os; os.write(2,b'x'*2097152); print('completed')"],
stderr=output, stdout=subprocess.PIPE, text=True)
stdout, _ = child.communicate(timeout=10)
self.assertEqual(child.returncode, 0)
self.assertEqual(stdout.strip(), "completed")
finally:
os.close(output)
thread.join(timeout=2)
self.assertFalse(thread.is_alive())
self.assertEqual(path.read_bytes(), b"x" * 1024)
def test_capped_log_continues_mirroring_after_file_limit_and_survives_mirror_errors(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "mirrored.log"
mirrored = io.StringIO()
with contextlib.redirect_stderr(mirrored):
output, thread = DEBUG["capped_log"](str(path), 4, mirror=True)
try:
os.write(output, b"abcdef")
finally:
os.close(output)
thread.join(timeout=2)
self.assertEqual(path.read_bytes(), b"abcd")
self.assertEqual(mirrored.getvalue(), "abcdef")
def test_desktop_logs_have_unique_names_and_a_hard_byte_limit(self):
with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stderr(io.StringIO()):
env = {"DROIDDECK_DESKTOP_PROGRAM": "managed.exe", "BL_DEBUG_DIR": folder}
for _ in range(2):
with DEBUG["desktop_program_logs"](env) as (launch_env, output):
self.assertNotIn("DROIDDECK_DESKTOP_PROGRAM", launch_env)
child = subprocess.Popen([sys.executable, "-c", "import os; os.write(2,b'x'*2097152)"], stderr=output)
self.assertEqual(child.wait(timeout=10), 0)
logs = list(Path(folder).glob("desktop-program-*.log"))
self.assertEqual(len(logs), 2)
self.assertTrue(all(path.stat().st_size == 1048576 for path in logs))
def test_broken_stderr_does_not_abort_launch_or_replace_exit_status(self):
class BrokenStderr:
def write(self, data):
raise BrokenPipeError("closed")
def flush(self):
raise BrokenPipeError("closed")
game_env = runpy.run_path(str(BIN / "droiddeck-game-env"))
with tempfile.TemporaryDirectory() as folder:
env = dict(os.environ, BL_DEBUG_DIR=folder, WINEDEBUG="-all", PROTON_LOG="0",
DROIDDECK_DESKTOP_PROGRAM="managed.exe")
with contextlib.redirect_stderr(BrokenStderr()):
code = game_env["start"](
[sys.executable, "-c", "import sys; sys.stderr.write('err:child_line\\n'); sys.exit(7)"],
env,
None,
)
self.assertEqual(code, 7)
logs = list(Path(folder).glob("desktop-program-*.log"))
self.assertEqual(len(logs), 1)
self.assertIn("err:child_line", logs[0].read_text())