Merge pull request #1571 from ludovic111/fix/home-leak-tests

Tools and harnesses start the game in scratch folders, not a player's
This commit is contained in:
Ludovic Marie
2026-10-25 05:07:12 +01:00
committed by GitHub
28 changed files with 193 additions and 41 deletions
+9 -6
View File
@@ -67,17 +67,20 @@ class Failed(Exception):
pass
def game_env(screen):
def game_env(screen, home=None):
"""The environment of a game: lab.game_env with HORIZON_HOME `home` (a scratch folder when None), no live-count
ping, and on Linux the virtual screen `screen`."""
extra = {'HORIZON_TELEMETRY_URL': 'off'} # no live-count ping from test games
if home is not None:
extra['HORIZON_HOME'] = home
if sys.platform == 'darwin':
return dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
env = dict(os.environ, VSCREEN=screen)
return lab.game_env(**extra)
env = lab.game_env(VSCREEN=screen, **extra)
subprocess.run(['vscreen', 'up'], env=env, check=False, capture_output=True)
text = subprocess.run(['vscreen', 'env'], env=env, capture_output=True, text=True, check=True).stdout
env.pop('DISPLAY', None)
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
env[match.group(1)] = match.group(2)
env['HORIZON_NO_AUDIO'] = '1'
env['HORIZON_TELEMETRY_URL'] = 'off' # no live-count ping from test games
if LAVAPIPE.exists():
env['VK_ICD_FILENAMES'] = str(LAVAPIPE)
return env
@@ -632,7 +635,7 @@ def scratch(mode, resources):
(work / '.local/horizon-client').mkdir()
os.symlink(resources, work / '.local/horizon-client' / lab.VERSION)
# horizon-ctl reads No AI in the game home: this one, not the player's.
env = dict(game_env(os.environ.get('VSCREEN', 'agent-control')), HORIZON_HOME=str(work))
env = game_env(os.environ.get('VSCREEN', 'agent-control'), home=work)
return work, env
+3 -4
View File
@@ -53,15 +53,14 @@ guiScale:0
def vscreen_env():
out = subprocess.run(["vscreen", "env"], cwd=ROOT, capture_output=True, text=True, check=True)
env = dict(os.environ)
env = lab.game_env()
for part in out.stdout.replace(";", " ").split():
if "=" in part and not part.startswith("export"):
k, v = part.split("=", 1)
env[k] = v
env.pop("DISPLAY", None)
# Benchmark games never play sound on the machine's speakers.
env["HORIZON_NO_AUDIO"] = "1"
# Nor reach the telemetry server (docs/telemetry.md).
# lab.game_env: no sound on the machine's speakers, and scratch folders instead of the player's.
# Benchmark games do not reach the telemetry server (docs/telemetry.md).
env["HORIZON_TELEMETRY_URL"] = "off"
return env
+33
View File
@@ -5,6 +5,7 @@ generated files stay in .local/. Also the small helpers the harnesses share
(free ports, offline UUIDs, VarInts, float bits)."""
import argparse
import atexit
from collections import Counter
import hashlib
import json
@@ -54,6 +55,38 @@ def cargo_target():
return ROOT / os.environ.get("CARGO_TARGET_DIR", "target")
_SCRATCH_DIRS = []
def _scratch_dir(prefix):
path = tempfile.mkdtemp(prefix=prefix)
_SCRATCH_DIRS.append(path)
return path
@atexit.register
def _remove_scratch_dirs():
for path in _SCRATCH_DIRS:
shutil.rmtree(path, ignore_errors=True)
def game_env(base=None, **extra):
"""The environment for every run of the game, the launcher or horizon-ctl from a tool or a harness: no audio,
and fresh scratch folders for the game's home (logs, saves, options), the launcher's home and the XDG folders,
so a run never writes into a real player's folders (the game falls back to them when HORIZON_HOME is unset).
A folder the caller already has in `base` (default os.environ) or passes in `extra` is kept. The scratch folders
are removed when this process exits."""
env = dict(os.environ if base is None else base)
env.update({key: str(value) for key, value in extra.items()})
env["HORIZON_NO_AUDIO"] = "1"
env["HORIZON_LAUNCHER_NO_SELF_UPDATE"] = "1"
for key, prefix in (("HORIZON_HOME", "horizon-home-"), ("HORIZON_LAUNCHER_HOME", "horizon-launcher-home-"),
("XDG_DATA_HOME", "horizon-xdg-data-"), ("XDG_CONFIG_HOME", "horizon-xdg-config-")):
if not env.get(key):
env[key] = _scratch_dir(prefix)
return env
def write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+1 -2
View File
@@ -278,8 +278,7 @@ class Game:
(self.work / '.local/horizon-client').mkdir(parents=True)
os.symlink(resources, self.work / '.local/horizon-client' / lab.VERSION)
self.socket = self.work / 'c.sock'
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'))
env['HORIZON_HOME'] = str(self.work / 'home')
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'), home=self.work / 'home')
self.d = Cli(ctl, self.socket, self.work, env)
self.d.name = name
+1 -2
View File
@@ -167,8 +167,7 @@ def main():
os.symlink(bins / name, version / name)
os.symlink(resources, version / '.local/horizon-client' / lab.VERSION)
(version / '.installed').write_text('')
env = dict(os.environ, HORIZON_LAUNCHER_HOME=str(work / 'launcher'), HORIZON_HOME=str(work / 'home'),
HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
env = lab.game_env(HORIZON_LAUNCHER_HOME=work / 'launcher', HORIZON_HOME=work / 'home', HORIZON_TELEMETRY_URL='off')
m = Mcp(Path(args.launcher).resolve(), env)
try:
summary = scenario(m, out)
+6 -2
View File
@@ -33,6 +33,11 @@ import tempfile
import time
from pathlib import Path
try:
from . import lab
except ImportError:
import lab
ROOT = Path(__file__).resolve().parents[1]
@@ -154,8 +159,7 @@ def main():
args = ap.parse_args()
home = Path(tempfile.mkdtemp(prefix="horizon-mod-browser-"))
env = dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO="1", HORIZON_NO_HEARTBEAT="1",
HORIZON_CONTROL=str(home / "ctl.sock"))
env = lab.game_env(HORIZON_HOME=home, HORIZON_NO_HEARTBEAT="1", HORIZON_CONTROL=home / "ctl.sock")
launcher = [args.launcher]
game = Game(str(Path(args.bin) / "horizon-ctl"), str(Path(args.bin) / "horizon-client"),
args.resources, home, env)
+7
View File
@@ -39,6 +39,7 @@ import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import subprocess
import sys
@@ -812,6 +813,12 @@ class LocalExecutor:
trace.unlink(missing_ok=True)
log = (STATE_DIR / "logs" / f"{name}.log").open("w")
environment = run_environment(reuse)
# A game the harness starts logs into HORIZON_HOME, which is a real player's folder when it is unset
# (lab.game_env keeps this one).
game_home = STATE_DIR / "game-home" / name
shutil.rmtree(game_home, ignore_errors=True)
game_home.mkdir(parents=True)
environment.setdefault("HORIZON_HOME", str(game_home))
environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True))
environment.pop("PARITY_SHARD", None)
if shard:
+1 -1
View File
@@ -400,7 +400,7 @@ def run_horizon(args, distance):
for carry in dev_mods(args):
command += ["--dev-mod", str(carry)]
# Benchmark runs stay out of the live count and send nothing (docs/telemetry.md).
env = dict(os.environ, HORIZON_NO_AUDIO="1", HORIZON_TELEMETRY_URL="off")
env = lab.game_env(HORIZON_TELEMETRY_URL="off")
if args.warm:
# A first start to the title screen builds what later starts reuse (the content-mod
# root, the block behaviour snapshot). It is not measured: players see it once.
+1 -1
View File
@@ -120,7 +120,7 @@ class Server:
self.process = subprocess.Popen([str(c) for c in command], cwd=directory, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
encoding='utf-8', errors='replace',
env=dict(os.environ, HORIZON_NO_AUDIO='1'))
env=lab.game_env())
threading.Thread(target=self._read, daemon=True).start()
def _read(self):
+3 -4
View File
@@ -206,9 +206,8 @@ class Game:
self.home = work / 'home'
for d in ('home', 'launcher', 'data', 'config'):
(work / d).mkdir(parents=True)
self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'),
XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'),
HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
self.env = lab.game_env(HORIZON_HOME=self.home, HORIZON_LAUNCHER_HOME=work / 'launcher',
XDG_DATA_HOME=work / 'data', XDG_CONFIG_HOME=work / 'config', HORIZON_TELEMETRY_URL='off')
self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')]
self.log = work / 'c.log'
reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources)
@@ -343,7 +342,7 @@ class Run:
('XDG_CONFIG_HOME', 'config')):
(work / 'servers' / sub).mkdir(parents=True)
os.environ[var] = str(work / 'servers' / sub)
os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
os.environ.update(lab.game_env(HORIZON_TELEMETRY_URL='off'))
game = self.game = Game(Path(self.args.bin), self.resources, work / 'game')
servers_dat = game.home / 'servers.dat'
downloads = game.home / 'downloads'
+1 -1
View File
@@ -183,7 +183,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+1 -1
View File
@@ -82,7 +82,7 @@ def main():
rust_dir = build / 'rust'
shutil.rmtree(rust_dir, ignore_errors=True)
rust_dir.mkdir()
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl'))
env = lab.game_env(HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
run([binary, '--resources', lab.RESOURCES, '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env)
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]
+1 -1
View File
@@ -125,7 +125,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+1 -1
View File
@@ -245,7 +245,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+2 -2
View File
@@ -126,7 +126,7 @@ class Server:
self.lines = []
self.process = subprocess.Popen(list(map(str, command)), cwd=directory, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
encoding='utf-8', errors='replace')
encoding='utf-8', errors='replace', env=lab.game_env())
self.reader = threading.Thread(target=self._read, daemon=True)
self.reader.start()
@@ -352,7 +352,7 @@ def horizon_client_joins(vanilla_server, binary, world, build, reference):
server = Server(vanilla_server, directory, label)
try:
server.wait_for(r'Done \(')
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report))
env = lab.game_env(HORIZON_NET_REPORT=report)
with (build / 'horizon-client-run.log').open('w') as log:
subprocess.run([str(c) for c in [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
'--server', f'127.0.0.1:{port}', '--name', PLAYER]],
+1 -1
View File
@@ -417,7 +417,7 @@ def main():
run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+1 -1
View File
@@ -96,7 +96,7 @@ class Game:
self.process = subprocess.Popen(Game.prefix + [
str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain',
'--control-socket', str(self.endpoint), '--timeout-seconds', '600',
] + Game.extra, cwd=self.home, env=dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_NO_AUDIO='1', **env),
] + Game.extra, cwd=self.home, env=lab.game_env(HORIZON_HOME=self.home, **env),
stdout=self.log, stderr=subprocess.STDOUT)
wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title')
+1 -1
View File
@@ -170,7 +170,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+1 -1
View File
@@ -71,7 +71,7 @@ def main():
str(executable), '--radius', '1', '--frames', '30',
'--smoke-report', str(report), '--timeout-seconds', '60']
with (root / 'startup-smoke.log').open('w') as log:
subprocess.run(command, cwd=lab.ROOT, env=environment, check=True,
subprocess.run(command, cwd=lab.ROOT, env=lab.game_env(environment), check=True,
stdout=log, stderr=subprocess.STDOUT, timeout=120)
result = json.loads(report.read_text())
if (result.get('error') is not None or result.get('presented_frames') != 30
+2 -2
View File
@@ -179,7 +179,7 @@ def run_client(binary, build, port, label, token, discovery):
shutil.rmtree(directory, ignore_errors=True)
directory.mkdir()
report = directory / 'report.json'
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report), HORIZON_API_DISCOVERY=discovery)
env = lab.game_env(HORIZON_NET_REPORT=report, HORIZON_API_DISCOVERY=discovery)
command = [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
'--server', f'127.0.0.1:{port}', '--name', PLAYER]
if token:
@@ -246,7 +246,7 @@ def run_side(label, command, binary, build, services, discovery):
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
(directory / 'eula.txt').write_text('eula=true\n')
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery))
server = Server(command, directory, f'{label}-online')
checks = []
starts = []
+2 -2
View File
@@ -330,7 +330,7 @@ def entity_uuid_text(i):
def vscreen_env():
text = subprocess.run(['vscreen', 'env'], capture_output=True, text=True, check=True).stdout
env = dict(os.environ)
env = lab.game_env()
env.pop('DISPLAY', None)
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
env[match.group(1)] = match.group(2)
@@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir):
ctl = [str(bin_dir / 'horizon-ctl'), '--socket', str(socket)]
extra = []
if sys.platform == 'darwin':
env = dict(os.environ, HORIZON_NO_AUDIO='1')
env = lab.game_env()
extra = ['--offscreen']
else:
alsa = destination / 'null-asound.conf'
+1 -1
View File
@@ -339,7 +339,7 @@ def main():
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'],
build, 'compile-rust')
oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon',
env={**os.environ, 'HORIZON_SCULK_FIXTURE': f'{inputs},{build / "horizon.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_SCULK_FIXTURE=f'{inputs},{build / "horizon.txt"}'))
if args.java_only:
return
names = {s[0] for _, s in chosen}
+1 -1
View File
@@ -264,7 +264,7 @@ def main():
oh.run_logged([*java, 'keys', build], build, 'keys')
services = Services(json.loads((build / 'publickeys.json').read_text()))
discovery = services.url + '/minecraft/client'
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery))
servers = {
'vanilla': ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}',
'-cp', dependencies, 'net.minecraft.server.Main', 'nogui'],
+1 -1
View File
@@ -375,7 +375,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+4 -1
View File
@@ -24,6 +24,9 @@ import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3'
RUN = ROOT / '.local' / 'world-reopen'
@@ -32,7 +35,7 @@ CYCLES = 3
def game_env():
"""macOS renders offscreen; Linux uses the virtual screen (as test_save_roundtrip_parity)."""
env = dict(os.environ, HORIZON_NO_AUDIO='1')
env = lab.game_env()
if sys.platform == 'darwin':
return env, ['--offscreen']
subprocess.run(['vscreen', 'up'], check=False, capture_output=True)
+1 -1
View File
@@ -140,7 +140,7 @@ def main():
# One worker thread: the chunks decorated in a fixed order (see above).
vanilla_server = ['java', '-Xmx2g', '-Dmax.bg.threads=1', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui']
os.environ['HORIZON_NO_AUDIO'] = '1'
os.environ.update(lab.game_env())
def one(seed):
t0 = time.time()