nv-nice: validate policy batches before writing to procfs (#537)

Co-authored-by: shiaho <222622008+shiaho777@users.noreply.github.com>
This commit is contained in:
shiaho
2026-12-05 08:15:54 +08:00
committed by GitHub
parent 9b579c4d11
commit 78eb9bf53d
2 changed files with 17 additions and 3 deletions

View File

@ -375,21 +375,24 @@ def run(
# Policy / desktop_comm / sync commands
if args.policy or args.desktop_comm or args.sync:
commands = []
for item in args.policy:
if "=" not in item:
raise ValueError(f"expected key=0|1, got {item!r}")
k, v = item.split("=", 1)
if k not in ("auto", "desktop_boost", "preempt") or v not in ("0", "1"):
raise ValueError(f"invalid policy setting: {item!r}")
_proc_write(write_fn, args.proc_file, f"{k} {v}")
commands.append(f"{k} {v}")
if args.desktop_comm:
op, name = args.desktop_comm
if op not in ("add", "del") or not name:
raise ValueError("expected --desktop-comm add|del <NAME>")
validate_desktop_comm_name(name)
_proc_write(write_fn, args.proc_file, f"desktop_comm {op} {name}")
commands.append(f"desktop_comm {op} {name}")
if args.sync:
_proc_write(write_fn, args.proc_file, "sync")
commands.append("sync")
for command in commands:
_proc_write(write_fn, args.proc_file, command)
if not (args.pid or args.pgid or rest or args.list or args.json):
return 0

View File

@ -149,6 +149,17 @@ class TestNvNice(unittest.TestCase):
self.assertEqual(writes, [(nv_nice.DEFAULT_PROC_PATH, "pid 5556 10")])
self.assertEqual(execs, [("python3", ["python3", "train.py"])])
def test_invalid_policy_batch_does_not_write(self) -> None:
for invalid in (
["--policy", "preempt=2"],
["--desktop-comm", "add", "name with space"],
):
with self.subTest(invalid=invalid):
write = mock.Mock()
with self.assertRaises(ValueError):
nv_nice.run(["--policy", "auto=0", *invalid, "--sync"], write_fn=write)
write.assert_not_called()
def test_policy_and_desktop_comm(self) -> None:
writes = []
rc = nv_nice.run(