Merge feature/ci/wordpress0-playwright-parallel into feature/store-i18n

- feature/ci/wordpress0-playwright-parallel (de40211272, 88/6, merged on
  the operator's word below the gate): roles that opt in through
  playwright.parallel (WordPress) run independent Playwright suites in
  parallel under a CPU-pressure gate, with dependency deferral, an onion
  cap and Tor lock, crash counting and per-job artifacts; roles without
  the opt-in run as before. The next push's WordPress#0 CI run is its
  live proof.

🎯 Fix: 88 %
💥 Break: 6 %
🌱 Efficiency: –
⚡ Speed: –
🛡️ Security: ~100 %
🏆 Score: 83
🚦 Gate: ⛔ fix 88 % < 90, break 6 % > 5; merged on the operator's word, CI is the live proof

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 5.5 committed 2026-11-05 15:11:52 +00:00
commit 6d4e5f7c59
16 files changed
+2474 -86

No files matched your search

@@ -1,3 +1,30 @@
from pathlib import Path
from utils.cache.yaml import load_yaml_any
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
ROLE: Path = PROJECT_ROOT / "roles" / "test-e2e-playwright"
def role_task(task_file: str, prefix: str) -> dict:
"""Find a task of the Playwright role by the start of its name.
Args:
task_file: path of the task file below the role's ``tasks`` directory.
prefix: the start of the task name, usually its emoji.
Returns:
The first matching task, searched depth first through ``block``,
``rescue`` and ``always``.
"""
pending = list(
load_yaml_any(str(ROLE / "tasks" / task_file), default_if_missing=[])
)
while pending:
task = pending.pop(0)
if task.get("name", "").startswith(prefix):
return task
pending[:0] = (
task.get("block", []) + task.get("rescue", []) + task.get("always", [])
)
raise LookupError(f"{task_file}: no task named {prefix}")
@@ -0,0 +1,5 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
__all__ = ["PROJECT_ROOT"]
@@ -0,0 +1,745 @@
import fcntl
import importlib.util
import itertools
import json
import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from . import PROJECT_ROOT
def _load_module():
path = PROJECT_ROOT / "roles" / "test-e2e-playwright" / "files" / "run_parallel.py"
spec = importlib.util.spec_from_file_location("playwright_run_parallel", path)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules["playwright_run_parallel"] = module
spec.loader.exec_module(module)
return module
rp = _load_module()
ROW = [
("web-app-keycloak", 118),
("web-app-hermes", 50),
("web-app-matomo", 165),
("web-app-openclaw", 29),
("web-app-weblate", 84),
("web-svc-cdn", 8),
("web-svc-design", 85),
("web-svc-logout", 76),
("web-svc-mirror", 7),
("web-svc-simpleicons", 8),
("web-svc-translate", 20),
("web-app-dashboard", 247),
("web-app-discourse", 224),
("web-app-stalwart", 162),
("web-app-jitsi", 65),
("web-app-matrix", 449),
("web-app-prometheus", 39),
("web-app-wordpress", 182),
]
def simulate(jobs, cap, release=None):
"""Drive a Plan on a virtual clock.
Args:
jobs: ``(Job, seconds)`` in submission order.
cap: the plan's concurrency cap.
release: per job id, the virtual second its file appears; 0 when absent.
Returns:
``(starts, ends, peak)``: per job id its start and end second, and the
most jobs that ever ran at once.
"""
release = release or {}
plan = rp.Plan(cap)
durations = {job.id: seconds for job, seconds in jobs}
queue = list(jobs)
starts, ends, running = {}, {}, {}
now, peak = 0.0, 0
while True:
while queue and release.get(queue[0][0].id, 0) <= now:
plan.submit(queue.pop(0)[0])
if not queue:
plan.seal()
for job in plan.start_next():
starts[job.id] = now
running[job.id] = now + durations[job.id]
peak = max(peak, len(running))
if plan.done():
return starts, ends, peak
events = list(running.values()) + (
[release.get(queue[0][0].id, 0)] if queue else []
)
now = min(event for event in events if event >= now)
for job_id, end in list(running.items()):
if end <= now:
del running[job_id]
ends[job_id] = end
plan.finish(job_id)
def row_jobs():
head = ROW[0][0]
return [
(rp.Job(app, () if app == head else (head,)), seconds) for app, seconds in ROW
]
class TestPlan(unittest.TestCase):
def test_the_cap_is_never_exceeded(self):
for cap in (1, 2, 3, 4):
with self.subTest(cap=cap):
_, _, peak = simulate(row_jobs(), cap)
self.assertLessEqual(peak, cap)
def test_cap_one_reproduces_the_serial_order(self):
starts, ends, _ = simulate(row_jobs(), 1)
order = sorted(starts, key=starts.get)
self.assertEqual(order, [app for app, _ in ROW])
for previous, following in itertools.pairwise(order):
self.assertLessEqual(ends[previous], starts[following])
def test_no_job_starts_before_the_jobs_it_runs_after(self):
jobs = row_jobs()
jobs[13] = (
rp.Job("web-app-stalwart", ("web-app-keycloak", "web-app-matomo")),
162,
)
starts, ends, _ = simulate(jobs, 3)
for job, _ in jobs:
for dep in job.after:
self.assertGreaterEqual(
starts[job.id], ends[dep], f"{job.id} started before {dep} ended"
)
def test_the_identity_provider_runs_alone_first(self):
starts, ends, _ = simulate(row_jobs(), 3)
head = ROW[0][0]
self.assertEqual(starts[head], 0)
self.assertTrue(all(starts[app] >= ends[head] for app, _ in ROW[1:]))
def test_every_job_runs_exactly_once(self):
starts, ends, _ = simulate(row_jobs(), 3)
self.assertEqual(set(starts), {app for app, _ in ROW})
self.assertEqual(set(ends), set(starts))
def test_a_dependency_that_is_not_submitted_yet_holds_the_job(self):
plan = rp.Plan(3)
plan.submit(rp.Job("b", ("a",)))
self.assertEqual(plan.start_next(), [])
plan.submit(rp.Job("a", ()))
self.assertEqual([job.id for job in plan.start_next()], ["a"])
def test_a_dependency_that_never_ran_defers_its_dependents_transitively(self):
plan = rp.Plan(3)
plan.submit(rp.Job("b", ("dropped",)))
plan.submit(rp.Job("c", ("b",)))
plan.submit(rp.Job("d", ()))
plan.seal()
self.assertEqual([job.id for job in plan.start_next()], ["d"])
self.assertEqual([job.id for job in plan.defer_orphans()], ["b", "c"])
plan.finish("d")
self.assertTrue(plan.done())
def test_a_ready_job_overtakes_a_blocked_one_but_keeps_submission_order(self):
plan = rp.Plan(2)
plan.submit(rp.Job("a", ()))
plan.submit(rp.Job("b", ("a",)))
plan.submit(rp.Job("c", ()))
plan.submit(rp.Job("d", ()))
self.assertEqual([job.id for job in plan.start_next()], ["a", "c"])
def test_an_unsatisfiable_sealed_list_raises(self):
plan = rp.Plan(2)
plan.submit(rp.Job("a", ("b",)))
plan.submit(rp.Job("b", ("a",)))
plan.seal()
self.assertEqual(plan.start_next(), [])
with self.assertRaises(RuntimeError):
plan.defer_orphans()
def test_a_duplicate_submission_raises(self):
plan = rp.Plan(2)
plan.submit(rp.Job("a", ()))
with self.assertRaises(ValueError):
plan.submit(rp.Job("a", ()))
def test_a_cap_below_one_raises(self):
with self.assertRaises(ValueError):
rp.Plan(0)
def test_the_measured_row_drains_well_inside_the_serial_time(self):
setup = 27
release = {app: setup * (index + 1) for index, (app, _) in enumerate(ROW)}
_, ends, _ = simulate(row_jobs(), 3, release)
serial = sum(seconds + setup for _, seconds in ROW)
self.assertEqual(serial, 2504)
self.assertEqual(max(ends.values()), 1020)
class FakeHost:
"""Pressure and meminfo files a test rewrites at will.
Args:
root: directory for the two files.
"""
def __init__(self, root: Path) -> None:
self.pressure = root / "pressure"
self.meminfo = root / "meminfo"
self.now = 0.0
self.set(cpu_avg10=5.0, mem_available_mb=8192)
def set(
self, *, cpu_avg10: float, mem_available_mb: int, cpu_avg60: float = 1.0
) -> None:
self.pressure.write_text(
f"some avg10={cpu_avg10:.2f} avg60={cpu_avg60:.2f} avg300=1.00 total=1\n"
"full avg10=0.00 avg60=0.00 avg300=0.00 total=0\n"
)
self.meminfo.write_text(
f"MemTotal: 16000000 kB\nMemAvailable: {mem_available_mb * 1024} kB\n"
)
def gate(self, sustain: float = 0.0, clock=time.monotonic) -> "rp.HostGate":
return rp.HostGate(36.0, 0.5, sustain, self.pressure, self.meminfo, clock)
class TestHostGate(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="host_gate_")
self.addCleanup(self.tmp.cleanup)
self.host = FakeHost(Path(self.tmp.name))
self.clock = [0.0]
self.gate = self.host.gate(sustain=30.0, clock=lambda: self.clock[0])
def _samples(self, seconds, **load):
self.host.set(**load)
for _ in range(seconds):
self.gate.observe()
self.clock[0] += 1.0
def test_the_first_container_always_starts(self):
self.host.set(cpu_avg10=99.0, cpu_avg60=99.0, mem_available_mb=10)
self.gate.observe()
self.assertTrue(self.gate.admits(0, 1536))
def test_a_further_container_needs_a_full_calm_window(self):
self._samples(29, cpu_avg10=5.0, mem_available_mb=8192)
self.assertFalse(self.gate.admits(1, 1536))
self._samples(2, cpu_avg10=5.0, mem_available_mb=8192)
self.assertTrue(self.gate.admits(1, 1536))
def test_a_single_dip_in_avg10_does_not_admit(self):
self._samples(60, cpu_avg10=50.0, cpu_avg60=50.0, mem_available_mb=8192)
self._samples(1, cpu_avg10=10.0, cpu_avg60=50.0, mem_available_mb=8192)
self.assertFalse(self.gate.admits(1, 1536))
self._samples(40, cpu_avg10=10.0, cpu_avg60=50.0, mem_available_mb=8192)
self.assertFalse(self.gate.admits(1, 1536))
def test_one_hot_sample_restarts_the_window(self):
self._samples(25, cpu_avg10=5.0, mem_available_mb=8192)
self._samples(1, cpu_avg10=36.5, mem_available_mb=8192)
self._samples(25, cpu_avg10=5.0, mem_available_mb=8192)
self.assertFalse(self.gate.admits(1, 1536))
self._samples(6, cpu_avg10=5.0, mem_available_mb=8192)
self.assertTrue(self.gate.admits(1, 1536))
def test_a_start_restarts_the_window(self):
self._samples(31, cpu_avg10=5.0, mem_available_mb=8192)
self.assertTrue(self.gate.admits(1, 1536))
self.assertFalse(self.gate.admits(2, 1536))
self._samples(31, cpu_avg10=5.0, mem_available_mb=8192)
self.assertTrue(self.gate.admits(2, 1536))
def test_an_estimate_above_half_the_free_memory_holds_the_next_container(self):
self._samples(31, cpu_avg10=5.0, mem_available_mb=3071)
self.assertFalse(self.gate.admits(1, 1536))
self._samples(1, cpu_avg10=5.0, mem_available_mb=3072)
self.assertTrue(self.gate.admits(1, 1536))
def test_an_unreadable_host_keeps_the_round_serial(self):
self.host.pressure.unlink()
for _ in range(60):
self.gate.observe()
self.clock[0] += 1.0
self.assertFalse(self.gate.admits(1, 1536))
self.assertTrue(self.gate.admits(0, 1536))
class TestRun(unittest.TestCase):
SCHEDULER = (
PROJECT_ROOT / "roles" / "test-e2e-playwright" / "files" / "run_parallel.py"
)
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="run_parallel_")
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.jobs = self.root / "jobs"
self.jobs.mkdir()
self.trace = self.root / "trace.log"
self.host = FakeHost(self.root)
self.tor_lock = self.root / "tor.lock"
def _job(
self,
index,
job_id,
seconds,
*,
rc=0,
after=(),
timeout=60,
tor=False,
name=None,
):
script = (
"import sys,time;"
f"open({str(self.trace)!r},'a').write('start {job_id} %f\\n' % time.time());"
f"time.sleep({seconds});"
f"open({str(self.trace)!r},'a').write('end {job_id} %f\\n' % time.time());"
f"print('out-{job_id}');print('err-{job_id}',file=sys.stderr);sys.exit({rc})"
)
spec = {
"id": job_id,
"argv": [sys.executable, "-c", script],
"env": {"PLAYWRIGHT_TEST_MARKER": job_id},
"timeout": timeout,
"after": list(after),
"tor": tor,
"workers": 1,
"memory_mb": 1536,
"stop": [
sys.executable,
"-c",
f"open({str(self.root / ('stopped-' + job_id))!r},'w').write('x')",
],
"meta": {"reports_dir": f"/reports/{job_id}"},
}
(self.jobs / (name or f"{index}-{job_id}.job.json")).write_text(
json.dumps(spec)
)
def _run(self, cap, poll=0.05, onion_cap=3):
return rp.run(
self.jobs,
cap,
poll,
self.host.gate(),
rp.TorReaders(self.tor_lock, onion_cap),
)
def _result(self, job_id):
text = (self.jobs / f"{job_id}.result.json").read_text() # nocheck: cache-read
return json.loads(text)
def _trace(self):
text = self.trace.read_text() # nocheck: cache-read
return [line.split() for line in text.splitlines()]
def _stamps(self, kind, job_id):
return [
float(stamp)
for event, name, stamp in self._trace()
if [event, name] == [kind, job_id]
]
def _peak(self):
live, peak = 0, 0
events = sorted(
(float(stamp), 1 if kind == "start" else -1)
for kind, _, stamp in self._trace()
)
for _, delta in events:
live += delta
peak = max(peak, live)
return peak
def test_jobs_run_concurrently_within_the_cap_and_keep_their_own_results(self):
self._job(0, "head", 0.3)
for index, name in enumerate(["a", "b", "c", "d"], start=1):
self._job(index, name, 0.6, rc=1 if name == "b" else 0, after=["head"])
(self.jobs / rp.SEALED).touch()
began = time.monotonic()
self.assertEqual(self._run(2), 0)
elapsed = time.monotonic() - began
self.assertEqual(self._peak(), 2)
self.assertLess(elapsed, 0.3 + 4 * 0.6)
self.assertEqual(self._result("b")["rc"], 1)
for name in ("head", "a", "c", "d"):
self.assertEqual(self._result(name)["rc"], 0)
self.assertEqual(self._result(name)["stdout"].strip(), f"out-{name}")
self.assertEqual(self._result(name)["stderr"].strip(), f"err-{name}")
self.assertEqual(
self._result(name)["meta"], {"reports_dir": f"/reports/{name}"}
)
head_end = self._stamps("end", "head")[0]
for name in ("a", "b", "c", "d"):
self.assertGreaterEqual(self._stamps("start", name)[0], head_end)
def test_a_hot_host_runs_the_round_serially(self):
self.host.set(cpu_avg10=80.0, mem_available_mb=8192)
for index, name in enumerate(["a", "b", "c"]):
self._job(index, name, 0.2)
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(3), 0)
self.assertEqual(self._peak(), 1)
def test_a_timeout_kills_only_its_own_job_and_says_so_in_stderr(self):
self._job(0, "slow", 30, timeout=0.5)
self._job(1, "fast", 0.2)
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(2), 0)
slow = self._result("slow")
self.assertTrue(slow["timed_out"])
self.assertNotIn("rc", slow)
self.assertIn("timeout", slow["msg"])
self.assertIn(slow["msg"], slow["stderr"])
self.assertTrue((self.root / "stopped-slow").exists())
self.assertEqual(self._result("fast")["rc"], 0)
def test_jobs_streamed_before_the_seal_are_all_run(self):
self._job(0, "first", 0.2)
runner = threading.Thread(target=self._run, args=(3,))
runner.start()
time.sleep(0.4)
self._job(1, "second", 0.1)
(self.jobs / rp.SEALED).touch()
runner.join(timeout=10)
self.assertFalse(runner.is_alive())
self.assertEqual(self._result("first")["rc"], 0)
self.assertEqual(self._result("second")["rc"], 0)
def test_the_temp_file_ansible_copy_writes_is_ignored(self):
self._job(0, "a", 0.1)
self._job(1, "b", 0.1, name=".ansible_tmpk3j2x11-b.job.json")
(self.jobs / ".ansible_tmpq9z").write_text("{")
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(2), 0)
self.assertEqual(self._result("a")["rc"], 0)
self.assertFalse((self.jobs / "b.result.json").exists())
def test_a_freed_slot_is_refilled_without_waiting_a_poll(self):
self._job(0, "a", 0.2)
self._job(1, "b", 0.1, after=["a"])
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(1, poll=1.0), 0)
self.assertLess(
self._stamps("start", "b")[0] - self._stamps("end", "a")[0], 0.6
)
def test_a_scheduler_crash_stops_every_running_container(self):
self._job(0, "long", 30)
runner_error = []
def drive():
try:
self._run(2)
except Exception as exc:
runner_error.append(exc)
runner = threading.Thread(target=drive)
runner.start()
deadline = time.monotonic() + 5
while not self.trace.exists() and time.monotonic() < deadline:
time.sleep(0.05)
(self.jobs / "1-broken.job.json").write_text("{not json")
runner.join(timeout=30)
self.assertFalse(runner.is_alive())
self.assertEqual(len(runner_error), 1)
self.assertTrue((self.root / "stopped-long").exists())
self.assertEqual(self._stamps("end", "long"), [])
def _scheduler(self) -> subprocess.Popen:
return subprocess.Popen(
[
sys.executable,
str(self.SCHEDULER),
str(self.jobs),
"2",
"0.05",
"36",
"0.5",
"0",
str(self.tor_lock),
"3",
],
env=os.environ.copy(),
)
def test_a_marker_a_killed_probe_left_in_an_earlier_round_does_not_hold_onion_runs(
self,
):
self.tor_lock.with_name(self.tor_lock.name + ".recreate-pending").touch()
self._job(0, "onion", 0.1, tor=True)
(self.jobs / rp.SEALED).touch()
proc = self._scheduler()
try:
self.assertEqual(proc.wait(timeout=10), 0)
finally:
proc.kill()
self.assertEqual(self._result("onion")["rc"], 0)
def test_sigterm_to_the_scheduler_stops_its_containers(self):
self._job(0, "long", 30)
proc = self._scheduler()
deadline = time.monotonic() + 10
while not self.trace.exists() and time.monotonic() < deadline:
time.sleep(0.05)
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=30), 128 + signal.SIGTERM)
self.assertTrue((self.root / "stopped-long").exists())
def test_an_onion_job_waits_while_tor_is_being_recreated(self):
self._job(0, "onion", 0.1, tor=True)
self._job(1, "clear", 0.1)
writer = os.open(self.tor_lock, os.O_RDWR | os.O_CREAT, 0o644)
fcntl.flock(writer, fcntl.LOCK_EX)
(self.jobs / rp.SEALED).touch()
runner = threading.Thread(target=self._run, args=(2,))
runner.start()
time.sleep(0.6)
self.assertEqual(self._stamps("start", "onion"), [])
self.assertEqual(len(self._stamps("end", "clear")), 1)
released = time.time()
fcntl.flock(writer, fcntl.LOCK_UN)
os.close(writer)
runner.join(timeout=10)
self.assertGreaterEqual(self._stamps("start", "onion")[0], released)
def test_onion_jobs_share_tor_with_each_other(self):
self._job(0, "onion-a", 0.5, tor=True)
self._job(1, "onion-b", 0.5, tor=True)
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(2), 0)
self.assertEqual(self._peak(), 2)
def test_onion_jobs_stay_within_the_tor_cap(self):
for index, name in enumerate(["onion-a", "onion-b", "onion-c"]):
self._job(index, name, 0.4, tor=True)
self._job(3, "clear", 0.4)
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(4, onion_cap=1), 0)
onion = sorted(
(self._stamps("start", name)[0], self._stamps("end", name)[0])
for name in ("onion-a", "onion-b", "onion-c")
)
for (_, previous_end), (next_start, _) in itertools.pairwise(onion):
self.assertGreaterEqual(next_start, previous_end)
self.assertLess(self._stamps("start", "clear")[0], onion[0][1])
def test_a_dropped_identity_provider_runs_none_of_its_dependents_here(self):
head = "web-app-keycloak"
self._job(1, "a", 0.1, after=[head])
self._job(2, "b", 0.1, after=[head])
self._job(3, "c", 0.1, after=[head, "b"])
(self.jobs / rp.SEALED).touch()
self.assertEqual(self._run(3), 0)
self.assertFalse(self.trace.exists())
self.assertEqual(self._result("a")["deferred"], [head])
self.assertEqual(self._result("c")["deferred"], [head, "b"])
self.assertNotIn("rc", self._result("b"))
def test_no_onion_job_starts_while_a_recreate_is_pending(self):
self._job(0, "onion", 0.1, tor=True)
pending = self.tor_lock.with_name(self.tor_lock.name + ".recreate-pending")
pending.touch()
(self.jobs / rp.SEALED).touch()
runner = threading.Thread(target=self._run, args=(2,))
runner.start()
time.sleep(0.5)
self.assertFalse(self.trace.exists())
cleared = time.time()
pending.unlink()
runner.join(timeout=10)
self.assertGreaterEqual(self._stamps("start", "onion")[0], cleared)
class TestRunSignals(unittest.TestCase):
def test_retries_flaky_tests_and_crashed_pages_are_counted(self):
output = (
" ✘ 3 tests/a.js:1:1 › login (retry #1) (2.1m)\n"
" ✓ 4 tests/a.js:1:1 › login (retry #2) (1.0m)\n"
"Error: page.goto: Page crashed\n"
" 1 flaky\n"
" 12 passed (9.0m)\n"
)
self.assertEqual(
rp.run_signals(output),
{"retries": 2, "flaky": 1, "crashes": 1, "crash_kinds": "page crashed 1"},
)
def test_a_killed_browser_or_worker_that_a_retry_hid_is_still_named(self):
output = (
" ✘ 1 tests/a.js:1:1 › login (2.1m)\n"
"Error: browserType.launch: Browser closed.\n"
"Error: page.click: Target page, context or browser has been closed\n"
"Error: worker process exited unexpectedly (code=null, signal=SIGKILL)\n"
" ✓ 2 tests/a.js:1:1 › login (retry #1) (1.0m)\n"
" 1 flaky\n"
)
self.assertEqual(
rp.run_signals(output),
{
"retries": 1,
"flaky": 1,
"crashes": 3,
"crash_kinds": "browser closed (OOM or timeout) 2, worker killed 1",
},
)
def test_a_clean_run_reports_nothing(self):
self.assertEqual(
rp.run_signals(" 12 passed (9.0m)\n"),
{"retries": 0, "flaky": 0, "crashes": 0, "crash_kinds": ""},
)
class TestTorRecreateWaitsForOnionRuns(unittest.TestCase):
"""The probe script recreates Tor only once no onion run holds the lock."""
SCRIPT = (
PROJECT_ROOT
/ "roles"
/ "test-e2e-playwright"
/ "files"
/ "wait_onion_reachable.sh"
)
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="tor_lock_")
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.bin = self.root / "bin"
self.bin.mkdir()
self.marker = self.root / "recreated"
self.answers = self.root / "onion-answers"
self.lock = self.root / "tor.lock"
self.pending = self.root / "tor.lock.recreate-pending"
(self.bin / "curl").write_text(
f"#!/bin/sh\nif [ -e {self.answers} ]; then printf 200; exit 0; fi\nexit 7\n"
)
(self.bin / "docker").write_text(
"#!/bin/sh\n"
f"if [ \"$2\" = update ]; then python3 -c \"import time; open('{self.marker}','w').write(str(time.time()))\"; fi\n"
"exit 0\n"
)
for stub in ("curl", "docker"):
(self.bin / stub).chmod(0o755)
def start(self, script: Path, lock: str) -> subprocess.Popen:
"""Start *script* with one attempt, a 2 s delay and a 1 s max time.
Args:
script: the probe script under test.
lock: the Tor lock argument, empty for the serial run.
Returns:
The running script.
"""
return subprocess.Popen(
[
"bash",
str(script),
"127.0.0.1:9050",
"x.onion",
"1",
"2",
"1",
str(self.root),
lock,
],
env={**os.environ, "PATH": f"{self.bin}:{os.environ['PATH']}"},
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
def run_script(
self, script: Path, hold: float, answer_at: float | None = None
) -> tuple[float | None, int, str, bool]:
"""Run *script* in the parallel mode while a reader holds the Tor lock.
Args:
script: the probe script under test.
hold: seconds the shared lock is held after the script starts.
answer_at: second at which the onion starts to answer, None for never.
Returns:
Recreate time minus release time (None when it never recreated),
the exit code, stderr, and whether the pending marker existed
while the script waited.
"""
reader = os.open(self.lock, os.O_RDONLY | os.O_CREAT, 0o644)
fcntl.flock(reader, fcntl.LOCK_SH)
proc = self.start(script, str(self.lock))
began = time.monotonic()
announced, released = False, None
events = [(min(hold, 2.5), "look"), (hold, "release")]
if answer_at is not None:
events.append((answer_at, "answer"))
for at, event in sorted(events):
time.sleep(max(0.0, at - (time.monotonic() - began)))
if event == "look":
announced = self.pending.exists()
elif event == "answer":
self.answers.touch()
else:
released = time.time()
fcntl.flock(reader, fcntl.LOCK_UN)
os.close(reader)
_, stderr = proc.communicate(timeout=20)
recreated = None
if self.marker.exists():
recreated = float(self.marker.read_text()) - released # nocheck: cache-read
self.assertFalse(self.pending.exists())
return recreated, proc.returncode, stderr, announced
def test_the_recreate_waits_until_the_onion_run_releases_tor(self):
recreated, rc, _, announced = self.run_script(self.SCRIPT, hold=3.0)
self.assertIsNotNone(recreated)
self.assertGreaterEqual(recreated, 0)
self.assertTrue(announced)
self.assertEqual(rc, 1)
def test_onion_runs_outlasting_the_wait_skip_the_recreate_and_a_recovered_onion_passes(
self,
):
recreated, rc, stderr, _ = self.run_script(self.SCRIPT, hold=6.0, answer_at=3.0)
self.assertIsNone(recreated)
self.assertEqual(rc, 0)
self.assertIn(
"skipped recreating Tor for x.onion: onion Playwright runs held", stderr
)
def test_onion_runs_outlasting_the_wait_fail_only_this_probe_when_the_onion_stays_silent(
self,
):
recreated, rc, stderr, _ = self.run_script(self.SCRIPT, hold=6.0)
self.assertIsNone(recreated)
self.assertEqual(rc, 1)
self.assertIn("skipped recreating Tor", stderr)
def test_the_serial_run_recreates_at_once_without_touching_the_lock(self):
began = time.time()
proc = self.start(self.SCRIPT, "")
stdout, _ = proc.communicate(timeout=20)
self.assertEqual(proc.returncode, 1)
recreated = float(self.marker.read_text()) # nocheck: cache-read
self.assertLess(recreated - began, 2 + 1.5)
self.assertIn("recreating Tor for fresh circuits", stdout)
self.assertNotIn("waiting up to", stdout)
self.assertFalse(self.lock.exists())
self.assertFalse(self.pending.exists())
@@ -0,0 +1,180 @@
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from ansible.errors import AnsibleError
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from plugins.lookup.role_tests import LookupModule as RoleTestsLookup
from utils.cache.yaml import dump_yaml, load_yaml_any
from utils.roles.mapping import ROLE_FILE_META_TESTS, ROLE_FILE_META_VARIANTS
from . import PROJECT_ROOT
def _load_module():
path = (
PROJECT_ROOT
/ "roles"
/ "test-e2e-playwright"
/ "lookup_plugins"
/ "playwright_parallel.py"
)
spec = importlib.util.spec_from_file_location("playwright_parallel_lookup", path)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules["playwright_parallel_lookup"] = module
spec.loader.exec_module(module)
return module
_plugin = _load_module()
def declared_caps() -> dict:
"""Collect every role's ``playwright.parallel`` entry.
Returns:
The declared value per role name, for the roles that declare one.
"""
found = {}
for role in sorted(
path for path in (PROJECT_ROOT / "roles").iterdir() if path.is_dir()
):
playwright = (
load_yaml_any(str(role / ROLE_FILE_META_TESTS), default_if_missing={}) or {}
).get("playwright") or {}
if "parallel" in playwright:
found[role.name] = playwright["parallel"]
return found
class TestRowCap(unittest.TestCase):
def test_an_app_without_the_list_runs_one_container(self):
self.assertEqual(_plugin.row_cap("web-app-x", None, 0), 1)
def test_the_entry_of_the_round_variant_is_the_cap(self):
self.assertEqual(_plugin.row_cap("web-app-x", [3, 1, 2], 2), 2)
def test_a_round_beyond_the_declared_variants_runs_serially(self):
self.assertEqual(_plugin.row_cap("web-app-x", [3], 1), 1)
self.assertEqual(_plugin.row_cap("web-app-x", [3], 3), 1)
def test_a_non_positive_or_non_integer_entry_is_rejected(self):
for caps in ([0], [-1], ["3"], [True], 3, {"0": 3}):
with self.subTest(caps=caps), self.assertRaises(AnsibleError):
_plugin.validate_caps("web-app-x", caps)
class TestPlaywrightParallelLookup(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="playwright_parallel_")
self.addCleanup(self.tmp.cleanup)
self.playbook_dir = Path(self.tmp.name)
for role in ("web-app-a", "web-app-b", "web-app-c"):
(self.playbook_dir / "roles" / role / "meta").mkdir(parents=True)
dump_yaml(
self.playbook_dir / "roles" / "web-app-a" / ROLE_FILE_META_TESTS,
{"playwright": {"parallel": [3, 1]}},
)
dump_yaml(
self.playbook_dir / "roles" / "web-app-b" / ROLE_FILE_META_TESTS,
{"playwright": {"parallel": [2, 4]}},
)
def _cap(self, primary_apps, variant, playbook_dir=None) -> int:
variables = {
"playbook_dir": str(playbook_dir or self.playbook_dir),
"PRIMARY_APPS": primary_apps,
"VARIANT_INDEX": variant,
}
templar = Templar(loader=DataLoader(), variables=variables)
lookup = _plugin.LookupModule(loader=DataLoader(), templar=templar)
role_tests = RoleTestsLookup(loader=DataLoader(), templar=templar)
with patch.object(_plugin, "lookup_loader") as loader:
loader.get.return_value = role_tests
return lookup.run([], variables=variables)[0]
def test_a_round_without_primary_apps_runs_one_container(self):
self.assertEqual(self._cap([], 0), 1)
def test_the_primary_app_row_sets_the_cap(self):
self.assertEqual(self._cap(["web-app-a"], 0), 3)
self.assertEqual(self._cap(["web-app-a"], 1), 1)
def test_a_primary_app_that_did_not_opt_in_keeps_the_round_serial(self):
self.assertEqual(self._cap(["web-app-a", "web-app-c"], 0), 1)
def test_several_primary_apps_take_the_smallest_cap(self):
self.assertEqual(self._cap(["web-app-a", "web-app-b"], 0), 2)
self.assertEqual(self._cap(["web-app-a", "web-app-b"], 1), 1)
def test_the_cli_string_form_of_primary_apps_opts_the_row_in(self):
self.assertEqual(self._cap('["web-app-a"]', "0"), 3)
self.assertEqual(self._cap('["web-app-wordpress"]', "0", PROJECT_ROOT), 3)
self.assertEqual(self._cap("[]", "0"), 1)
def test_a_primary_apps_value_that_is_no_list_warns_and_keeps_the_round_serial(
self,
):
for value in ("web-app-a", '"web-app-a"', '{"a": 1}', "[1]"):
with self.subTest(value=value), patch.object(_plugin, "Display") as display:
self.assertEqual(self._cap(value, "0"), 1)
display.return_value.warning.assert_called_once()
def test_a_multi_app_round_beyond_a_primary_variants_runs_serially(self):
for variant in ("1", "2", "3"):
with self.subTest(variant=variant):
self.assertEqual(
self._cap(
'["web-app-wordpress","web-app-nextcloud"]',
variant,
PROJECT_ROOT,
),
1,
)
self.assertEqual(self._cap('["web-app-a","web-app-b"]', "5"), 1)
def test_a_malformed_cap_list_warns_and_keeps_the_round_serial(self):
dump_yaml(
self.playbook_dir / "roles" / "web-app-c" / ROLE_FILE_META_TESTS,
{"playwright": {"parallel": "3"}},
)
with patch.object(_plugin, "Display") as display:
self.assertEqual(self._cap(["web-app-c"], 0), 1)
display.return_value.warning.assert_called_once()
def test_every_declared_cap_list_is_valid_and_covers_every_variant(self):
for role, caps in declared_caps().items():
with self.subTest(role=role):
_plugin.validate_caps(role, caps)
variants = load_yaml_any(
str(PROJECT_ROOT / "roles" / role / ROLE_FILE_META_VARIANTS),
default_if_missing=[{}],
)
self.assertEqual(len(caps), len(variants))
def test_the_sizing_terms_follow_playwright_workers(self):
lookup = _plugin.LookupModule(
loader=DataLoader(), templar=Templar(loader=DataLoader())
)
self.assertEqual(lookup.run(["memory_mb"], workers="1"), [1536])
self.assertEqual(lookup.run(["memory_mb"], workers=2), [3072])
self.assertEqual(lookup.run(["ram_fraction"]), [0.5])
self.assertEqual(lookup.run(["onion_cap"]), [3])
def test_wordpress_opts_in_its_first_row_only(self):
self.assertEqual(self._cap(["web-app-wordpress"], 0, PROJECT_ROOT), 3)
self.assertEqual(self._cap(["web-app-wordpress"], 1, PROJECT_ROOT), 1)
self.assertEqual(self._cap(["web-app-wordpress"], 2, PROJECT_ROOT), 1)
def test_every_other_role_keeps_the_serial_runner(self):
self.assertEqual(sorted(declared_caps()), ["web-app-wordpress"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,514 @@
import base64
import importlib.util
import json
import re
import shlex
import sys
import tempfile
import time
import unittest
from pathlib import Path
import jinja2
from ansible.parsing.dataloader import DataLoader
from ansible.plugins.filter.core import FilterModule
from ansible.plugins.test.core import TestModule
from ansible.template import Templar
from jinja2.nativetypes import NativeEnvironment
from plugins.lookup.role_tests import LookupModule as RoleTestsLookup
from plugins.lookup.timeout import scaled_timeout
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml_any
from utils.roles.mapping import (
ROLE_FILE_DEFAULTS_MAIN,
ROLE_FILE_META_NETWORKS,
ROLE_FILE_VARS_MAIN,
)
from . import PROJECT_ROOT, ROLE, role_task
AFTER_STAGING = (
"🔏 Seal the job list so the scheduler drains and exits",
"⏳ Wait for the scheduler to drain the job list",
"🧹 Remove any handed-over container the scheduler did not stop",
"📥 Read each handed-over run's job and result",
"🧭 Leave the runs whose dependency never ran here to the serial runner",
"📝 Report and archive each handed-over run",
"🛑 Fail when the scheduler itself did not finish cleanly",
)
BUDGET_INPUTS = (
"TEST_E2E_PLAYWRIGHT_ONION_RUN_TIMEOUT",
"test_e2e_playwright_run_timeout",
"TEST_E2E_PLAYWRIGHT_ONION_PROBE_RETRIES",
"TEST_E2E_PLAYWRIGHT_ONION_PROBE_DELAY",
"TEST_E2E_PLAYWRIGHT_ONION_PROBE_MAX_TIME",
"test_e2e_playwright_wait_retries",
"test_e2e_playwright_wait_delay",
)
FIXTURE_INPUTS = dict(zip(BUDGET_INPUTS, (5400, 3600, 40, 15, 120, 30, 5), strict=True))
WORDPRESS0_APPS = (
"web-app-keycloak",
"web-app-hermes",
"web-app-matomo",
"web-app-openclaw",
"web-app-weblate",
"web-svc-cdn",
"web-svc-design",
"web-svc-logout",
"web-svc-mirror",
"web-svc-simpleicons",
"web-svc-translate",
"web-app-dashboard",
"web-app-discourse",
"web-app-stalwart",
"web-app-jitsi",
"web-app-matrix",
"web-app-prometheus",
"web-app-wordpress",
)
def budget_expression() -> str:
"""Read ``TEST_E2E_PLAYWRIGHT_PARALLEL_BUDGET`` as the role writes it.
Returns:
The Jinja expression.
"""
return load_yaml_any(str(ROLE / ROLE_FILE_VARS_MAIN), default_if_missing={})[
"TEST_E2E_PLAYWRIGHT_PARALLEL_BUDGET"
]
def render_budget(
expression, apps, factor, inputs, role_timeout, networks, handover
) -> int:
"""Render the scheduler's async ceiling for one round.
Args:
expression: the ceiling expression to render.
apps: ``TEST_E2E_PLAYWRIGHT_APPS`` of the round.
factor: the ``TIMEOUT_FACTOR`` the ``timeout`` lookup scales by.
inputs: the role variables the expression reads, by name.
role_timeout: an app's ``playwright.timeout``, ``''`` when unset.
networks: the networks an app's domain has siblings on.
handover: whether an app is pinned to its own domain.
Returns:
The ceiling in seconds.
"""
def lookup(name, *terms, **kwargs):
if name == "role_tests":
return role_timeout(terms[0])
if name == "timeout":
return scaled_timeout(terms[0], factor)
if name == "domain":
return f"clearnet:{terms[0]}"
if name == "config":
return handover(terms[0])
if name == "network_siblings":
app = terms[0].split(":", 1)[1]
return [f"{network}:{app}" for network in networks(app)]
raise AssertionError(name)
env = jinja2.Environment(
autoescape=jinja2.select_autoescape(default_for_string=False)
)
env.globals["lookup"] = lookup
env.filters["network_of"] = lambda domain: domain.split(":", 1)[0]
return int(
env.from_string(expression).render(
TEST_E2E_PLAYWRIGHT_APPS=list(apps), **inputs
)
)
def conditional(expression: str, **variables) -> bool:
"""Evaluate a task condition the way Ansible does.
Args:
expression: the ``when`` or ``failed_when`` text.
**variables: the variables in scope.
Returns:
The condition's truth.
"""
env = jinja2.Environment(
autoescape=jinja2.select_autoescape(default_for_string=False)
)
env.filters.update(FilterModule().filters())
env.tests.update(TestModule().tests())
return (
env.from_string("{{ (" + expression + ") | bool }}").render(**variables)
== "True"
)
def native(expression: str, **variables):
"""Evaluate a task value the way Ansible does, keeping its native type.
Args:
expression: the templated value.
**variables: the variables in scope.
Returns:
The rendered value.
"""
env = NativeEnvironment()
env.filters.update(FilterModule().filters())
env.tests.update(TestModule().tests())
return env.from_string(expression).render(**variables)
def scheduler_module():
"""Load ``run_parallel.py``, which the role ships as a plain file.
Returns:
The scheduler module.
"""
spec = importlib.util.spec_from_file_location(
"playwright_run_parallel_flow", ROLE / "files" / "run_parallel.py"
)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
rp = scheduler_module()
def encoded(path: Path) -> str:
"""Return a file the way ``ansible.builtin.slurp`` hands it back.
Args:
path: a file the test wrote.
Returns:
The base64 content.
"""
data = path.read_bytes() # nocheck: cache-read
return base64.b64encode(data).decode()
class TestParallelOrchestration(unittest.TestCase):
def test_a_dropped_identity_provider_sends_its_dependents_to_a_serial_first_pass(
self,
):
head = "web-app-keycloak"
apps = [head, "web-app-a", "web-app-b", "web-app-c"]
with tempfile.TemporaryDirectory() as tmp:
jobs, trace = Path(tmp) / "jobs", Path(tmp) / "trace"
jobs.mkdir()
names = []
for index, app in enumerate(apps[1:], start=1):
names.append(f"{index}-{app}.job.json")
spec = {
"id": app,
"argv": [sys.executable, "-c", f"open({str(trace)!r}, 'a')"],
"env": {},
"timeout": 30,
"after": [head],
"tor": False,
"workers": 1,
"memory_mb": 1,
"stop": ["true"],
"meta": {"reports_dir": tmp},
}
(jobs / names[-1]).write_text(json.dumps(spec))
(jobs / "sealed").touch()
gate = rp.HostGate(36.0, 0.5, 0.0, jobs / "-", jobs / "-", time.monotonic)
tor = rp.TorReaders(Path(tmp) / "tor.lock", 3)
self.assertEqual(rp.run(jobs, 3, 0.05, gate, tor), 0)
self.assertFalse(trace.exists())
reads = [
{"playwright_read": name, "content": encoded(jobs / name)}
for app, job in zip(apps[1:], names, strict=True)
for name in (job, f"{app}.result.json")
]
leave = role_task("03_run_pass.yml", "📝 Leave")["ansible.builtin.set_fact"]
serial = native(
leave["_playwright_serial_roles"],
_playwright_serial_roles=[],
application_id=head,
)
defer = role_task("01_setup/parallel.yml", "🧭")["ansible.builtin.set_fact"]
serial = native(
defer["_playwright_serial_roles"],
_playwright_serial_roles=serial,
_playwright_reads={"results": reads},
)
report = role_task("01_setup/parallel.yml", "📝 Report")
for read in reads[1::2]:
run = json.loads(base64.b64decode(read["content"]))
self.assertFalse(conditional(report["when"], _playwright_run=run))
first_pass = role_task("01_setup/orchestrate.yml", "▶️ Run the roles left")
self.assertEqual(
native(
first_pass["loop"],
TEST_E2E_PLAYWRIGHT_APPS=apps,
_playwright_serial_roles=serial,
),
apps,
)
self.assertEqual(native(first_pass["loop"], TEST_E2E_PLAYWRIGHT_APPS=apps), [])
self.assertFalse(first_pass["vars"]["_playwright_dispatch"])
orchestrate = [
task["name"]
for task in load_yaml_any(
str(ROLE / "tasks" / "01_setup" / "orchestrate.yml"),
default_if_missing=[],
)
]
parallel_at = next(i for i, n in enumerate(orchestrate) if n.startswith("🔀"))
self.assertEqual(orchestrate[parallel_at + 1], first_pass["name"])
self.assertEqual(
[n.split()[1] for n in orchestrate[parallel_at + 2 : parallel_at + 4]],
["Stash", "Retry"],
)
def test_a_failed_staging_still_waits_reaps_and_reports_the_handed_over_runs(self):
staging = role_task("01_setup/parallel.yml", "📦")
self.assertEqual([t["name"] for t in staging["always"]], list(AFTER_STAGING))
include = role_task("01_setup/orchestrate.yml", "🔀")
self.assertEqual(
include["ansible.builtin.include_tasks"], "01_setup/parallel.yml"
)
self.assertEqual(include["when"], "TEST_E2E_PLAYWRIGHT_PARALLEL | int > 1")
def test_the_ceiling_counts_probe_passes_only_where_an_onion_can_be_picked(self):
timeouts = {"web-app-docs": 9000}
networks = {
"web-app-docs": ["clearnet", "tor"],
"web-app-x": ["clearnet"],
"web-app-h": ["clearnet", "tor"],
}
onion_wait = 2 * 40 * (120 + 15) + 40 * 15
for factor in (1, 2):
with self.subTest(factor=factor):
self.assertEqual(
render_budget(
budget_expression(),
["web-app-docs", "web-app-x", "web-app-h"],
factor,
FIXTURE_INPUTS,
lambda app: timeouts.get(app, ""),
networks.get,
lambda app: app == "web-app-h",
),
(factor * 9000 + onion_wait) + 2 * (factor * 3600 + 30 * 5),
)
def test_the_real_wordpress0_ceiling_never_undercuts_the_ci_step_timeout(self):
role_vars = {
**load_yaml_any(str(ROLE / ROLE_FILE_DEFAULTS_MAIN), default_if_missing={}),
**load_yaml_any(str(ROLE / ROLE_FILE_VARS_MAIN), default_if_missing={}),
}
variables = {"playbook_dir": str(PROJECT_ROOT)}
role_tests = RoleTestsLookup(
loader=DataLoader(),
templar=Templar(loader=DataLoader(), variables=variables),
)
factor = load_yaml_any(
str(PROJECT_ROOT / "group_vars" / "all" / "17_resource.yml"),
default_if_missing={},
)["TIMEOUT_FACTOR"]
ceiling = render_budget(
budget_expression(),
WORDPRESS0_APPS,
factor,
{name: role_vars[name] for name in BUDGET_INPUTS},
lambda app: role_tests.run(
[app, "playwright.timeout"], variables=variables, default=""
)[0],
lambda app: ["clearnet", "tor"],
lambda app: bool(
(
load_yaml_any(
str(PROJECT_ROOT / "roles" / app / ROLE_FILE_META_NETWORKS),
default_if_missing={},
)
or {}
)
.get("reachability", {})
.get("handover", False)
),
)
self.assertEqual(ceiling, 18 * (5400 + 2 * 40 * (120 + 15) + 40 * 15))
workflow = load_yaml_any(
str(PROJECT_ROOT / ".github" / "workflows" / "call-test-deploy.yml"),
default_if_missing={},
)
drill = next(
step
for job in workflow["jobs"].values()
for step in job.get("steps", [])
if str(step.get("name", "")).startswith("🚀 Drill")
)
self.assertGreater(ceiling, int(drill["timeout-minutes"]) * 60)
def test_each_parallel_run_keeps_output_result_and_retry_count_with_its_reports(
self,
):
line = role_task("04_collect.yml", "⏱️")
for signal in ("retries", "flaky", "crashes", "crash_kinds"):
self.assertIn(
f"_playwright_run.{signal}", line["ansible.builtin.debug"]["msg"]
)
keep = role_task("04_collect.yml", "📋")
self.assertEqual(keep["loop"], ["result.json", "stdout", "stderr"])
self.assertTrue(keep["ansible.builtin.copy"]["dest"].endswith("/run-parallel/"))
tasks = load_yaml_any(
str(ROLE / "tasks" / "04_collect.yml"), default_if_missing=[]
)
holder = next(
i for i, t in enumerate(tasks) if keep in [t, *t.get("block", [])]
)
archive = next(i for i, t in enumerate(tasks) if t["name"].startswith("🗄️"))
self.assertLess(holder, archive)
script = read_text(str(ROLE / "files" / "archive_playwright_reports.sh"))
self.assertIn(
"for item in playwright-junit.xml playwright-report test-results run-parallel; do",
script,
)
def test_only_the_parallel_run_hands_the_probe_its_tor_lock(self):
probe = role_task("03_run_pass.yml", "⏳ Wait until the onion")
self.assertEqual(probe["when"], "TEST_E2E_PLAYWRIGHT_IS_ONION | bool")
env = jinja2.Environment(
autoescape=jinja2.select_autoescape(default_for_string=False)
)
env.filters.update(FilterModule().filters())
env.globals["lookup"] = lambda name, *terms: {
"tor_socks": "127.0.0.1:9050",
"container": "/opt/tor",
}[name]
for dispatch, lock in ((False, ""), (True, "/stage/tor.lock")):
with self.subTest(dispatch=dispatch):
argv = shlex.split(
env.from_string(probe["ansible.builtin.script"]).render(
role_path="/role",
_playwright_pass_domain="x.onion",
_playwright_dispatch=dispatch,
TEST_E2E_PLAYWRIGHT_ONION_PROBE_RETRIES=40,
TEST_E2E_PLAYWRIGHT_ONION_PROBE_DELAY=15,
TEST_E2E_PLAYWRIGHT_ONION_PROBE_MAX_TIME=120,
TEST_E2E_PLAYWRIGHT_TOR_LOCK="/stage/tor.lock",
)
)
self.assertEqual(
argv[1:],
["127.0.0.1:9050", "x.onion", "40", "15", "120", "/opt/tor", lock],
)
def test_an_unreachable_onion_fails_the_serial_run_but_only_its_own_app_in_parallel(
self,
):
probe = role_task("03_run_pass.yml", "⏳ Wait until the onion")
queue = role_task("03_run_pass.yml", "📮")
remember = role_task("03_run_pass.yml", "📝 Remember")
leave = role_task("03_run_pass.yml", "📝 Leave")
skipped = {"skipped": True, "changed": False}
self.assertTrue(
conditional(
probe["failed_when"],
_playwright_probe={"rc": 1},
_playwright_dispatch=False,
)
)
self.assertFalse(
conditional(
probe["failed_when"],
_playwright_probe={"rc": 0},
_playwright_dispatch=False,
)
)
self.assertFalse(
conditional(
probe["failed_when"],
_playwright_probe={"rc": 1},
_playwright_dispatch=True,
)
)
for result, queued in (
(skipped, True),
({"rc": 0}, True),
({"rc": 1}, False),
({"msg": "transfer failed"}, False),
):
with self.subTest(result=result):
self.assertEqual(
conditional(queue["when"], _playwright_probe=result), queued
)
written = {"dest": "/jobs/3-x.job.json"} if queued else skipped
self.assertEqual(
conditional(remember["when"], _playwright_job_written=written),
queued,
)
self.assertEqual(
conditional(leave["when"], _playwright_job_written=written),
not queued,
)
self.assertIn("_playwright_serial_roles", leave["ansible.builtin.set_fact"])
def test_the_seal_keeps_its_times_and_the_async_states_why_it_is_safe(self):
seal = role_task("01_setup/parallel.yml", "🔏")["ansible.builtin.file"]
self.assertEqual(
(seal["modification_time"], seal["access_time"]), ("preserve", "preserve")
)
self.assertRegex(
read_text(str(ROLE / "tasks" / "01_setup" / "parallel.yml")),
r"#\s*rationale:\s*async;\s*\S",
)
class TestParallelContainerFlags(unittest.TestCase):
"""The flags only the parallel run adds must not shift the image argument."""
def _container_module(self):
path = (
PROJECT_ROOT
/ "roles"
/ "sys-svc-container"
/ "files"
/ "python"
/ "container.py"
)
spec = importlib.util.spec_from_file_location("container_wrapper", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _flags(self):
return role_task("03_run_pass.yml", "📮")["vars"]["_playwright_parallel_flags"]
def test_every_parallel_flag_carries_its_value_in_one_token(self):
flags = self._flags()
self.assertEqual(len(flags), 2)
for flag in flags:
self.assertRegex(re.sub(r"\{\{.*?\}\}", "X", flag), r"^--[a-z-]+=\S+$")
def test_no_job_gets_a_memory_cap_that_could_kill_it_running_alone(self):
self.assertFalse(
any(flag.startswith(("--memory", "-m")) for flag in self._flags())
)
self.assertTrue(
any(flag.startswith("--oom-score-adj=") for flag in self._flags())
)
def test_the_wrapper_still_finds_the_image(self):
container = self._container_module()
argv = [
"--rm",
"--name=infinito-playwright-x",
"--oom-score-adj=1000",
"image:tag",
"/bin/bash",
]
_, image_and_args = container.split_docker_run_argv(argv)
self.assertEqual(image_and_args[0], "image:tag")
if __name__ == "__main__":
unittest.main()