The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Validate changed-kernel driver updates and offline recovery (#811)
Deef9e24ba36837
diff --git a/.github/workflows/os.yml b/.github/workflows/os.ymlindex 8a3564e6b..29a821a62 100644--- a/.github/workflows/os.yml+++ b/.github/workflows/os.yml@@ -47,11 +47,11 @@ on:default: falsetype: booleanchecks:- description: 'Image journey, browser focus, lock/suspend, recovery, Wi-Fi/audio, hardware, or private zram acceptance'+ description: 'Image journey, browser focus, lock/suspend, recovery, Wi-Fi/audio, hardware, private zram, or changed-kernel recovery acceptance'required: falsedefault: imagetype: choice- options: [image, browser, session, recovery, essentials, hardware, zram]+ options: [image, browser, session, recovery, essentials, hardware, zram, hardware-update]browser_memory:description: 'With checks=browser, diagnose memory in the UEFI VM only; retain ordinary workload and deadlines'required: false@@ -66,12 +66,12 @@ permissions:actions: readconcurrency:- group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.checks == 'browser' && 'browser' || inputs.checks == 'session' && 'session' || inputs.checks == 'recovery' && 'recovery' || inputs.checks == 'essentials' && 'essentials' || inputs.checks == 'hardware' && 'hardware' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}+ group: programmer-os-${{ github.ref }}-${{ inputs.memory_mib || '2048' }}-${{ inputs.live_transport || 'cdrom' }}-${{ inputs.development_update && 'update' || inputs.checks == 'browser' && 'browser' || inputs.checks == 'session' && 'session' || inputs.checks == 'recovery' && 'recovery' || inputs.checks == 'essentials' && 'essentials' || inputs.checks == 'hardware' && 'hardware' || inputs.checks == 'hardware-update' && 'hardware-update' || inputs.dsh && 'dsh' || inputs.workloads && 'workloads' || 'image' }}cancel-in-progress: falsejobs:image:- if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'zram' }}+ if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'zram' && inputs.checks != 'hardware-update' }}runs-on: ubuntu-24.04timeout-minutes: 50steps:@@ -159,7 +159,7 @@ jobs:machine:needs: image- if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && inputs.checks != 'hardware' && inputs.checks != 'zram' && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}+ if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && inputs.checks != 'hardware' && inputs.checks != 'zram' && inputs.checks != 'hardware-update' && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}runs-on: ubuntu-24.04timeout-minutes: 65strategy:@@ -288,6 +288,62 @@ jobs:os/test-results/zram/*/*.logretention-days: 14+ hardware-update:+ if: ${{ inputs.checks == 'hardware-update' }}+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v7+ - name: Check the pinned private fixture inputs+ env:+ OS_IMAGE_RUN: ${{ inputs.image_run_id }}+ OS_PUBLISH_RUN: ${{ inputs.publish_run_id }}+ OS_DEVELOPMENT_UPDATE: ${{ inputs.development_update }}+ OS_WORKLOADS: ${{ inputs.workloads }}+ OS_DSH: ${{ inputs.dsh }}+ run: |+ python3 - <<'PYTHON'+ import json, os+ lock = json.load(open('os/tests/hardware-update.lock.json'))+ assert os.environ['OS_IMAGE_RUN'] == str(lock['baseline']['image_run_id']), 'Use the exact locked preview14 image run'+ assert not os.environ['OS_PUBLISH_RUN'], 'This private gate never publishes'+ assert all(os.environ[key] == 'false' for key in ['OS_DEVELOPMENT_UPDATE', 'OS_WORKLOADS', 'OS_DSH'])+ PYTHON+ python3 -m unittest discover -s os/tests -p test_hardware_update_fixture.py+ python3 -m py_compile os/tests/hardware_update_guest.py os/tests/hardware_update_vm.py+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml+ - name: Reuse the original preview14 ISO and runtime+ uses: actions/download-artifact@v6+ with:+ name: programmer-os-x86_64+ path: os/dist+ run-id: ${{ inputs.image_run_id }}+ github-token: ${{ github.token }}+ - name: Prepare native VM tools+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr+ sudo chmod a+rw /dev/kvm+ df -h .+ - name: Upgrade the full signed snapshot and recover the original kernel offline+ run: >-+ python3 os/tests/hardware_update_vm.py+ --iso os/dist/harness-0.1.0-preview.14-x86_64.iso+ --snapshot-lock os/tests/hardware-update.lock.json+ --candidate-system os/system.py+ --output os/test-results/hardware-update+ - name: Retain every completed stage and failure+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-os-hardware-update+ path: |+ os/test-results/hardware-update/+ !os/test-results/hardware-update/*.qcow2+ !os/test-results/hardware-update/OVMF_VARS.fd+ retention-days: 14+ compression-level: 0+hardware:needs: imageif: ${{ always() && !inputs.publish_run_id && !inputs.development_update && (needs.image.result == 'success' || inputs.checks == 'hardware' && inputs.image_run_id != '') && !cancelled() }}@@ -401,7 +457,7 @@ jobs:retention-days: 14development-update:- if: ${{ inputs.development_update && !inputs.publish_run_id }}+ if: ${{ inputs.development_update && !inputs.publish_run_id && inputs.checks != 'hardware-update' }}runs-on: ubuntu-24.04timeout-minutes: 30steps:@@ -466,7 +522,7 @@ jobs:compression-level: 0publish:- if: ${{ inputs.publish_run_id != '' }}+ if: ${{ inputs.publish_run_id != '' && inputs.checks != 'hardware-update' }}runs-on: ubuntu-24.04timeout-minutes: 30concurrency:diff --git a/os/tests/hardware-update.lock.json b/os/tests/hardware-update.lock.jsonnew file mode 100644index 000000000..9d6208f3b--- /dev/null+++ b/os/tests/hardware-update.lock.json@@ -0,0 +1,107 @@+{+ "schema": 1,+ "baseline": {+ "image_run_id": 37257481538,+ "artifact": "programmer-os-x86_64",+ "source_commit": "b6cbaf3e3090f43106ad1ee47606349bd1a0ae89",+ "manifest_sha256": "140bd40e6507bf367b8b227b688a9a3a81da2ac40420041aff64abd118c27064",+ "iso": {+ "name": "harness-0.1.0-preview.14-x86_64.iso",+ "bytes": 2007023616,+ "sha256": "fa4f282644ac81e9e3b7de55276edd7dc08405e50875da544dc7f9fd6d50ba12"+ },+ "snapshot": "2026/10/01",+ "kernel": "6.18.54-1-lts",+ "packages": {+ "linux-lts": "6.18.54-1",+ "linux-lts-headers": "6.18.54-1",+ "nvidia-open-lts": "1:615.71.09-5",+ "nvidia-utils": "615.71.09-1",+ "broadcom-wl-dkms": "6.30.223.271-50",+ "dkms": "3.4.3-2",+ "harness-os": "0.1.0pre14.r1791169013.gb6cbaf3e30-1"+ },+ "runtime_files": {+ "notify.mjs": {+ "sha256": "5690159e964f9ce022bdb2a5e4bc9d853e595e822f254478df241e1386dde68e",+ "bytes": 72444+ },+ "harness-tui": {+ "sha256": "bd221059a24d7f7ca8ce69bb3b6d69c2fb66cb655aae6658627c278a548a8fa8",+ "bytes": 16521264+ },+ "cli.mjs": {+ "sha256": "23b46a7c498fd1ef8ff5936aeb431f1de08b959b957141fa732d2cede870d147",+ "bytes": 4419875+ }+ }+ },+ "candidate": {+ "snapshot": "2026/10/04",+ "kernel": "6.18.55-1-lts",+ "repositories": {+ "core": {+ "url": "https://archive.archlinux.org/repos/2026/10/04/core/os/x86_64/core.db",+ "bytes": 130360,+ "sha256": "373a91595792d33d02ef809742d109db27b2a5039152904f808f7943f6d0b6cb"+ },+ "extra": {+ "url": "https://archive.archlinux.org/repos/2026/10/04/extra/os/x86_64/extra.db",+ "bytes": 8854164,+ "sha256": "823815022358b353e960223ea9d6abdfdf916b166d223c9190e71adcb9702cc9"+ }+ },+ "packages": {+ "archlinux-keyring": {+ "version": "20260909-1",+ "filename": "archlinux-keyring-20260909-1-any.pkg.tar.zst",+ "sha256": "6a8ea16f51d3b305c18322d5884ca959f12c32a3f186873090fdc18465605293",+ "bytes": 1273532,+ "repository": "core"+ },+ "linux-lts": {+ "version": "6.18.55-1",+ "filename": "linux-lts-6.18.55-1-x86_64.pkg.tar.zst",+ "sha256": "d7b80550feb4309cd812bb21d0965d6e26f5ec72241c96a7ad57a3eb8b5f7e12",+ "bytes": 162981884,+ "repository": "core"+ },+ "linux-lts-headers": {+ "version": "6.18.55-1",+ "filename": "linux-lts-headers-6.18.55-1-x86_64.pkg.tar.zst",+ "sha256": "e4ef03c9a97d40cc8f58c8c4f731aa80d132b2290e0854709b82ef8bfa68bd7d",+ "bytes": 61794036,+ "repository": "core"+ },+ "broadcom-wl-dkms": {+ "version": "6.30.223.271-50",+ "filename": "broadcom-wl-dkms-6.30.223.271-50-x86_64.pkg.tar.zst",+ "sha256": "e3f2532c3519c6267c93724046e27cf7ec70b4028db537bd22dc2813447b4ed9",+ "bytes": 1724160,+ "repository": "extra"+ },+ "dkms": {+ "version": "3.4.3-2",+ "filename": "dkms-3.4.3-2-any.pkg.tar.zst",+ "sha256": "469d1abf762c5bb22e43cad8c63fbec5250cfd9fe958ae9e842c251956dc5faa",+ "bytes": 51451,+ "repository": "extra"+ },+ "nvidia-open-lts": {+ "version": "1:615.71.09-7",+ "filename": "nvidia-open-lts-1:615.71.09-7-x86_64.pkg.tar.zst",+ "sha256": "feded1790abb3787db6cf677658597cc8e7ae431ae8cd6d96b75cff883dce2f6",+ "bytes": 10160617,+ "repository": "extra"+ },+ "nvidia-utils": {+ "version": "615.71.09-1",+ "filename": "nvidia-utils-615.71.09-1-x86_64.pkg.tar.zst",+ "sha256": "0e32f81f52ac7b9516faa5eeef79c277212f6c65df545eeb54d64257963352a5",+ "bytes": 329970574,+ "repository": "extra"+ }+ },+ "metadata_only": true+ }+}diff --git a/os/tests/hardware_update_guest.py b/os/tests/hardware_update_guest.pynew file mode 100644index 000000000..a716f1252--- /dev/null+++ b/os/tests/hardware_update_guest.py@@ -0,0 +1,578 @@+#!/usr/bin/env python3+"""Private changed-kernel gate. Never run outside the disposable HN_OS_TEST VM."""+import argparse+import base64+from datetime import datetime+import gzip+import hashlib+import importlib.util+import json+import lzma+import os+from pathlib import Path+import re+import subprocess+import tarfile+import tempfile+import time+from urllib.request import urlopen++SYSTEM = Path('/usr/lib/harness-os/system.py')+PROJECT = Path('/home/me/projects/kernel-update-survivor')+NVIDIA = ('nvidia', 'nvidia_modeset', 'nvidia_uvm', 'nvidia_drm')+EARLY = ('nvidia', 'nvidia_modeset', 'nvidia_drm')+MASKS = ('harness-update.timer', 'harness-update.service')+++def digest(path):+ with Path(path).open('rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def run(*args, timeout=90):+ return subprocess.check_output([str(arg) for arg in args], text=True, timeout=timeout).strip()+++def load(name, path):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def save(path, value):+ Path(path).write_text(json.dumps(value, indent=2) + '\n')+++def validate_lock(lock):+ assert lock['schema'] == 1+ old, new = lock['baseline'], lock['candidate']+ assert old['kernel'] != new['kernel'], 'This gate requires a different kernel ABI'+ assert old['snapshot'] < new['snapshot']+ assert old['kernel'] == old['packages']['linux-lts'] + '-lts'+ assert old['packages']['linux-lts'] == old['packages']['linux-lts-headers']+ assert new['kernel'] == new['packages']['linux-lts']['version'] + '-lts'+ assert new['packages']['linux-lts']['version'] == new['packages']['linux-lts-headers']['version']+ assert set(new['repositories']) == {'core', 'extra'}+ assert set(old['runtime_files']) == {'harness-tui', 'cli.mjs', 'notify.mjs'}+ for name, row in new['repositories'].items():+ assert row['url'] == f'https://archive.archlinux.org/repos/{new["snapshot"]}/{name}/os/x86_64/{name}.db'+ assert re.fullmatch(r'[0-9a-f]{64}', row['sha256']) and row['bytes'] > 0+ for row in new['packages'].values():+ assert row['repository'] in new['repositories']+ assert Path(row['filename']).name == row['filename']+ assert re.fullmatch(r'[0-9a-f]{64}', row['sha256']) and row['bytes'] > 0+++def inventory():+ return dict(line.split(' ', 1) for line in run('pacman', '-Q').splitlines())+++def assert_versions(packages, expected):+ for name, version in expected.items():+ assert packages.get(name) == version, (name, packages.get(name), version)+++def expected_versions(lock, candidate):+ versions = dict(lock['baseline']['packages'])+ if candidate:+ versions.update({name: row['version'] for name, row in lock['candidate']['packages'].items()})+ return versions+++def runtime(lock):+ result = {'files': {}, 'package': inventory()['harness-os'], 'runtime_json_sha256': digest('/usr/share/harness-os/runtime.json')}+ assert result['package'] == lock['baseline']['packages']['harness-os']+ for name, expected in lock['baseline']['runtime_files'].items():+ path = Path('/usr/lib/harness') / name+ actual = {'bytes': path.stat().st_size, 'sha256': digest(path)}+ assert actual == expected, ('Frozen Harness runtime changed', name, actual)+ result['files'][name] = actual+ info = json.loads(Path('/usr/share/harness-os/runtime.json').read_text())+ assert info['source_commit'] == lock['baseline']['source_commit']+ assert info['files'] == lock['baseline']['runtime_files']+ # A selected per-user binary must not silently replace the packaged one.+ updates = Path('/home/me/.local/state/harness-os/updates/current')+ result['user_update_directory_exists'] = updates.exists()+ assert not updates.exists() and not updates.is_symlink(), 'Unexpected per-user runtime update state'+ for name in MASKS:+ assert os.readlink('/etc/systemd/user/' + name) == '/dev/null'+ return result+++def initramfs_identity(listing, kernel, firmware):+ namespaces = sorted(set(re.findall(r'(?:^|/)usr/lib/modules/([^/\s]+)/', listing, re.M)))+ assert namespaces == [kernel], ('Initramfs kernel namespace', namespaces, kernel)+ modules = {}+ for name in EARLY:+ pattern = r'[^\s]*usr/lib/modules/' + re.escape(kernel) + r'/[^\s]*/' + name.replace('_', '[-_]') + r'\.ko(?:\.(?:zst|xz|gz))?(?=\s|$)'+ found = re.findall(pattern, listing)+ assert len(found) == 1, ('Missing early NVIDIA module', name, found)+ modules[name] = found[0]+ assert firmware, 'No declared NVIDIA GSP firmware'+ for name in firmware:+ found = re.findall(r'(?:^|/)usr/lib/firmware/' + re.escape(name) + r'(?:\.(?:zst|xz|gz))?(?=\s|$)', listing, re.M)+ assert len(found) == 1, ('Missing or ambiguous GSP firmware', name, found)+ return {'kernel_namespaces': namespaces, 'early_modules': modules, 'firmware': firmware}+++def content_digest(path):+ """Compare payload bytes even when mkinitcpio changes their compression."""+ with Path(path).open('rb') as handle:+ magic = handle.read(6)+ if magic.startswith(b'\x28\xb5\x2f\xfd'):+ # Spool decompressed data to the guest disk, not the 2 GiB guest's RAM.+ with tempfile.TemporaryFile(dir='/var/tmp') as decoded:+ subprocess.run(['zstd', '--decompress', '--stdout', str(path)],+ stdout=decoded, check=True, timeout=30)+ decoded.seek(0)+ return hashlib.file_digest(decoded, 'sha256').hexdigest()+ opener = gzip.open if magic.startswith(b'\x1f\x8b') else lzma.open if magic == b'\xfd7zXZ\x00' else open+ with opener(path, 'rb') as handle:+ return hashlib.file_digest(handle, 'sha256').hexdigest()+++def payload_identity(segments, identity, modules, firmware_root=Path('/usr/lib/firmware')):+ pairs = []+ for name, relative in identity['early_modules'].items():+ found = [(segment, root / relative) for segment, root in segments.items() if (root / relative).is_file()]+ assert len(found) == 1, ('Missing or ambiguous archived module', name, found)+ segment, archived = found[0]+ pairs.append((name, segment, archived, Path(modules[name]['path'])))+ for name in identity['firmware']:+ installed = [firmware_root / (name + suffix) for suffix in ('', '.zst', '.xz', '.gz')]+ present = [path for path in installed if path.is_file()]+ assert len(present) == 1, ('Ambiguous installed GSP payload', name, present)+ archived = [(segment, root / 'usr/lib/firmware' / (name + suffix))+ for segment, root in segments.items() for suffix in ('', '.zst', '.xz', '.gz')]+ archived = [(segment, path) for segment, path in archived if path.is_file()]+ assert len(archived) == 1, ('Missing or ambiguous archived GSP payload', name, archived)+ pairs.append((name, *archived[0], present[0]))+ result = {}+ for name, segment, archived, installed in pairs:+ root = segments[segment]+ assert archived.resolve().is_relative_to(root.resolve()), 'Initramfs link escapes its extracted payload'+ expected, actual = content_digest(installed), content_digest(archived)+ assert expected == actual, ('Initramfs contains different payload bytes', name)+ result[name] = {'segment': segment, 'archive_path': str(archived.relative_to(root)), 'installed_path': str(installed),+ 'installed_file_sha256': digest(installed), 'archive_file_sha256': digest(archived),+ 'decompressed_sha256': actual}+ return result+++def module_identity(path, kernel, modules_root=Path('/usr/lib/modules')):+ """Resolve the guest's real aliases before accepting or hashing a module."""+ raw = Path(path)+ root = (modules_root / kernel).resolve(strict=True)+ resolved = raw.resolve(strict=True)+ assert raw.is_absolute() and root.is_dir() and resolved.is_file(), ('Not a regular module file', raw, resolved)+ assert resolved.is_relative_to(root), ('Module escapes expected kernel directory', raw, resolved, root)+ return {'path': str(raw), 'resolved_path': str(resolved), 'module_root': str(root), 'sha256': digest(resolved)}+++def validate_probe(result, lock, candidate, running_kernel):+ expected = lock['candidate' if candidate else 'baseline']['kernel']+ assert result['running_kernel'] == running_kernel+ assert result['installed_kernel'] == expected and result['headers_kernel'] == expected+ assert_versions(result['packages'], expected_versions(lock, candidate))+ assert result['boot']['vmlinuz-linux-lts'] == result['package_kernel_sha256']+ root = Path(result['module_root'])+ assert root.is_absolute() and root.name == expected and '..' not in root.parts+ version = result['packages']['nvidia-utils'].rsplit('-', 1)[0]+ for name in ('wl',) + NVIDIA:+ row = result['modules'][name]+ assert row['vermagic'].split()[0] == expected, ('Wrong module ABI', name, row)+ # These are already resolved in the guest. Never resolve guest paths on+ # the host when replaying pure receipt assertions.+ resolved = Path(row['resolved_path'])+ assert row['module_root'] == str(root) and row['sha256']+ assert resolved.is_absolute() and '..' not in resolved.parts and resolved != root and resolved.is_relative_to(root)+ if name in NVIDIA:+ assert row['owner'] == 'nvidia-open-lts', 'NVIDIA must remain the prebuilt package, not DKMS'+ assert row['version'] == version, ('NVIDIA userspace/module mismatch', row, version)+ assert re.search(r'broadcom-wl/[^,]+, ' + re.escape(expected) + r', [^\n]+: installed', result['dkms']), 'Automatic wl DKMS install is missing'+ assert result['initramfs']['kernel_namespaces'] == [expected]+ assert set(result['initramfs']['early_modules']) == set(EARLY)+++def probe(lock, candidate, running_kernel, output):+ assert not Path('/etc/harness-live').exists()+ system = load('system', SYSTEM)+ packages = inventory()+ kernel = packages['linux-lts'] + '-lts'+ result = {'running_kernel': run('uname', '-r'), 'installed_kernel': kernel, 'packages': packages,+ 'headers_kernel': Path(f'/usr/lib/modules/{kernel}/build/include/config/kernel.release').read_text().strip(),+ 'package_kernel_sha256': digest(f'/usr/lib/modules/{kernel}/vmlinuz'),+ 'boot': system.boot_hashes(Path('/boot')), 'modules': {}, 'dkms': run('dkms', 'status'),+ 'module_root': str(Path(f'/usr/lib/modules/{kernel}').resolve(strict=True)),+ 'lib_alias': {'target': os.readlink('/lib') if Path('/lib').is_symlink() else None,+ 'resolved': str(Path('/lib').resolve(strict=True))},+ 'runtime': runtime(lock), 'system_sha256': digest(SYSTEM),+ 'pacman_config': Path('/etc/pacman.conf').read_text(), 'node': run('node', '--version'),+ 'networking': run('nmcli', 'networking'),+ 'install': json.loads(Path('/var/lib/harness-os/install.json').read_text())}+ partial = Path(output).with_suffix('.partial.json')+ result['probe_stage'] = 'modules'+ save(partial, result)+ for name in ('wl',) + NVIDIA:+ path = run('modinfo', '-k', kernel, '-F', 'filename', name)+ row = {key: run('modinfo', '-k', kernel, '-F', key, name) for key in ('vermagic', 'version')}+ row.update(module_identity(path, kernel))+ if name in NVIDIA:+ row['owner'] = run('pacman', '-Qqo', path)+ result['modules'][name] = row+ result['probe_stage'] = 'initramfs-listings'+ save(partial, result)+ listings = {}+ for segment, option in [('early', '--early'), ('main', '--cpio')]:+ listings[segment] = run('lsinitcpio', '--list', option, '/boot/initramfs-linux-lts.img')+ Path(output).with_suffix('.initramfs-' + segment + '.txt').write_text(listings[segment] + '\n')+ listing = '\n'.join(listings.values())+ Path(output).with_suffix('.initramfs.txt').write_text(listing + '\n')+ firmware = run('modinfo', '-k', kernel, '-F', 'firmware', 'nvidia').splitlines()+ result['initramfs'] = initramfs_identity(listing, kernel, firmware)+ result['initramfs']['segments'] = {segment: {'listing_sha256': hashlib.sha256((text + '\n').encode()).hexdigest(),+ 'entries': len(text.splitlines())} for segment, text in listings.items()}+ # mkinitcpio 42.1 puts compressed modules/firmware in early CPIO. Inspect+ # both parts separately; matching names in both must not silently overwrite+ # one another. No build or repair command runs here.+ with tempfile.TemporaryDirectory(prefix='kernel-update-initrd-', dir='/var/tmp') as directory:+ segments = {name: Path(directory) / name for name in ('early', 'main')}+ try:+ for segment, option in [('early', '--early'), ('main', '--cpio')]:+ result['probe_stage'] = 'initramfs-extract-' + segment+ save(partial, result)+ segments[segment].mkdir()+ subprocess.run(['lsinitcpio', '--extract', option, '/boot/initramfs-linux-lts.img'],+ cwd=segments[segment], check=True, timeout=60, stdout=subprocess.DEVNULL)+ result['probe_stage'] = 'initramfs-payload-bytes'+ result['initramfs']['payloads'] = payload_identity(segments, result['initramfs'], result['modules'])+ except Exception as error:+ result['probe_error'] = repr(error)+ raise+ finally:+ result['initramfs']['extracted_candidates'] = {+ segment: sorted(str(path.relative_to(root)) for pattern in+ ('usr/lib/modules/**/nvidia*.ko*', 'usr/lib/firmware/nvidia/**/*')+ for path in root.glob(pattern) if path.is_file() or path.is_symlink())+ for segment, root in segments.items()}+ save(partial, result)+ result['probe_stage'] = 'module-consistency'+ save(partial, result)+ validate_probe(result, lock, candidate, running_kernel)+ snapshot = lock['candidate' if candidate else 'baseline']['snapshot']+ assert set(re.findall(r'archive.archlinux.org/repos/(\d{4}/\d{2}/\d{2})/', result['pacman_config'])) == {snapshot}+ assert not Path('/var/lib/pacman/db.lck').exists()+ if kernel == running_kernel:+ # Real module loading, even though no physical Broadcom radio is present.+ run('modprobe', 'wl')+ assert Path('/sys/module/wl').is_dir()+ result['wl_loaded'] = True+ run('modprobe', '-r', 'wl')+ result['probe_stage'] = 'complete'+ save(partial, result)+ save(output, result)+ return result+++def install(lock, candidate_path):+ assert Path('/etc/harness-live').is_file() and run('nmcli', 'networking') == 'disabled'+ hardware = load('hardware', '/usr/lib/harness-os/hardware.py')+ installer = load('installer', '/usr/lib/harness-os/install.py')+ broadcom = hardware.bundle_manifest(hardware.BUNDLE, all_files=True)+ nvidia = hardware.nvidia_bundle_manifest(hardware.NVIDIA_BUNDLE, all_files=True)+ assert broadcom['kernel'] == nvidia['kernel'] == lock['baseline']['kernel']+ gpu = next(identity for identity, names in nvidia['supported_devices'].items()+ if any('GeForce RTX 4090' in name for name in names))+ devices = [dict(address='0000:03:00.0', id='14e4:43a0', **{'class': '028000'}, driver=None, interfaces=[]),+ dict(address='0000:04:00.0', id=gpu, **{'class': '030000'}, driver='nouveau', interfaces=[])]+ result = {'devices': devices, 'image_system_sha256': digest(SYSTEM), 'candidate_system_sha256': digest(candidate_path),+ 'image_hardware_sha256': digest('/usr/lib/harness-os/hardware.py'),+ 'image_installer_sha256': digest('/usr/lib/harness-os/install.py')}+ original = installer.run++ def select(*args, **kwargs):+ if args[:3] != ('/usr/bin/python3', '/usr/lib/harness-os/hardware.py', 'configure-install'):+ return original(*args, **kwargs)+ target = Path(args[3])+ assert target == Path('/mnt/harness-os') and target.is_mount()+ before = dict(line.split(' ', 1) for line in hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True).splitlines())+ result['selection'] = hardware.configure_install(target, devices)+ assert set(result['selection']['drivers']) == {'broadcom-wl-dkms', 'nvidia-open-lts'}+ after = dict(line.split(' ', 1) for line in hardware.run('arch-chroot', target, 'pacman', '-Q', capture=True).splitlines())+ assert all(after.get(name) == version for name, version in before.items())+ expected = {row['name']: row['version'] for bundle in (broadcom, nvidia) for row in bundle['packages'].values()}+ assert {name: version for name, version in after.items() if name not in before} == expected+ assert_versions(after, lock['baseline']['packages'])+ installed_system = target / SYSTEM.relative_to('/')+ assert digest(installed_system) == result['image_system_sha256']+ installed_system.write_bytes(candidate_path.read_bytes())+ # Apply before the first installed boot; no public feed may replace the+ # frozen runtime. These are private fixture settings in the root snapshot.+ for name in MASKS:+ path = target / 'etc/systemd/user' / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.symlink_to('/dev/null')+ result['optional_packages'] = expected++ installer.run = select+ config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda',+ username='me', hostname='harness', password='test-password-123', encrypt=True, serial_console=True)+ installer.install(config, installer.live_payload(), Path('/mnt/harness-os'))+ assert result.get('optional_packages'), 'Installer never selected the two optional stacks'+ return result+++def database(path):+ packages = {}+ with tarfile.open(path) as archive:+ for entry in archive:+ if not entry.isfile() or not entry.name.endswith('/desc'):+ continue+ sections = archive.extractfile(entry).read().decode().strip().split('\n\n')+ fields = {lines[0].strip('%'): lines[1:] for lines in (section.splitlines() for section in sections)}+ packages[fields['NAME'][0]] = fields+ return packages+++def verify_metadata(lock, folder, fetch):+ packages = {}+ for repo, expected in lock['candidate']['repositories'].items():+ path = folder / (repo + '.db') if fetch else Path('/var/lib/pacman/sync') / (repo + '.db')+ if fetch:+ # Two bounded reads of the exact dated metadata, with no mirror fallback.+ with urlopen(expected['url'], timeout=30) as response:+ data = response.read(expected['bytes'] + 1)+ path.write_bytes(data)+ assert path.stat().st_size == expected['bytes'] and digest(path) == expected['sha256'], ('Archive database changed', repo)+ for name, row in database(path).items():+ row['repository'] = repo+ packages[name] = row+ for name, expected in lock['candidate']['packages'].items():+ row = packages[name]+ for key, field in [('version', 'VERSION'), ('filename', 'FILENAME'), ('sha256', 'SHA256SUM'), ('bytes', 'CSIZE')]:+ assert str(expected[key]) == row[field][0], (name, field)+ assert row['PGPSIG'][0], ('Package signature absent', name)+ return packages+++def verify_transaction(before, after, metadata, folder):+ changed = {name: version for name, version in after.items() if before.get(name) != version}+ assert 'linux-lts' in changed and 'linux-lts-headers' in changed and 'nvidia-open-lts' in changed+ rows = {}+ for name, version in sorted(changed.items()):+ item = metadata[name]+ assert version == item['VERSION'][0], ('Package not from the dated snapshot', name, version)+ archive = Path('/var/cache/pacman/pkg') / item['FILENAME'][0]+ assert archive.stat().st_size == int(item['CSIZE'][0]) and digest(archive) == item['SHA256SUM'][0]+ signature = folder / (archive.name + '.sig')+ signature.write_bytes(base64.b64decode(item['PGPSIG'][0], validate=True))+ verified = subprocess.run(['pacman-key', '--verify', str(signature), str(archive)],+ capture_output=True, text=True, timeout=30)+ assert verified.returncode == 0, (name, verified.stdout, verified.stderr)+ rows[name] = {'version': version, 'repository': item['repository'], 'filename': archive.name,+ 'bytes': archive.stat().st_size, 'sha256': digest(archive),+ 'signature_sha256': digest(signature), 'signature_base64': item['PGPSIG'][0],+ 'signature_verification': verified.stdout + verified.stderr}+ return {'changed': rows, 'removed': {name: version for name, version in before.items() if name not in after}}+++def update(lock, folder, baseline):+ system = load('system', SYSTEM)+ before = inventory()+ assert before == baseline['packages']+ config = Path('/etc/pacman.conf').read_text()+ assert config == baseline['pacman_config']+ assert re.findall(r'^\[([^]]+)\]', config, re.M) == ['options', 'core', 'extra']+ policy = run('pacman-conf', 'SigLevel')+ assert 'PackageRequired' in policy and 'PackageTrustedOnly' in policy and 'TrustAll' not in policy+ assert not re.search(r'^\s*(IgnorePkg|IgnoreGroup|NoUpgrade)\s*=', config, re.M)+ verify_metadata(lock, folder, fetch=True)+ before_checkpoints = {p.parent.name for p in Path('/.snapshots').glob('*/checkpoint.json')}+ # Use the real API and every normal transaction hook. Never invoke DKMS or+ # mkinitcpio manually: repairing a hook failure would invalidate this gate.+ started = time.monotonic()+ with system.operation_lock():+ system.update(lock['candidate']['snapshot'], noninteractive=True)+ receipt = json.loads(Path('/var/lib/harness-os/update.json').read_text())+ assert receipt['exit_status'] == 0+ checkpoint = Path('/.snapshots') / receipt['checkpoint']+ assert checkpoint.name not in before_checkpoints+ assert {p.parent.name for p in Path('/.snapshots').glob('*/checkpoint.json')} - before_checkpoints == {checkpoint.name}+ meta = json.loads((checkpoint / 'checkpoint.json').read_text())+ assert meta['boot_sha256'] == baseline['boot'] and meta['reason'] == 'before-update'+ assert meta['root_uuid'] == baseline['install']['root_uuid'] and meta['boot_uuid'] == baseline['install']['boot_uuid']+ assert system.boot_hashes(checkpoint / 'boot') == baseline['boot']+ assert run('pacman-conf', 'SigLevel') == policy+ assert Path('/etc/pacman.conf').read_text() == system.advance_snapshot(config, lock['candidate']['snapshot'])+ metadata = verify_metadata(lock, folder, fetch=False)+ closure = verify_transaction(before, inventory(), metadata, folder)+ remaining = subprocess.run(['pacman', '-Qu'], capture_output=True, text=True, timeout=30)+ assert remaining.returncode in (0, 1) and not remaining.stdout.strip() and not remaining.stderr.strip(), ('Full upgrade query failed or left pending packages', remaining.stdout, remaining.stderr)+ result = {'seconds': round(time.monotonic() - started, 3), 'update_receipt': receipt,+ 'checkpoint': meta, 'checkpoint_sha256': digest(checkpoint / 'checkpoint.json'),+ 'signature_policy': policy, 'transaction': closure}+ save(folder / 'transaction.json', result)+ candidate = probe(lock, True, lock['baseline']['kernel'], folder / 'pre-reboot.json')+ validate_transition(baseline, candidate)+ return result+++def validate_transition(before, after):+ assert before['installed_kernel'] != after['installed_kernel']+ assert before['boot']['vmlinuz-linux-lts'] != after['boot']['vmlinuz-linux-lts'], 'Kernel bytes did not change'+ assert before['boot']['initramfs-linux-lts.img'] != after['boot']['initramfs-linux-lts.img']+ assert before['runtime'] == after['runtime']+ assert before['system_sha256'] == after['system_sha256']+++def process(pid):+ path = Path('/proc') / str(pid)+ fields = (path / 'stat').read_text().rsplit(')', 1)[1].split()+ executable = path / 'exe'+ info = executable.stat()+ # A full base update may unlink the running interpreter. The open inode+ # and process must survive; Linux's added " (deleted)" suffix is expected.+ return {'pid': pid, 'starttime': fields[19], 'exe': os.readlink(executable).removesuffix(' (deleted)'),+ 'exe_inode': info.st_ino, 'exe_device': info.st_dev, 'exe_sha256': digest(executable)}+++def start_agent(window, directory):+ directory.mkdir(parents=True, exist_ok=True)+ pid_file = Path('/tmp') / (window + '.pid')+ assert not pid_file.exists()+ run('hn', 'new-window', '-d', '-n', window,+ 'echo $$ > ' + str(pid_file) + '; cd ' + str(directory) + '; exec opencode')+ deadline = time.monotonic() + 45+ pane = ''+ while time.monotonic() < deadline:+ if pid_file.exists():+ value = pid_file.read_text().strip()+ if not value.isdigit():+ time.sleep(.1)+ continue+ pid = int(value)+ comm = Path(f'/proc/{pid}/comm')+ pane = run('hn', 'capture-pane', '-p', '-t', window)+ # These ready controls are present in the retained preview14 pane;+ # a live process or healthy neighboring shell alone is insufficient.+ if comm.exists() and comm.read_text().strip() == 'opencode' and 'Ask anything' in pane and 'ctrl+p commands' in pane:+ before = process(pid)+ time.sleep(.5)+ assert process(pid) == before+ return {'process': before, 'pane': pane, 'window': window,+ 'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text(), 'kernel': run('uname', '-r')}+ time.sleep(.25)+ raise AssertionError('Fresh OpenCode pane did not reach its ready screen: ' + pane)+++def live_start():+ assert os.getuid() == 1000 and Path.home() == Path('/home/me')+ PROJECT.mkdir(parents=True, exist_ok=False)+ (PROJECT / 'keep.txt').write_text('before checkpoint\n')+ (PROJECT / 'heartbeat.py').write_text('import os,time\nfrom pathlib import Path\np=Path(__file__).parent\n'+ '(p/"pid").write_text(str(os.getpid()))\nwhile True:\n'+ ' with (p/"heartbeat").open("a") as f: f.write("alive\\n")\n time.sleep(.2)\n')+ run('hn', 'new-window', '-d', '-n', 'kernel-update-survivor', 'python3 ' + str(PROJECT / 'heartbeat.py'))+ deadline = time.monotonic() + 20+ while not (PROJECT / 'heartbeat').exists():+ assert time.monotonic() < deadline, 'Survivor pane did not start'+ time.sleep(.1)+ pids = {'heartbeat': int((PROJECT / 'pid').read_text())}+ agent = start_agent('kernel-update-agent', PROJECT / 'agent')+ pids['opencode'] = agent['process']['pid']+ for name in ('hn-screen', 'harness-daemon'):+ pids[name] = int(run('systemctl', '--user', 'show', '-p', 'MainPID', '--value', name))+ assert pids[name] > 0+ clients = run('hn', 'hn-list-clients', '-F', '#{client_pid} #{session_id}').splitlines()+ assert len(clients) == 1, ('Expected one rendering hn client', clients)+ pids['hn-client'] = int(clients[0].split()[0])+ client = Path('/proc') / str(pids['hn-client'])+ assert (client / 'exe').samefile('/usr/lib/harness/harness-tui')+ assert re.fullmatch(r'/dev/pts/\d+', os.readlink(client / 'fd/0'))+ assert any(line.endswith('/hn-screen.service') for line in (client / 'cgroup').read_text().splitlines())+ return {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text(),+ 'processes': {name: process(pid) for name, pid in pids.items()},+ 'client': clients[0], 'agent_pane': agent['pane'],+ 'heartbeat_bytes': (PROJECT / 'heartbeat').stat().st_size}+++def live_check(before):+ assert Path('/proc/sys/kernel/random/boot_id').read_text() == before['boot_id']+ for row in before['processes'].values():+ assert process(row['pid']) == row, ('Running work was replaced', row)+ assert run('hn', 'hn-list-clients', '-F', '#{client_pid} #{session_id}') == before['client']+ size = (PROJECT / 'heartbeat').stat().st_size+ assert size > before['heartbeat_bytes']+ time.sleep(.5)+ assert (PROJECT / 'heartbeat').stat().st_size > size+ assert (PROJECT / 'keep.txt').read_text() == 'before checkpoint\n'+ return {'original_processes_alive': before, 'heartbeat_bytes': (PROJECT / 'heartbeat').stat().st_size}+++def project_edit(transaction):+ assert os.getuid() == 1000+ (PROJECT / 'keep.txt').write_text('edited after checkpoint ' + transaction['checkpoint']['name'] + '\n')+ (PROJECT / 'new.txt').write_text('created after checkpoint\n')+ assert min((PROJECT / name).stat().st_mtime for name in ('keep.txt', 'new.txt')) > datetime.fromisoformat(transaction['checkpoint']['created_at']).timestamp()+ return project_state()+++def project_state():+ result = {}+ for name in ('keep.txt', 'new.txt'):+ path = PROJECT / name+ info = path.stat()+ assert info.st_uid == info.st_gid == 1000+ result[name] = {'sha256': digest(path), 'uid': info.st_uid, 'gid': info.st_gid, 'mtime_ns': info.st_mtime_ns}+ return result+++def validate_recovery(baseline, restored, transaction, project_before, project_after):+ for name in ('packages', 'boot', 'modules', 'headers_kernel', 'package_kernel_sha256', 'runtime', 'system_sha256', 'pacman_config', 'install'):+ assert baseline[name] == restored[name], ('Recovery identity differs', name)+ assert restored['running_kernel'] == baseline['running_kernel']+ assert restored['boot'] == transaction['checkpoint']['boot_sha256']+ assert project_before == project_after, 'Post-checkpoint project edits changed during recovery'+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('phase', choices=['install', 'baseline', 'update', 'candidate', 'recovered', 'live-start', 'live-check', 'project-edit', 'project-state', 'fresh-agent'])+ parser.add_argument('--lock', type=Path, required=True)+ parser.add_argument('--output', type=Path, required=True)+ parser.add_argument('--candidate-system', type=Path)+ parser.add_argument('--before', type=Path)+ args = parser.parse_args()+ assert run('lsblk', '-ndo', 'SERIAL', '/dev/vda') == 'HN_OS_TEST'+ lock = json.loads(args.lock.read_text())+ validate_lock(lock)+ if args.phase.startswith('live-') or args.phase.startswith('project-') or args.phase == 'fresh-agent':+ assert os.getuid() == 1000 and not Path('/etc/harness-live').exists()+ else:+ assert os.geteuid() == 0+ args.output.parent.mkdir(parents=True, exist_ok=True)+ if args.phase == 'install':+ result = install(lock, args.candidate_system)+ elif args.phase == 'update':+ result = update(lock, args.output.parent, json.loads(args.before.read_text()))+ elif args.phase == 'live-start':+ result = live_start()+ elif args.phase == 'live-check':+ result = live_check(json.loads(args.before.read_text()))+ elif args.phase == 'project-edit':+ result = project_edit(json.loads(args.before.read_text()))+ elif args.phase == 'project-state':+ result = project_state()+ elif args.phase == 'fresh-agent':+ identity = Path('/proc/sys/kernel/random/boot_id').read_text().strip()[:8]+ result = start_agent('kernel-update-fresh-' + identity, PROJECT / ('agent-' + identity))+ else:+ candidate = args.phase == 'candidate'+ result = probe(lock, candidate, lock['candidate' if candidate else 'baseline']['kernel'], args.output)+ save(args.output, result)+ print('HN_HARDWARE_UPDATE=' + args.phase, flush=True)+++if __name__ == '__main__':+ main()diff --git a/os/tests/hardware_update_vm.py b/os/tests/hardware_update_vm.pynew file mode 100644index 000000000..13b76dd5d--- /dev/null+++ b/os/tests/hardware_update_vm.py@@ -0,0 +1,331 @@+#!/usr/bin/env python3+"""One native changed-kernel update/recovery VM, reusing a frozen preview ISO."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import select+import shlex+import shutil+import signal+import subprocess+import time+import uuid++from footprint_vm import copy_file+from hardware_install_vm import candidate_record+from hardware_update_guest import digest, validate_lock, validate_recovery, validate_transition+from vm import VM, check_graphical_keyboard+++def verify_image(iso, lock):+ old = lock['baseline']+ manifest_path = iso.with_name('manifest.json')+ assert digest(manifest_path) == old['manifest_sha256'], 'Wrong image manifest'+ manifest = json.loads(manifest_path.read_text())+ assert manifest['source_commit'] == old['source_commit']+ assert manifest['iso'] == old['iso']+ assert iso.name == old['iso']['name'] and iso.stat().st_size == old['iso']['bytes']+ assert digest(iso) == old['iso']['sha256'], 'Wrong preview14 ISO'+ assert manifest['harness_inputs']['files'] == old['runtime_files']+ assert manifest['harness_inputs']['source_commit'] == old['source_commit']+ assert manifest['package_version'] == old['packages']['harness-os']+ assert manifest['arch_snapshot'] == old['snapshot']+ assert {'broadcom-offline', 'nvidia-offline'}.issubset(manifest['capabilities'])+ return manifest+++def graceful_stop(vm, privileged, timeout=45):+ # Poweroff may terminate the requesting shell before it prints a command+ # status. Require QMP's fresh guest-shutdown event and the owned QEMU+ # process's real exit status; the live ISO need not log its kernel to serial.+ process = vm.process+ started = time.monotonic()+ deadline = started + timeout+ event = {'boot': vm.boot_count, 'qemu_pid': process.pid, 'started_at': time.time(),+ 'status': 'failed', 'command_status': None, 'serial_eof': False,+ 'qmp_before_request': [], 'qmp_after_request': []}+ output = bytearray()+ qmp_timeout = vm.qmp.gettimeout()++ def remaining():+ value = deadline - time.monotonic()+ if value <= 0:+ raise TimeoutError('Guest shutdown exceeded its bounded deadline')+ return value++ def qmp_message():+ # Read the file object's buffer even after QEMU exits; select() on the+ # socket alone cannot account for messages already buffered by readline.+ vm.qmp.settimeout(remaining())+ line = vm.qmp_file.readline(65537)+ assert len(line) <= 65536, 'Oversized QMP shutdown message'+ return json.loads(line) if line else None++ try:+ assert process.poll() is None, 'QEMU had already exited before shutdown request'+ # Old buffered bytes and earlier boots' log entries cannot prove this+ # shutdown. Drain pending console output before sending the request.+ while select.select([vm.serial], [], [], 0)[0]:+ remaining()+ chunk = vm.serial.recv(65536)+ assert chunk, 'Serial was disconnected before shutdown request'+ vm.log.write(chunk)+ event['serial_offset'] = vm.log.tell()+ # A correlated response separates earlier events from this request,+ # including events already read into qmp_file's buffer by other probes.+ barrier = uuid.uuid4().hex+ vm.qmp.sendall((json.dumps({'execute': 'query-status', 'id': barrier}) + '\n').encode())+ while True:+ message = qmp_message()+ assert message is not None, 'QMP disconnected before shutdown request'+ event['qmp_before_request'].append(message)+ if message.get('id') == barrier:+ status = message.get('return', {})+ assert 'error' not in message and status.get('running') is True and status.get('status') == 'running', 'Guest was not running before shutdown'+ break+ assert process.poll() is None, 'QEMU exited before shutdown request'+ marker = 'HN_POWEROFF_' + uuid.uuid4().hex+ command = ('sudo -n ' if privileged else '') + 'systemctl --no-block poweroff'+ event['command'] = command+ vm.send('(' + command + f"); hn_poweroff_status=$?; printf '\\n{marker}:%s\\n' \"$hn_poweroff_status\"\n")+ while not event['serial_eof']:+ if select.select([vm.serial], [], [], min(1, remaining()))[0]:+ chunk = vm.serial.recv(65536)+ if not chunk:+ event['serial_eof'] = True+ break+ vm.log.write(chunk)+ output.extend(chunk)+ match = re.search(rb'\r?\n' + marker.encode() + rb':(\d+)\r?\n', output)+ if match:+ event['command_status'] = int(match.group(1))+ assert event['command_status'] == 0, 'Guest poweroff command failed'+ # Drain QMP through EOF as well, retaining its exact events independently+ # of serial-console configuration and the timing of the child exit.+ while True:+ message = qmp_message()+ if message is None:+ break+ event['qmp_after_request'].append(message)+ event['qemu_exit_status'] = process.wait(timeout=remaining())+ assert event['qemu_exit_status'] == 0, 'QEMU did not exit cleanly'+ event['guest_power_down'] = bool(re.search(rb'\[\s*[0-9.]+\]\s+reboot: Power down(?:\r?\n|$)', output))+ shutdown = [row for row in event['qmp_after_request'] if row.get('event') == 'SHUTDOWN']+ assert len(shutdown) == 1, 'Missing or ambiguous fresh QMP shutdown event'+ event['guest_shutdown'] = shutdown[0].get('data', {})+ assert event['guest_shutdown'].get('guest') is True and event['guest_shutdown'].get('reason') == 'guest-shutdown', 'QEMU exit was not a guest shutdown'+ assert not any(row.get('event') in ('RESET', 'GUEST_PANICKED') for row in event['qmp_after_request']), 'Guest reset or panicked during shutdown'+ event['status'] = 'passed'+ except BaseException as error:+ event['error'] = repr(error)+ raise+ finally:+ event['qemu_exit_status'] = process.poll()+ event['seconds'] = round(time.monotonic() - started, 3)+ event['serial_tail'] = output[-2000:].decode(errors='replace')+ with (vm.folder / 'shutdown-events.jsonl').open('a') as log:+ log.write(json.dumps(event) + '\n')+ vm.qmp.settimeout(qmp_timeout)+ vm.stop()+ return event+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--iso', type=Path, required=True)+ parser.add_argument('--snapshot-lock', type=Path, default=Path(__file__).with_name('hardware-update.lock.json'))+ parser.add_argument('--candidate-system', type=Path, required=True)+ parser.add_argument('--output', type=Path, default=Path('os/test-results/hardware-update'))+ args = parser.parse_args()+ assert os.uname().machine == 'x86_64' and os.access('/dev/kvm', os.R_OK | os.W_OK), 'Native x86 KVM is required'+ lock = json.loads(args.snapshot_lock.read_text())+ validate_lock(lock)+ manifest = verify_image(args.iso.resolve(), lock)+ candidate = candidate_record(args.candidate_system)+ assert candidate['path'] == 'os/system.py', 'Only the OS update/recovery helper may be overlaid'+ sources = {name: candidate_record(Path(__file__).with_name(name)) for name in+ ('hardware_update_vm.py', 'hardware_update_guest.py',+ 'vm.py', 'footprint_vm.py', 'hardware_install_vm.py')}+ sources['lock'] = candidate_record(args.snapshot_lock)+ assert sources['lock']['path'] == 'os/tests/hardware-update.lock.json'+ sources['workflow'] = candidate_record(Path(__file__).resolve().parents[2] / '.github/workflows/os.yml')+ assert {row['source_commit'] for row in sources.values()} == {candidate['source_commit']}+ folder = args.output.resolve()+ folder.mkdir(parents=True, exist_ok=False)+ assert shutil.disk_usage(folder).free >= 12 * 1024**3, 'This installed snapshot/rollback gate needs 12 GiB free'+ vm = VM(folder, args.iso.resolve(), 'uefi', 2048, 'usb')+ config = dict(username='me', password='test-password-123', encrypt=True)+ receipt = {'status': 'running', 'started_at': time.time(), 'image_source_commit': manifest['source_commit'],+ 'image_run_id': lock['baseline']['image_run_id'], 'iso': lock['baseline']['iso'],+ 'candidate_system': candidate, 'test_sources': sources, 'memory_mib': 2048, 'firmware': 'uefi',+ 'limits': ['Full-upgrade API, not public Update UI activation.',+ 'Synthetic PCI selection and real software hooks, no physical radio or GPU.',+ 'Combined driver row does not prove NVIDIA-only dependency footprint.',+ 'Offline checkpoint recovery, not a power-cut atomicity experiment.'], 'phases': {}}++ def timeout(_signum, _frame):+ raise TimeoutError('Changed-kernel gate exceeded its 1200 second budget')++ signal.signal(signal.SIGALRM, timeout)+ signal.alarm(1200)++ def authenticate():+ vm.command('printf %s ' + shlex.quote(config['password'] + '\n') + ' | sudo -S -v')++ def transfer(live):+ # Serial transfer keeps installation and recovery completely offline.+ prefix = '/run' if live else '/tmp'+ for source, name in [(Path(__file__).with_name('hardware_update_guest.py'), 'hardware-update-guest.py'),+ (args.snapshot_lock, 'hardware-update-lock.json')]:+ copy_file(vm, source.read_bytes(), prefix + '/' + name)+ return prefix++ def guest(phase, before=None, live=False, extra=(), seconds=90):+ prefix = '/run' if live else '/tmp'+ destination = prefix + '/hardware-update/' + phase + '.json'+ command = ([] if live or phase.startswith(('live-', 'project-')) or phase == 'fresh-agent' else ['sudo', '-n'])+ command += ['python3', prefix + '/hardware-update-guest.py', phase,+ '--lock', prefix + '/hardware-update-lock.json', '--output', destination]+ if before is not None:+ copy_file(vm, json.dumps(before).encode(), prefix + '/hardware-update-before.json')+ command += ['--before', prefix + '/hardware-update-before.json']+ command += list(extra)+ started = time.monotonic()+ output, status = vm.command(shlex.join(command), timeout=seconds, check=False)+ (folder / (phase + '.log')).write_text(output)+ assert status == 0, phase + ' failed; see its full log and serial.log'+ result = json.loads(vm.read_file(destination))+ (folder / (phase + '.json')).write_text(json.dumps(result, indent=2) + '\n')+ probe = 'pre-reboot' if phase == 'update' else phase+ if probe in ('baseline', 'pre-reboot', 'candidate', 'recovered'):+ for suffix in ('.partial.json', '.initramfs.txt', '.initramfs-early.txt', '.initramfs-main.txt'):+ name = probe + suffix+ (folder / name).write_bytes(vm.read_file(prefix + '/hardware-update/' + name))+ receipt['phases'][phase] = {'seconds': round(time.monotonic() - started, 3), 'status': 'passed'}+ return result++ def installed_boot(label):+ vm.start(live=False)+ vm.login_installed(config)+ authenticate()+ transfer(False)+ vm.command('mkdir -p /tmp/hardware-update')+ vm.command('test "$(systemctl --user is-enabled harness-update.timer)" = masked && '+ 'test "$(systemctl --user is-enabled harness-update.service)" = masked')+ receipt[label + '_keyboard'] = check_graphical_keyboard(vm, label)+ vm.boot_diagnostics(config, label)++ try:+ vm.start(live=True)+ vm.wait(r'root@[^\r\n]*[#] ', timeout=180)+ vm.shell_ready = True+ vm.command('stty -echo; nmcli networking off')+ transfer(True)+ copy_file(vm, args.candidate_system.read_bytes(), '/run/system-candidate.py')+ receipt['installation'] = guest('install', live=True, extra=('--candidate-system', '/run/system-candidate.py'), seconds=360)+ assert receipt['installation']['candidate_system_sha256'] == candidate['sha256']+ vm.screenshot('01-installed-offline')+ graceful_stop(vm, False)++ installed_boot('baseline')+ baseline = guest('baseline')+ assert baseline['system_sha256'] == candidate['sha256']+ live = guest('live-start')+ # Ensure connectivity for the full update after checking runtime masks+ # and identities. Installed boot may already have enabled networking;+ # baseline.json records that state. Install/recovery are explicitly offline.+ vm.command('sudo -n nmcli networking on && nm-online -q --timeout=60')+ transaction = guest('update', before=baseline, seconds=650)+ before_reboot = json.loads(vm.read_file('/tmp/hardware-update/pre-reboot.json'))+ (folder / 'pre-reboot.json').write_text(json.dumps(before_reboot, indent=2) + '\n')+ validate_transition(baseline, before_reboot)+ receipt['live_processes'] = guest('live-check', before=live)+ receipt['apply_keyboard'] = check_graphical_keyboard(vm, 'applied')+ project = guest('project-edit', before=transaction)+ receipt['checkpoint'] = transaction['checkpoint']+ receipt['checkpoint_sha256'] = transaction['checkpoint_sha256']+ authenticate()+ vm.command('sudo -n cp /var/log/pacman.log /tmp/hardware-update/pacman.log && '+ 'sudo -n chmod -R a+rX /tmp/hardware-update')+ (folder / 'pacman.log').write_bytes(vm.read_file('/tmp/hardware-update/pacman.log'))+ vm.screenshot('02-applied-before-reboot')+ graceful_stop(vm, True)++ installed_boot('candidate')+ updated = guest('candidate')+ validate_transition(baseline, updated)+ assert updated['boot'] == before_reboot['boot'] and updated['modules'] == before_reboot['modules']+ assert guest('project-state') == project+ receipt['candidate_agent'] = guest('fresh-agent')+ (folder / 'candidate-project.json').write_text(json.dumps(project, indent=2) + '\n')+ receipt['candidate_kernel'] = updated['running_kernel']+ # Explicit cold boot boundary: old PIDs are not compared after this point.+ authenticate()+ graceful_stop(vm, True)++ vm.start(live=True)+ vm.wait(r'root@[^\r\n]*[#] ', timeout=180)+ vm.shell_ready = True+ vm.command('stty -echo; nmcli networking off')+ original = hashlib.sha256(vm.read_file(str(Path('/usr/lib/harness-os/system.py')))).hexdigest()+ assert original == receipt['installation']['image_system_sha256']+ copy_file(vm, args.candidate_system.read_bytes(), '/usr/lib/harness-os/system.py')+ receipt['recovery_system_sha256'] = hashlib.sha256(vm.read_file('/usr/lib/harness-os/system.py')).hexdigest()+ assert receipt['recovery_system_sha256'] == candidate['sha256']+ vm.command('printf %s ' + shlex.quote(config['password']) + ' | cryptsetup open --key-file=- /dev/vda3 hn-recovery')+ # No inspection mounts: production recover validates and mounts the real+ # root/boot identities itself, then restores @ while preserving @home.+ started = time.monotonic()+ output, status = vm.command('hn-os recover /dev/mapper/hn-recovery ' ++ shlex.quote(transaction['checkpoint']['name']), timeout=180, check=False)+ (folder / 'offline-recovery.log').write_text(output)+ assert status == 0, 'Offline recovery failed; see offline-recovery.log'+ receipt['phases']['offline-recovery'] = {'status': 'passed', 'seconds': round(time.monotonic() - started, 3)}+ vm.command('cryptsetup close hn-recovery')+ graceful_stop(vm, False)++ installed_boot('recovered')+ restored = guest('recovered')+ receipt['recovered_agent'] = guest('fresh-agent')+ # project-state is recorded separately on each boot; no old process IDs+ # are treated as evidence of functionality after a real reboot.+ post = guest('project-state')+ validate_recovery(baseline, restored, transaction, project, post)+ checkpoint_path = '/.snapshots/' + transaction['checkpoint']['name'] + '/checkpoint.json'+ vm.command('sudo -n cp ' + shlex.quote(checkpoint_path) + ' /tmp/original-checkpoint.json && sudo -n chmod a+r /tmp/original-checkpoint.json')+ assert hashlib.sha256(vm.read_file('/tmp/original-checkpoint.json')).hexdigest() == transaction['checkpoint_sha256']+ receipt['restored_kernel'] = restored['running_kernel']+ receipt['post_checkpoint_project'] = post+ receipt['status'] = 'passed'+ graceful_stop(vm, True)+ except BaseException as error:+ receipt.update(status='failed', error=repr(error))+ try:+ vm.screenshot('failure')+ diagnostics, _ = vm.command('cat /var/log/pacman.log; dkms status; systemctl --failed --no-pager', timeout=20, check=False)+ (folder / 'failure-diagnostics.log').write_text(diagnostics)+ names = ['transaction.json'] + [phase + suffix for phase in ('baseline', 'pre-reboot', 'candidate', 'recovered')+ for suffix in ('.json', '.partial.json', '.initramfs.txt', '.initramfs-early.txt', '.initramfs-main.txt')]+ for name in names:+ remote = '/tmp/hardware-update/' + name+ _, exists = vm.command('test -r ' + shlex.quote(remote), timeout=5, check=False)+ if exists == 0:+ (folder / ('failure-' + name)).write_bytes(vm.read_file(remote, timeout=15))+ except Exception:+ pass+ raise+ finally:+ signal.alarm(0)+ receipt['finished_at'] = time.time()+ (folder / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')+ vm.stop()+ vm.log.close()+ vm.stderr.close()+ vm.control.cleanup()+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_hardware_update_fixture.py b/os/tests/test_hardware_update_fixture.pynew file mode 100644index 000000000..821627090--- /dev/null+++ b/os/tests/test_hardware_update_fixture.py@@ -0,0 +1,430 @@+"""Reject plausible false passes in the private changed-kernel acceptance gate."""+import copy+import gzip+import hashlib+import io+import json+from pathlib import Path+import select+import socket+import subprocess+import sys+import tarfile+import tempfile+from types import SimpleNamespace+import unittest++from hardware_update_guest import (EARLY, NVIDIA, database, expected_versions,+ initramfs_identity, module_identity, payload_identity, validate_lock, validate_probe, validate_recovery, validate_transition)+from hardware_update_vm import graceful_stop, verify_image++LOCK = json.loads(Path(__file__).with_name('hardware-update.lock.json').read_text())+++def probe(candidate=False):+ kernel = LOCK['candidate' if candidate else 'baseline']['kernel']+ packages = expected_versions(LOCK, candidate)+ modules = {name: {'path': f'/usr/lib/modules/{kernel}/kernel/{name}.ko.zst',+ 'vermagic': kernel + ' SMP preempt mod_unload', 'sha256': 'a' * 64,+ 'version': '615.71.09', 'owner': 'nvidia-open-lts'} for name in NVIDIA}+ modules['wl'] = {'path': f'/usr/lib/modules/{kernel}/updates/dkms/wl.ko.zst',+ 'vermagic': kernel + ' SMP preempt mod_unload', 'sha256': 'b' * 64, 'version': '6.30.223.271'}+ for row in modules.values():+ row.update(resolved_path=row['path'], module_root=f'/usr/lib/modules/{kernel}')+ kernel_hash, initrd_hash = ('c' * 64, 'd' * 64) if candidate else ('e' * 64, 'f' * 64)+ return {'running_kernel': kernel, 'installed_kernel': kernel, 'packages': packages,+ 'headers_kernel': kernel, 'package_kernel_sha256': kernel_hash,+ 'boot': {'vmlinuz-linux-lts': kernel_hash, 'initramfs-linux-lts.img': initrd_hash, 'grub/grub.cfg': '9' * 64},+ 'modules': modules, 'module_root': f'/usr/lib/modules/{kernel}',+ 'dkms': f'broadcom-wl/6.30.223.271, {kernel}, x86_64: installed',+ 'initramfs': {'kernel_namespaces': [kernel], 'early_modules': dict.fromkeys(EARLY, 'present')},+ 'runtime': {'files': LOCK['baseline']['runtime_files'], 'runtime_json_sha256': '8' * 64},+ 'system_sha256': '7' * 64, 'pacman_config': 'original dated config', 'install': {'root_uuid': 'root', 'boot_uuid': 'boot'}}+++class LockTests(unittest.TestCase):+ def test_recorded_different_kernel_target(self):+ validate_lock(LOCK)++ def test_same_kernel_and_partial_headers_are_rejected(self):+ for mutation in ('kernel', 'headers'):+ with self.subTest(mutation=mutation):+ lock = copy.deepcopy(LOCK)+ if mutation == 'kernel':+ lock['candidate']['kernel'] = lock['baseline']['kernel']+ else:+ lock['candidate']['packages']['linux-lts-headers']['version'] = lock['baseline']['packages']['linux-lts-headers']+ with self.assertRaises(AssertionError):+ validate_lock(lock)++ def test_mixed_dates_or_live_mirror_are_rejected(self):+ for url in ('https://archive.archlinux.org/repos/2026/10/03/extra/os/x86_64/extra.db',+ 'https://mirror.example/extra/os/x86_64/extra.db'):+ lock = copy.deepcopy(LOCK)+ lock['candidate']['repositories']['extra']['url'] = url+ with self.assertRaises(AssertionError):+ validate_lock(lock)+++class ArtifactTests(unittest.TestCase):+ def test_exact_manifest_source_and_image_bytes_required(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ iso = root / 'fixture.iso'+ iso.write_bytes(b'original immutable image')+ lock = copy.deepcopy(LOCK)+ old = lock['baseline']+ old['iso'] = dict(name=iso.name, bytes=iso.stat().st_size, sha256=hashlib.sha256(iso.read_bytes()).hexdigest())+ manifest = {'source_commit': old['source_commit'], 'iso': old['iso'],+ 'arch_snapshot': old['snapshot'], 'package_version': old['packages']['harness-os'],+ 'harness_inputs': {'files': old['runtime_files'], 'source_commit': old['source_commit']},+ 'capabilities': ['broadcom-offline', 'nvidia-offline']}+ path = root / 'manifest.json'+ path.write_text(json.dumps(manifest))+ old['manifest_sha256'] = hashlib.sha256(path.read_bytes()).hexdigest()+ self.assertEqual(verify_image(iso, lock), manifest)+ iso.write_bytes(b'changed! immutable image')+ with self.assertRaises(AssertionError):+ verify_image(iso, lock)+ iso.write_bytes(b'original immutable image')+ manifest['source_commit'] = '0' * 40+ path.write_text(json.dumps(manifest))+ with self.assertRaises(AssertionError):+ verify_image(iso, lock)++ def test_archive_database_preserves_signature_and_epoch(self):+ with tempfile.TemporaryDirectory() as temp:+ path = Path(temp) / 'extra.db'+ data = b'%NAME%\nnvidia-open-lts\n\n%VERSION%\n1:615.71.09-7\n\n%PGPSIG%\nYWN0dWFsLXNpZ25hdHVyZQ==\n\n'+ with tarfile.open(path, 'w:gz') as archive:+ info = tarfile.TarInfo('nvidia-open-lts-615.71.09-7/desc')+ info.size = len(data)+ archive.addfile(info, io.BytesIO(data))+ parsed = database(path)['nvidia-open-lts']+ self.assertEqual(parsed['VERSION'], ['1:615.71.09-7'])+ self.assertEqual(parsed['PGPSIG'], ['YWN0dWFsLXNpZ25hdHVyZQ=='])+++class ShutdownTests(unittest.TestCase):+ # Real owned subprocess/sockets exercise serial and buffered QMP independently,+ # including quiet guests, stale events and failure to exit. This does not boot+ # a VM or turn simulated transport evidence into native kernel acceptance.+ CHILD = r'''+import json, os, re, signal, socket, sys+channel = socket.socket(fileno=int(sys.argv[1]))+qmp = socket.socket(fileno=int(sys.argv[2]))+mode = sys.argv[3]+powerdown = b'[ 12.34] reboot: Power down\r\n'+shutdown = {'event': 'SHUTDOWN', 'data': {'guest': True, 'reason': 'guest-shutdown'},+ 'timestamp': {'seconds': 1234, 'microseconds': 5678}}+def encode(row):+ return (json.dumps(row) + '\r\n').encode()+if mode == 'stale-buffer':+ channel.sendall(powerdown)+barrier = json.loads(qmp.makefile('rb').readline())+assert barrier['execute'] == 'query-status'+response = {'return': {'running': True, 'singlestep': False, 'status': 'running'}, 'id': barrier['id']}+if mode == 'barrier-failure':+ response = {'error': {'class': 'GenericError', 'desc': 'query failed'}, 'id': barrier['id']}+# One write exercises events buffered alongside the correlated response.+qmp.sendall((encode(shutdown) if mode == 'stale-event' else b'') + encode(response))+request = b''+while b'\n' not in request:+ chunk = channel.recv(65536)+ if not chunk:+ sys.exit(0)+ request += chunk+marker = re.search(rb'HN_POWEROFF_[0-9a-f]+', request).group()+if mode == 'unrelated-exception' or mode == 'serial-timeout':+ signal.pause()+if mode in ('ack', 'command-failure'):+ status = b'7' if mode == 'command-failure' else b'0'+ channel.sendall(b'\r\n' + marker + b':' + status + b'\r\n')+if mode not in ('quiet-guest', 'no-proof', 'stale-log', 'stale-buffer', 'stale-event'):+ channel.sendall(powerdown)+channel.close()+if mode == 'qmp-timeout':+ signal.pause()+if mode.startswith('cause-'):+ reason = mode.removeprefix('cause-')+ shutdown['data'] = {'guest': reason.startswith('guest-'), 'reason': reason}+if mode == 'guest-string':+ shutdown['data']['guest'] = 'true'+if mode not in ('no-proof', 'stale-log', 'stale-buffer', 'stale-event', 'kernel-only'):+ qmp.sendall(encode(shutdown))+ if mode == 'duplicate-event':+ qmp.sendall(encode(shutdown))+qmp.close()+if mode == 'exit-timeout':+ signal.pause()+sys.exit(9 if mode == 'nonzero' else 0)+'''++ def exercise(self, mode, expected=None):+ with tempfile.TemporaryDirectory() as directory:+ folder = Path(directory)+ host, guest = socket.socketpair()+ qmp_host, qmp_guest = socket.socketpair()+ qmp_file = qmp_host.makefile('rb')+ process = subprocess.Popen([sys.executable, '-c', self.CHILD, str(guest.fileno()), str(qmp_guest.fileno()), mode],+ pass_fds=(guest.fileno(), qmp_guest.fileno()), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ guest.close()+ qmp_guest.close()+ log = (folder / 'serial.log').open('ab', buffering=0)+ if mode == 'stale-log':+ log.write(b'[ 1.0] reboot: Power down\n')+ if mode == 'stale-buffer':+ self.assertTrue(select.select([host], [], [], 5)[0], 'Child did not prepare stale bytes')+ stopped = []++ def send(command):+ if mode == 'unrelated-exception':+ raise ValueError('unrelated transport error')+ host.sendall(command.encode())+ if mode == 'buffered-exit':+ process.wait(timeout=5)++ vm = SimpleNamespace(folder=folder, boot_count=2, process=process, serial=host, log=log,+ qmp=qmp_host, qmp_file=qmp_file, send=send, stop=lambda: stopped.append(process.poll()))+ try:+ if expected:+ with self.assertRaises(expected):+ graceful_stop(vm, True, timeout=.5)+ else:+ event = graceful_stop(vm, True, timeout=5)+ self.assertEqual(event['status'], 'passed')+ self.assertTrue(event['serial_eof'])+ self.assertEqual(event['guest_power_down'], mode != 'quiet-guest')+ self.assertEqual(event['guest_shutdown'], {'guest': True, 'reason': 'guest-shutdown'})+ self.assertEqual(event['qmp_after_request'][0]['timestamp'], {'seconds': 1234, 'microseconds': 5678})+ self.assertEqual(event['qemu_exit_status'], 0)+ self.assertEqual(event['command_status'], 0 if mode == 'ack' else None)+ recorded = json.loads((folder / 'shutdown-events.jsonl').read_text())+ self.assertEqual(recorded['qemu_pid'], process.pid)+ self.assertEqual(recorded['status'], 'failed' if expected else 'passed')+ self.assertEqual(stopped, [] if expected else [0], 'Forced cleanup must not establish graceful shutdown')+ if mode == 'stale-event':+ self.assertEqual(recorded['qmp_before_request'][0]['event'], 'SHUTDOWN')+ self.assertEqual(recorded['qmp_after_request'], [])+ finally:+ if process.poll() is None:+ process.terminate()+ process.wait(timeout=5)+ process.stderr.close()+ host.close()+ qmp_file.close()+ qmp_host.close()+ log.close()++ def test_real_exit_after_ack_or_early_serial_disconnect(self):+ for mode in ('ack', 'early-disconnect', 'quiet-guest', 'buffered-exit'):+ with self.subTest(mode=mode):+ self.exercise(mode)++ def test_missing_fresh_guest_proof_or_nonzero_exit_fails(self):+ for mode in ('no-proof', 'stale-log', 'stale-buffer', 'stale-event', 'kernel-only', 'nonzero', 'command-failure'):+ with self.subTest(mode=mode):+ self.exercise(mode, AssertionError)++ def test_unrelated_errors_and_transport_or_exit_timeouts_fail(self):+ for mode, error in [('unrelated-exception', ValueError), ('serial-timeout', TimeoutError),+ ('qmp-timeout', TimeoutError),+ ('exit-timeout', subprocess.TimeoutExpired)]:+ with self.subTest(mode=mode):+ self.exercise(mode, error)++ def test_host_exit_reboot_panic_and_ambiguous_events_fail(self):+ for mode in ('cause-host-qmp-quit', 'cause-host-signal', 'cause-guest-reset',+ 'cause-guest-panic', 'duplicate-event', 'guest-string', 'barrier-failure'):+ with self.subTest(mode=mode):+ self.exercise(mode, AssertionError)+++class AutomaticHooksTests(unittest.TestCase):+ def test_module_alias_resolution_is_strict_and_kernel_scoped(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ kernel = LOCK['baseline']['kernel']+ modules = root / 'usr/lib/modules'+ installed = modules / kernel / 'extramodules/wl.ko'+ installed.parent.mkdir(parents=True)+ installed.write_bytes(b'actual module payload')+ (root / 'lib').symlink_to('usr/lib', target_is_directory=True)+ raw = root / 'lib/modules' / kernel / 'extramodules/wl.ko'+ row = module_identity(raw, kernel, modules)+ self.assertEqual(row['path'], str(raw))+ self.assertEqual(row['resolved_path'], str(installed.resolve()))+ self.assertEqual(row['module_root'], str((modules / kernel).resolve()))+ self.assertEqual(row['sha256'], hashlib.sha256(installed.read_bytes()).hexdigest())+ for other in (LOCK['candidate']['kernel'], kernel + '-other'):+ outside = modules / other / 'wl.ko'+ outside.parent.mkdir()+ outside.write_bytes(installed.read_bytes())+ with self.assertRaisesRegex(AssertionError, 'escapes expected kernel'):+ module_identity(outside, kernel, modules)+ alias = installed.with_name('escaped.ko')+ alias.symlink_to(outside)+ with self.assertRaisesRegex(AssertionError, 'escapes expected kernel'):+ module_identity(alias, kernel, modules)+ alias.unlink()+ with self.assertRaisesRegex(AssertionError, 'Not a regular module'):+ module_identity(installed.parent, kernel, modules)+ with self.assertRaises(FileNotFoundError):+ module_identity(installed.with_name('missing.ko'), kernel, modules)++ def test_pre_reboot_uname_stays_old_but_new_modules_are_checked(self):+ row = probe(True)+ row['running_kernel'] = LOCK['baseline']['kernel']+ validate_probe(row, LOCK, True, LOCK['baseline']['kernel'])+ with self.assertRaises(AssertionError):+ validate_probe(row, LOCK, True, LOCK['candidate']['kernel'])++ def test_missing_dkms_rebuild_wrong_abi_and_nvidia_fallback_fail(self):+ mutations = [lambda p: p.update(dkms=''),+ lambda p: p['modules']['wl'].update(vermagic=LOCK['baseline']['kernel'] + ' SMP'),+ lambda p: p['modules']['nvidia_uvm'].update(vermagic=LOCK['baseline']['kernel'] + ' SMP'),+ lambda p: p['modules']['nvidia'].update(owner='nvidia-open-dkms'),+ lambda p: p['modules']['nvidia_modeset'].update(version='previous-version'),+ lambda p: p['modules']['wl'].update(resolved_path='/tmp/usr/lib/modules/' + LOCK['candidate']['kernel'] + '/wl.ko'),+ lambda p: p['modules']['wl'].update(resolved_path='/usr/lib/modules/' + LOCK['baseline']['kernel'] + '/wl.ko'),+ lambda p: p.update(headers_kernel=LOCK['baseline']['kernel']),+ lambda p: p.update(package_kernel_sha256='stale-boot-kernel')]+ for mutation in mutations:+ with self.subTest(mutation=mutation):+ row = probe(True)+ mutation(row)+ with self.assertRaises(AssertionError):+ validate_probe(row, LOCK, True, LOCK['candidate']['kernel'])++ def test_initramfs_needs_new_namespace_early_gpu_and_gsp_not_wl(self):+ kernel = LOCK['candidate']['kernel']+ firmware = ['nvidia/615.71.09/gsp_ga10x.bin', 'nvidia/615.71.09/gsp_tu10x.bin']+ lines = [f'usr/lib/modules/{kernel}/kernel/drivers/video/{name}.ko.zst' for name in EARLY]+ lines += ['usr/lib/firmware/' + name + '.zst' for name in firmware]+ listing = '\n'.join(lines)+ self.assertEqual(initramfs_identity(listing, kernel, firmware)['kernel_namespaces'], [kernel])+ for invalid in (listing.replace(kernel, LOCK['baseline']['kernel']), '\n'.join(lines[1:]),+ '\n'.join(lines[:-1]), listing + '\nusr/lib/modules/another/kernel/stale.ko'):+ with self.subTest(invalid=invalid), self.assertRaises(AssertionError):+ initramfs_identity(invalid, kernel, firmware)++ def test_changed_package_labels_do_not_substitute_for_changed_kernel_bytes(self):+ old, new = probe(), probe(True)+ validate_transition(old, new)+ new['boot']['vmlinuz-linux-lts'] = old['boot']['vmlinuz-linux-lts']+ with self.assertRaises(AssertionError):+ validate_transition(old, new)++ def test_correct_initramfs_names_with_stale_module_or_gsp_bytes_fail(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ installed, extracted = root / 'installed', root / 'initrd'+ firmware = 'nvidia/615.71.09/gsp_tu10x.bin'+ identity = {'early_modules': {}, 'firmware': [firmware]}+ modules = {}+ for name in EARLY:+ relative = 'usr/lib/modules/new/kernel/' + name + '.ko'+ archived = extracted / relative+ archived.parent.mkdir(parents=True, exist_ok=True)+ archived.write_bytes(('module payload ' + name).encode())+ source = installed / (name + '.ko.gz')+ source.parent.mkdir(parents=True, exist_ok=True)+ with gzip.open(source, 'wb') as handle:+ handle.write(archived.read_bytes())+ modules[name] = {'path': str(source)}+ identity['early_modules'][name] = relative+ original = installed / 'firmware' / firmware+ original.parent.mkdir(parents=True)+ original.write_bytes(b'signed GSP payload')+ archived = extracted / 'usr/lib/firmware' / firmware+ archived.parent.mkdir(parents=True)+ archived.write_bytes(original.read_bytes())+ result = payload_identity({'main': extracted}, identity, modules, installed / 'firmware')+ self.assertEqual(set(result), set(EARLY) | {firmware})+ for bad in (extracted / identity['early_modules']['nvidia'], archived):+ good = bad.read_bytes()+ bad.write_bytes(b'stale or corrupt payload under the correct filename')+ with self.assertRaisesRegex(AssertionError, 'different payload bytes'):+ payload_identity({'main': extracted}, identity, modules, installed / 'firmware')+ bad.write_bytes(good)++ def test_compressed_payload_keeps_its_path_in_early_archive(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ segments = {name: root / name for name in ('early', 'main')}+ kernel = LOCK['baseline']['kernel']+ modules, listings = {}, {'early': [], 'main': []}+ for index, name in enumerate(EARLY):+ segment = 'early' if index == 0 else 'main'+ relative = f'usr/lib/modules/{kernel}/extramodules/{name}.ko' + ('.gz' if segment == 'early' else '')+ archived = segments[segment] / relative+ archived.parent.mkdir(parents=True, exist_ok=True)+ opener = gzip.open if segment == 'early' else open+ with opener(archived, 'wb') as handle:+ handle.write(('module ' + name).encode())+ source = root / ('installed-' + name + '.ko')+ source.write_bytes(('module ' + name).encode())+ modules[name] = {'path': str(source)}+ listings[segment].append(relative)+ firmware = 'nvidia/615.71.09/gsp_tu10x.bin'+ original = root / 'firmware' / firmware+ original.parent.mkdir(parents=True)+ original.write_bytes(b'GSP bytes')+ archived = segments['early'] / 'usr/lib/firmware' / (firmware + '.gz')+ archived.parent.mkdir(parents=True)+ with gzip.open(archived, 'wb') as handle:+ handle.write(original.read_bytes())+ listings['early'].append(str(archived.relative_to(segments['early'])))+ identity = initramfs_identity('\n'.join(listings['early'] + listings['main']), kernel, [firmware])+ # Reproduce attempt 1: the unchanged compressed filename is listed,+ # but selecting only the main archive cannot find its payload.+ with self.assertRaisesRegex(AssertionError, 'Missing or ambiguous archived module'):+ payload_identity({'main': segments['main']}, identity, modules, root / 'firmware')+ result = payload_identity(segments, identity, modules, root / 'firmware')+ self.assertEqual(result['nvidia']['segment'], 'early')+ self.assertEqual(result['nvidia_drm']['segment'], 'main')+ self.assertEqual(result[firmware]['segment'], 'early')+ for name, relative in [('nvidia', identity['early_modules']['nvidia']),+ (firmware, 'usr/lib/firmware/' + firmware + '.gz')]:+ duplicate = segments['main'] / relative+ duplicate.parent.mkdir(parents=True, exist_ok=True)+ duplicate.write_bytes((segments['early'] / relative).read_bytes())+ with self.assertRaisesRegex(AssertionError, 'ambiguous archived'):+ payload_identity(segments, identity, modules, root / 'firmware')+ with self.assertRaises(AssertionError):+ initramfs_identity('\n'.join(listings['early'] + listings['main'] + [relative]), kernel, [firmware])+ duplicate.unlink()++ def test_runtime_must_stay_frozen_while_distro_packages_may_change(self):+ old, new = probe(), probe(True)+ old['packages']['nodejs'], new['packages']['nodejs'] = '22.1-1', '22.2-1'+ validate_transition(old, new)+ new['runtime']['runtime_json_sha256'] = 'changed-runtime'+ with self.assertRaises(AssertionError):+ validate_transition(old, new)+++class RecoveryTests(unittest.TestCase):+ def test_full_root_boot_and_later_project_edit_must_agree(self):+ old, restored = probe(), probe()+ transaction = {'checkpoint': {'boot_sha256': old['boot']}}+ project = {'keep.txt': {'sha256': 'edited-after-checkpoint', 'uid': 1000, 'gid': 1000, 'mtime_ns': 42},+ 'new.txt': {'sha256': 'new-after-checkpoint', 'uid': 1000, 'gid': 1000, 'mtime_ns': 43}}+ validate_recovery(old, restored, transaction, project, copy.deepcopy(project))+ for mutation in (lambda r: r['packages'].update({'linux-lts-headers': 'wrong'}),+ lambda r: r['boot'].update({'grub/grub.cfg': 'changed'}),+ lambda r: r['modules']['wl'].update(sha256='newer-module'),+ lambda r: r.update(running_kernel=LOCK['candidate']['kernel']),+ lambda r: r.update(pacman_config='new snapshot')):+ row = copy.deepcopy(restored)+ mutation(row)+ with self.assertRaises(AssertionError):+ validate_recovery(old, row, transaction, project, project)+ for changed in ({'keep.txt': project['keep.txt']},+ {**project, 'keep.txt': {'sha256': 'old-before-checkpoint', 'uid': 1000, 'gid': 1000, 'mtime_ns': 1}}):+ with self.assertRaises(AssertionError):+ validate_recovery(old, restored, transaction, project, changed)+++if __name__ == '__main__':+ unittest.main()