Recover interrupted worker jobs before starting the next cycle

This commit is contained in:
Pavel Isaev 2026-11-06 03:02:26 +03:00
parent 864fc3855a
commit e9b93e608b
4 changed files with 86 additions and 5 deletions

View file

@ -41,6 +41,12 @@ not advance publication. The systemd stop hook also records coordinator kills or
timeouts that bypass Python exception handling. No screenshot is accepted by an
LLM: UI drift or timeout is a failed test.
Worker unit identities are recorded before launch. The next coordinator, after
acquiring the exclusive lock, stops recorded jobs from an interrupted/failed run
before starting work. It preserves the original failure reason. The cycle reports
`complete` only after public verification and successful worker cleanup; a cleanup
failure remains visible with `published: true` if publication already happened.
## Publication scope
This driver currently publishes **hardware-test**, not testing/stable. Existing

View file

@ -7,10 +7,10 @@ separate contract; the one-build D-079 exception must never be reused here.
import argparse
from datetime import datetime, timezone
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import signal
@ -46,6 +46,7 @@ def main():
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
run = parent / stamp
run.mkdir()
previous = json.loads((parent / 'latest.json').read_text()) if (parent / 'latest.json').exists() else None
source = Path(__file__).resolve().parent
shutil.copytree(source, run / 'pipeline', ignore=shutil.ignore_patterns('__pycache__'))
atomic(run / 'config.json', config)
@ -70,6 +71,8 @@ def main():
step += 1
unit = 'archipelago-cycle-' + stamp + '-' + str(step)
worker_units.append(unit)
state['worker_units'] = list(worker_units)
atomic(run / 'state.json', state)
call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', '-o', 'ServerAliveInterval=15', worker,
shlex.join(['systemd-run', '--wait', '--pipe', '--unit=' + unit,
'--property=RuntimeMaxSec=' + str(timeout - 30),
@ -88,6 +91,23 @@ def main():
builds = None
vm_unit = 'archipelago-cycle-gnome-' + stamp
try:
if previous and previous.get('state') != 'complete':
old_id = previous['run']
if not re.fullmatch(r'[0-9]{8}T[0-9]{6}Z', old_id):
raise ValueError('Invalid previous run identity')
old_path = parent / old_id / 'state.json'
old = json.loads(old_path.read_text())
units = old.get('worker_units', [])
if any(not re.fullmatch('archipelago-cycle-' + old_id + r'-[0-9]+', u) for u in units):
raise ValueError('Invalid previous worker unit identity')
call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker,
'set -e; for unit in ' + shlex.join([*units, 'archipelago-cycle-gnome-' + old_id]) +
'; do if systemctl is-active --quiet "$unit"; then systemctl stop "$unit"; fi; done'], 180)
if old['state'] != 'failed':
old.update(failed_phase=old['state'], state='failed',
error='Interrupted coordinator recovered by ' + stamp)
old['worker_recovery_run'] = stamp
atomic(old_path, old)
phase('preflight')
remote(f'mkdir -p {shlex.quote(remote_root)}; test -c /dev/kvm; command -v qemu-system-x86_64; python3 -c "import pexpect"')
# Compile from the frozen source tree, not a possibly stale deployed CLI.
@ -182,7 +202,9 @@ python3 {remote_root}/probes/core_iso_acceptance.py --iso {shlex.quote(builds['c
with urllib.request.urlopen(address + '.sha256', timeout=60) as response:
if response.read().decode().split()[0] != item['sha256']:
raise ValueError('Public checksum mismatch')
phase('complete', finished=datetime.now(timezone.utc).isoformat(), releases=current)
phase('cleaning-worker', releases=current)
remote('rm -rf ' + shlex.quote(remote_root))
phase('complete', finished=datetime.now(timezone.utc).isoformat())
completed = sorted(p for p in parent.iterdir() if p.is_dir() and (p / 'state.json').exists()
and json.loads((p / 'state.json').read_text()).get('state') == 'complete')
for old in completed[:-3]:
@ -190,8 +212,6 @@ python3 {remote_root}/probes/core_iso_acceptance.py --iso {shlex.quote(builds['c
# Keep evidence/source/status, expire only archived artifact bytes.
for name in ('repo', 'output'):
shutil.rmtree(old / variant / 'build' / name, ignore_errors=True)
# A successful, archived cycle no longer needs worker disks/artifacts.
remote('systemctl stop ' + shlex.quote(vm_unit) + '; rm -rf ' + shlex.quote(remote_root))
except BaseException as error:
phase('failed', error=str(error), failed_phase=state['state'])
# Stop this run's VM before archiving diagnostics; never select host VMs

View file

@ -11,7 +11,8 @@
'archiving-artifacts': 'Передача на terra', 'core-installed-acceptance': 'Проверка установленного Core',
'gnome-installed-acceptance': 'Проверка установленного GNOME',
'preparing-publication': 'Проверка свидетельств', 'signing-and-publishing': 'Подпись и публикация',
'verifying-public-endpoints': 'Проверка скачивания', 'complete': 'Цикл завершён', 'failed': 'Цикл завершился ошибкой'};
'verifying-public-endpoints': 'Проверка скачивания', 'cleaning-worker': 'Очистка сборочного окружения',
'complete': 'Цикл завершён', 'failed': 'Цикл завершился ошибкой'};
label.textContent = `${names[status.state] || status.state} · ${status.run}`;
} catch { label.textContent = 'Состояние временно недоступно.'; }
})();

54
tests/cycle-recovery.py Normal file
View file

@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""An interrupted worker is stopped before preflight; foreign units fail closed."""
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('cycle', Path(__file__).parents[1] / 'pipeline/release-cycle.py')
cycle = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cycle)
for foreign in (False, True):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
parent = root / 'data/private/release-cycle'
old_id = '20260101T000000Z'
old_dir = parent / old_id
old_dir.mkdir(parents=True)
unit = 'unrelated-workload' if foreign else 'archipelago-cycle-' + old_id + '-3'
old = dict(run=old_id, state='failed', error='Original timeout', worker_units=[unit])
for path in (old_dir / 'state.json', parent / 'latest.json'):
path.write_text(json.dumps(old))
config = root / 'config.json'
config.write_text(json.dumps(dict(coordinator_root=str(root), worker='worker', worker_root='/worker')))
calls = []
def invoke(argv, **kwargs):
calls.append(argv)
if argv[0] == 'ssh' and 'systemd-run' in argv[-1]:
raise subprocess.CalledProcessError(1, argv)
# Keep failure artifacts rather than simulating successful archival.
return subprocess.CompletedProcess(argv, 1 if argv[0] == 'rsync' else 0)
with patch.object(sys, 'argv', ['cycle', '--config', str(config)]), \
patch.object(cycle.subprocess, 'run', side_effect=invoke), \
patch.object(cycle.signal, 'signal'):
try:
cycle.main()
except (ValueError, subprocess.CalledProcessError):
pass
else:
raise AssertionError('Failed preflight must not succeed')
saved = json.loads((old_dir / 'state.json').read_text())
assert saved['error'] == 'Original timeout'
if foreign:
assert all('unrelated-workload' not in str(call) for call in calls)
else:
assert unit in calls[0][-1] and 'systemctl stop' in calls[0][-1]
assert 'systemd-run' in calls[1][-1]
assert 'worker_recovery_run' in saved
assert json.loads((parent / 'latest.json').read_text())['state'] == 'failed'
print('CYCLE_RECOVERY_ORDER_AND_OWNERSHIP_PASS')