Skip to content

The agent that grows with you

test: windows hand-off marker claim, release and post-commit outcomes run live

Tekniumbde2d86bc93f
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py b/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py
new file mode 100644
index 00000000000..80bbb995e7b
--- /dev/null
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py
@@ -0,0 +1,143 @@
+"""Post-commit outcomes (contract C3) on the real Windows hand-off script.
+
+A real ``windows.ps1`` drives a real published launcher whose ``hermes``
+application is a scripted stand-in: once ``hermes update`` exits 0 the install
+is on the new version, so nothing afterwards may report "still on the previous
+version", and the hand-off's own supervision (watchdog, probes, marker
+release) must not turn healthy work into a failure.
+"""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import time
+
+import pytest
+
+from tests.installation_launcher_fixture import publish_fixture_launcher
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SCRIPT = ROOT / 'scripts/desktop-update/windows.ps1'
+CLI = """
+import json, os, subprocess, sys, time
+from pathlib import Path
+def main():
+ if '--version' in sys.argv:
+ print('Install directory: ' + str(Path(__file__).resolve().parents[1])); return 0
+ if '--help' in sys.argv:
+ if os.environ.get('HANDOFF_HELP_HANG'):
+ time.sleep(600)
+ print('--keep-stash'); return 0
+ with Path(os.environ['HANDOFF_CALLS']).open('a') as stream:
+ stream.write(json.dumps(sys.argv[1:]) + '\\n')
+ if sys.argv[1:2] != ['update']:
+ return 0
+ busy = float(os.environ.get('HANDOFF_BUSY_SECONDS', '0'))
+ end = time.monotonic() + busy
+ while time.monotonic() < end: # pipe-silent, CPU-busy (download/extract shape)
+ pass
+ if os.environ.get('HANDOFF_DELEGATE'):
+ # Leave a live process running under the claim, named on line 4.
+ child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)'],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ Path(os.environ['HANDOFF_DELEGATE']).write_text(str(child.pid))
+ marker = Path(os.environ['HERMES_HOME']) / '.hermes-update-in-progress'
+ head = marker.read_bytes().decode().split('\\n')[:3]
+ marker.write_bytes(('\\n'.join(head) + '\\ndelegate:%d\\n' % child.pid).encode())
+ if os.environ.get('HANDOFF_HANG'):
+ print(os.environ['HANDOFF_HANG'], flush=True)
+ time.sleep(300)
+ print('Update complete!', flush=True)
+ return 0
+if __name__ == '__main__':
+ sys.exit(main())
+"""
+
+
+def _handoff(tmp_path: Path, *args: str, verify: str = 'pass\n', timeout: int = 150, **env: str):
+ install = tmp_path / 'checkout'
+ publish_fixture_launcher(install, CLI)
+ (install / 'hermes_cli/desktop_update_verify.py').write_text(verify)
+ home = tmp_path / 'home'; home.mkdir()
+ calls = tmp_path / 'calls.jsonl'
+ proc = subprocess.Popen(
+ ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPT),
+ '-InstallRoot', str(install), '-NoUi', *args],
+ cwd=tmp_path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
+ env={**os.environ, 'HERMES_HOME': str(home), 'HERMES_RUNTIME_DIR': str(tmp_path / 'empty-store'),
+ 'HANDOFF_CALLS': str(calls), 'PYTHONIOENCODING': 'utf-8', **env},
+ )
+ try:
+ out, _ = proc.communicate(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ subprocess.run(['taskkill', '/T', '/F', '/PID', str(proc.pid)], capture_output=True)
+ out, _ = proc.communicate()
+ pytest.fail(f'hand-off did not finish within {timeout}s: {out}')
+ argv = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
+ result = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))
+ return proc.returncode, out, argv, result, home
+
+
+def test_verify_failure_after_a_committed_update_is_ok_with_warnings(tmp_path: Path) -> None:
+ code, out, argv, result, _ = _handoff(tmp_path, verify='raise SystemExit(3)\n')
+ assert code == 0, out
+ assert (result['ok'], result['exit_code'], result['manual']) == (True, 0, True), result
+ assert [w.split(':')[0] for w in result['warnings']] == ['verify'], result
+ assert result['message'].startswith('Hermes was updated, but'), result
+ assert 'previous version' not in result['message']
+ # The fleet the Desktop stopped is still brought back.
+ assert argv[-1] == ['gateway', 'start', '--all'], argv
+
+
+def test_result_is_atomic_json_carrying_started_at_and_warnings(tmp_path: Path) -> None:
+ started = int(time.time()) - 5
+ code, out, _, result, home = _handoff(tmp_path, HERMES_UPDATE_STARTED_AT=str(started))
+ assert code == 0, out
+ assert (result['ok'], result['started_at'], result['warnings']) == (True, started, []), result
+ assert not list(home.glob('.hermes-update-result.json.*.tmp'))
+
+
+def test_marker_with_a_live_delegate_is_kept_at_finish(tmp_path: Path) -> None:
+ pid_file = tmp_path / 'delegate.pid'
+ try:
+ code, out, _, result, home = _handoff(tmp_path, HANDOFF_DELEGATE=str(pid_file))
+ assert code == 0, out
+ marker = (home / '.hermes-update-in-progress').read_bytes().decode().split('\n')
+ assert marker[3] == f'delegate:{pid_file.read_text()}', marker
+ finally:
+ if pid_file.exists():
+ subprocess.run(['taskkill', '/F', '/PID', pid_file.read_text()], capture_output=True)
+
+
+def test_watchdog_remap_after_banner_reports_interrupted_followups(tmp_path: Path) -> None:
+ code, out, argv, result, _ = _handoff(
+ tmp_path, '-NoGateway', HANDOFF_HANG='Update complete! (v1.0.0)',
+ HERMES_UPDATE_STEP_IDLE_SECONDS='3',
+ )
+ assert code == 0, out
+ assert (result['ok'], result['manual']) == (True, True), result
+ assert any('interrupted' in w for w in result['warnings']), result
+
+
+def test_cpu_busy_pipe_silent_update_is_not_killed_by_the_idle_watchdog(tmp_path: Path) -> None:
+ code, out, argv, result, _ = _handoff(
+ tmp_path, '-NoGateway', HANDOFF_BUSY_SECONDS='15', HERMES_UPDATE_STEP_IDLE_SECONDS='4',
+ )
+ assert code == 0, out
+ assert (result['ok'], result['warnings']) == (True, []), result
+
+
+def test_hanging_update_help_probe_is_bounded(tmp_path: Path) -> None:
+ code, out, argv, result, _ = _handoff(
+ tmp_path, '-NoGateway', timeout=120, HANDOFF_HELP_HANG='1', HERMES_UPDATE_PROBE_TIMEOUT_SECONDS='10',
+ )
+ assert code == 0, out
+ assert argv[0][:2] == ['update', '--yes'] and '--keep-stash' not in argv[0], argv
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py b/tests/scripts/desktop_update/test_desktop_update_windows_marker.py
new file mode 100644
index 00000000000..fb61392ba85
--- /dev/null
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_marker.py
@@ -0,0 +1,166 @@
+"""Update-marker contract C1 v2 on the real Windows hand-off script.
+
+Every case runs the real ``scripts/desktop-update/windows.ps1`` under
+Windows PowerShell against a marker owned by a REAL process (a sleeping
+Python child) and reads the marker / result / hand-off log it leaves.
+"""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+
+import pytest
+
+from tests.installation_launcher_fixture import publish_fixture_launcher
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SCRIPT = ROOT / 'scripts/desktop-update/windows.ps1'
+MARKER = '.hermes-update-in-progress'
+CLI = """
+import sys
+from pathlib import Path
+def main():
+ if '--version' in sys.argv:
+ print('Install directory: ' + str(Path(__file__).resolve().parents[1])); return 0
+ if '--help' in sys.argv:
+ print('--keep-stash'); return 0
+ return 0
+if __name__ == '__main__':
+ sys.exit(main())
+"""
+
+
+def sleeper():
+ proc = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)'])
+ yield proc
+ proc.kill()
+ proc.wait()
+
+
+def _creation_time(pid: int) -> str:
+ out = subprocess.run(
+ ['powershell', '-NoProfile', '-Command',
+ f"[DateTimeOffset]::new((Get-Process -Id {pid}).StartTime.ToUniversalTime())"
+ ".ToUnixTimeMilliseconds().ToString()"],
+ capture_output=True, text=True, timeout=60, check=True,
+ ).stdout.strip()
+ return f'{int(out) / 1000:.3f}'
+
+
+def _dead_pid() -> int:
+ proc = subprocess.Popen([sys.executable, '-c', 'pass'])
+ proc.wait()
+ return proc.pid
+
+
+def _run(home: Path, *args: str, install: Path | None = None, timeout: int = 120):
+ command = ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPT),
+ '-InstallRoot', str(install or home / 'hermes-agent'), '-NoUi', *args]
+ proc = subprocess.Popen(command, cwd=home, env={**os.environ, 'HERMES_HOME': str(home)},
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ try:
+ out, _ = proc.communicate(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ subprocess.run(['taskkill', '/T', '/F', '/PID', str(proc.pid)], capture_output=True)
+ out, _ = proc.communicate()
+ pytest.fail(f'hand-off did not finish within {timeout}s: {out}')
+ return proc.pid, proc.returncode, out
+
+
+def _result(home: Path) -> dict:
+ return json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))
+
+
+def test_claim_is_the_first_action_and_writes_a_v2_body(tmp_path: Path) -> None:
+ pid, code, out = _run(tmp_path, '-SelfTestMarker', '-NoMarkerCleanup')
+ assert code == 0, out
+ lines = (tmp_path / MARKER).read_bytes().decode().split('\n')
+ assert lines[0] == str(pid)
+ assert lines[2].startswith('ct:') and len(lines[2].split('.')[-1]) == 3, lines
+ log = (tmp_path / 'logs/desktop-update-handoff.log').read_text(encoding='utf-8-sig').splitlines()
+ # Nothing (UI, Add-Type'd console helpers, probes) logs before the claim.
+ assert 'claimed update marker' in log[0], log
+
+
[email protected]('ct_matches', [True, False])
+def test_live_foreign_owner_refuses_and_reused_pid_is_reclaimed(
+ tmp_path: Path, sleeper: subprocess.Popen, ct_matches: bool,
+) -> None:
+ ct = _creation_time(sleeper.pid) if ct_matches else '1000.000' # wrong ct = pid reuse
+ body = f'{sleeper.pid}\n{int(time.time())}\nct:{ct}\n'.encode()
+ (tmp_path / MARKER).write_bytes(body)
+ pid, code, out = _run(tmp_path, '-SelfTestMarker', '-NoMarkerCleanup')
+ if ct_matches:
+ assert code == 2, out
+ assert (tmp_path / MARKER).read_bytes() == body
+ result = _result(tmp_path)
+ assert (result['ok'], result['exit_code']) == (False, 2)
+ assert 'Nothing was changed' in result['message']
+ else:
+ assert code == 0, out
+ lines = (tmp_path / MARKER).read_bytes().decode().split('\n')
+ assert lines[0] == str(pid) and lines[2].startswith('ct:'), lines
+
+
+def test_live_desktop_bridge_marker_is_adopted_keeping_its_started_at(
+ tmp_path: Path, sleeper: subprocess.Popen,
+) -> None:
+ started = int(time.time()) - 30
+ (tmp_path / MARKER).write_bytes(f'{sleeper.pid}\n{started}\nct:{_creation_time(sleeper.pid)}\n'.encode())
+ pid, code, out = _run(tmp_path, '-SelfTestMarker', '-NoMarkerCleanup', '-DesktopPid', str(sleeper.pid))
+ assert code == 0, out
+ lines = (tmp_path / MARKER).read_bytes().decode().split('\n')
+ assert lines[:2] == [str(pid), str(started)], lines
+ assert lines[2].startswith('ct:'), lines
+ assert _result(tmp_path)['started_at'] == started
+
+
+def test_dead_owner_marker_is_reclaimed_and_released(tmp_path: Path) -> None:
+ (tmp_path / MARKER).write_bytes(f'{_dead_pid()}\n{int(time.time())}\nct:5.000\n'.encode())
+ pid, code, out = _run(tmp_path, '-SelfTestMarker')
+ assert code == 0, out
+ assert not (tmp_path / MARKER).exists()
+ log = (tmp_path / 'logs/desktop-update-handoff.log').read_text(encoding='utf-8-sig')
+ assert f'claimed update marker (pid {pid})' in log
+ assert 'removed update marker (owned)' in log
+
+
+def test_desktop_that_never_exits_is_not_relaunched_over(
+ tmp_path: Path, sleeper: subprocess.Popen,
+) -> None:
+ install = tmp_path / 'checkout'
+ publish_fixture_launcher(install, CLI)
+ home = tmp_path / 'home'; home.mkdir()
+ relaunch = Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32' / 'hostname.exe'
+ _, code, out = _run(home, '-DesktopPid', str(sleeper.pid), '-RelaunchExe', str(relaunch),
+ install=install, timeout=180)
+ assert code == 4, out
+ log = (home / 'logs/desktop-update-handoff.log').read_text(encoding='utf-8-sig')
+ assert 'relaunching desktop' not in log, log
+
+
+def test_ui_profile_sweep_keeps_dirs_of_live_handoffs(tmp_path: Path, sleeper: subprocess.Popen) -> None:
+ live = tmp_path / f'hermes-update-ui-{sleeper.pid}'
+ dead = tmp_path / f'hermes-update-ui-{_dead_pid()}'
+ live.mkdir(); dead.mkdir()
+ home = tmp_path / 'home'; home.mkdir()
+ result = subprocess.run(
+ ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPT), '-SelfTestUi', '-NoUi'],
+ cwd=tmp_path, env={**os.environ, 'HERMES_HOME': str(home), 'TEMP': str(tmp_path),
+ 'HERMES_SELFTEST_HOLD_SECONDS': '0'},
+ capture_output=True, text=True, timeout=120,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert live.exists(), 'another live hand-off lost its browser profile'
+ assert not dead.exists()