Merge pull request #1398: run_game.py rejects a profile copy that overlaps the original and a --tag with path separators, and stops a still-running child before deleting its profile (ICUMADETHIS)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-23 19:17:37 +03:00
commit 480ccec4b1
3 files changed
+168 -5

No files matched your search

+1
View File
@@ -57,6 +57,7 @@ TESTS = {
'pack_shader_cache_test': ('.venv', None, [], ''),
'spin_waits_test': ('.venv', None, [], ''),
'worktree_test': ('.venv', None, [], ''),
'run_game_test': ('.venv', None, [], ''),
'installer_test': ('.venv-py314', None, [], ''),
'ncz_test': ('.venv-py314', None, [], ''),
'romfs_prompts_test': ('.venv-py314', None, [], ''),
+130
View File
@@ -0,0 +1,130 @@
"""Run-profile copying and CLI rejection with disposable marker files; never launches a game."""
import contextlib
import io
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import run_game as run # noqa: E402
class ProfileTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.folder = Path(tmp.name)
self.profile = self.folder / 'profile'
self.profile.mkdir()
(self.profile / 'marker').write_text('original profile')
source = patch.object(run, 'PROFILE', self.profile)
source.start()
self.addCleanup(source.stop)
def test_overlapping_copies_fail_before_cleanup_or_copying(self):
for target in (self.profile, self.profile.parent, self.profile / 'nested'):
with self.subTest(target=target), \
patch.object(run.shutil, 'rmtree', side_effect=AssertionError('cleanup ran before overlap check')), \
patch.object(run.shutil, 'copytree', side_effect=AssertionError('copy ran before overlap check')):
with self.assertRaisesRegex(ValueError, 'profile'):
run.profile_copy(target, None)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
def test_separate_copy_refreshes_only_the_disposable_destination(self):
target = self.folder / 'build' / 'prof-run'
target.mkdir(parents=True)
(target / 'stale').write_text('old copy')
run.profile_copy(target, None)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
self.assertEqual((target / 'marker').read_text(), 'original profile')
self.assertFalse((target / 'stale').exists())
def test_path_like_tags_are_rejected_before_files_or_locks_are_touched(self):
for tag in ('../escape', '../../profile', '../../../profile', '..\\escape', 'nested/run', '/absolute'):
with self.subTest(tag=tag), \
patch.object(sys, 'argv', ['run_game.py', str(self.folder / 'build'), '--seconds', '1', '--tag', tag]), \
patch.object(Path, 'mkdir', side_effect=AssertionError('created a folder before checking tag')), \
patch.object(run, 'take_slot', side_effect=AssertionError('took a slot before checking tag')), \
contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as error:
run.main()
self.assertEqual(error.exception.code, 2)
def test_build_inside_the_original_profile_is_rejected_before_writes(self):
with patch.object(sys, 'argv', ['run_game.py', str(self.profile), '--seconds', '1']), \
patch.object(Path, 'mkdir', side_effect=AssertionError('created a folder before overlap check')), \
contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as error:
run.main()
self.assertEqual(error.exception.code, 2)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
def test_normal_run_cleans_its_copy_and_keeps_the_source(self):
build = self.folder / 'build'
proc = unittest.mock.Mock()
proc.wait.return_value = 0
proc.poll.return_value = 0
with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--tag', 'bench-1', '--show']), \
patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \
patch.object(run.subprocess, 'Popen', return_value=proc) as launch, \
contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(SystemExit) as error:
run.main()
self.assertEqual(error.exception.code, 0)
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
self.assertFalse((build / 'prof-bench-1').exists())
self.assertIn('rc=0', (build / 'logs' / 'bench-1.log').read_text())
launch.assert_called_once()
proc.terminate.assert_not_called()
def test_interrupted_wait_stops_the_owned_child_before_cleanup(self):
child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
proxy = unittest.mock.Mock(wraps=child)
interrupted = False
def wait(*args, **kwargs):
nonlocal interrupted
if not interrupted:
interrupted = True
raise KeyboardInterrupt
return child.wait(*args, **kwargs)
proxy.wait.side_effect = wait
build = self.folder / 'build'
remove = run.shutil.rmtree
def remove_after_exit(path, *args, **kwargs):
if Path(path) == build / 'prof-run':
self.assertIsNotNone(child.poll(), 'profile cleanup ran while the child was alive')
return remove(path, *args, **kwargs)
try:
with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--show']), \
patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \
patch.object(run.shutil, 'rmtree', side_effect=remove_after_exit), \
patch.object(run.subprocess, 'Popen', return_value=proxy):
with self.assertRaises(KeyboardInterrupt):
run.main()
self.assertIsNotNone(child.poll(), 'interrupted run left its child alive')
self.assertFalse((build / 'prof-run').exists())
self.assertEqual((self.profile / 'marker').read_text(), 'original profile')
finally:
if child.poll() is None:
child.kill()
child.wait(timeout=5)
def test_unresponsive_child_is_killed_after_termination_timeout(self):
proc = unittest.mock.Mock()
proc.poll.return_value = None
proc.wait.side_effect = [subprocess.TimeoutExpired('owned child', 5), 0]
run.stop_process(proc)
proc.terminate.assert_called_once()
proc.kill.assert_called_once()
self.assertEqual(proc.wait.call_args_list, [unittest.mock.call(timeout=5), unittest.mock.call()])
if __name__ == '__main__':
unittest.main(verbosity=2)
+37 -5
View File
@@ -137,7 +137,20 @@ def release_gpu_lock(f):
f.close()
def tag_name(value):
if '/' in value or '\\' in value:
raise argparse.ArgumentTypeError('run tag must be a name without path separators')
return value
def check_profile_destination(dest):
source, target = PROFILE.resolve(), Path(dest).resolve()
if source.is_relative_to(target) or target.is_relative_to(source):
raise ValueError('profile copy must not overlap the original profile')
def profile_copy(dest, save):
check_profile_destination(dest)
if dest.exists():
shutil.rmtree(dest)
shutil.copytree(PROFILE, dest)
@@ -149,6 +162,18 @@ def profile_copy(dest, save):
shutil.copytree(SAVES / save, users[0])
def stop_process(proc):
"""Stop this run's child before its disposable profile is removed, including an interrupted wait."""
if proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('exe_dir', type=Path, help='build directory holding totk.exe')
@@ -157,7 +182,7 @@ def main():
ap.add_argument('--seconds', type=float, required=True,
help='game time to run: the run ends once the world clock (game time since the save loaded) passed '
'this many seconds (shot is taken of that frame)')
ap.add_argument('--tag', default='run', help='names the profile copy and the log')
ap.add_argument('--tag', type=tag_name, default='run', help='names the profile copy and the log (no path separators)')
ap.add_argument('--shot', type=Path, help='PNG of the last frame; turns async pipeline builds off (boot.c)')
ap.add_argument('--log', type=Path, help='default: <exe dir>/logs/<tag>.log')
ap.add_argument('--env', action='append', default=[], metavar='KEY=VALUE', help='extra environment, repeatable')
@@ -166,6 +191,11 @@ def main():
a = ap.parse_args()
exe_dir = a.exe_dir.resolve()
prof = exe_dir / f'prof-{a.tag}'
try:
check_profile_destination(prof)
except ValueError as e:
ap.error(str(e))
log = (a.log or exe_dir / 'logs' / f'{a.tag}.log').resolve()
log.parent.mkdir(parents=True, exist_ok=True)
gpu = take_gpu_lock(exe_dir) if a.quiet else None
@@ -174,7 +204,6 @@ def main():
if a.quiet:
while busy():
time.sleep(10)
prof = exe_dir / f'prof-{a.tag}'
profile_copy(prof, a.save)
env = dict(os.environ, TOTK_ASSUME_FOCUS='1', TOTK_INPUT='none', TOTK_INPUT_SCRIPT=str(a.script.resolve()))
@@ -192,9 +221,12 @@ def main():
f.flush()
start = time.time()
proc = subprocess.Popen(args, cwd=exe_dir, env=env, stdout=f, stderr=subprocess.STDOUT)
if not a.show:
threading.Thread(target=keep_in_background, args=(proc,), daemon=True).start()
rc = proc.wait()
try:
if not a.show:
threading.Thread(target=keep_in_background, args=(proc,), daemon=True).start()
rc = proc.wait()
finally:
stop_process(proc)
f.write(f'run_game: rc={rc} wall={time.time() - start:.0f}s; others running after: '
f'totk.exe {count("totk.exe")}, ninja.exe {count("ninja.exe")}\n')
finally: