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
Improve compressed swap capacity for constrained OS browser sessions (#809)
Dee49e95ab6a698
diff --git a/.github/workflows/os.yml b/.github/workflows/os.ymlindex 3bfc4e22e..8a3564e6b 100644--- a/.github/workflows/os.yml+++ b/.github/workflows/os.yml@@ -47,11 +47,16 @@ on:default: falsetype: booleanchecks:- description: 'Image journey, browser focus, lock/suspend, compositor recovery, Wi-Fi/audio, or hardware; image_run_id reuses an image'+ description: 'Image journey, browser focus, lock/suspend, recovery, Wi-Fi/audio, hardware, or private zram acceptance'required: falsedefault: imagetype: choice- options: [image, browser, session, recovery, essentials, hardware]+ options: [image, browser, session, recovery, essentials, hardware, zram]+ browser_memory:+ description: 'With checks=browser, diagnose memory in the UEFI VM only; retain ordinary workload and deadlines'+ required: false+ default: false+ type: booleanpush:branches: ['os/**']paths: ['os/**', 'tui/**', 'cli/**', '.github/workflows/os.yml']@@ -66,7 +71,7 @@ concurrency:jobs:image:- if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update }}+ if: ${{ !inputs.image_run_id && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'zram' }}runs-on: ubuntu-24.04timeout-minutes: 50steps:@@ -154,21 +159,13 @@ jobs:machine:needs: image- if: ${{ always() && !inputs.publish_run_id && !inputs.development_update && inputs.checks != 'essentials' && inputs.checks != 'hardware' && (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' && (needs.image.result == 'success' || inputs.image_run_id != '') && !cancelled() }}runs-on: ubuntu-24.04timeout-minutes: 65strategy:fail-fast: falsematrix:- include:- - firmware: bios- encryption: ''- agents: '--agents'- cpu: '--cpu Nehalem'- - firmware: uefi- encryption: '--encrypt'- agents: ''- cpu: ''+ include: ${{ inputs.checks == 'browser' && inputs.browser_memory && fromJSON('[{"firmware":"uefi","encryption":"--encrypt","agents":"","cpu":""}]') || fromJSON('[{"firmware":"bios","encryption":"","agents":"--agents","cpu":"--cpu Nehalem"},{"firmware":"uefi","encryption":"--encrypt","agents":"","cpu":""}]') }}steps:- uses: actions/checkout@v7- uses: actions/download-artifact@v6@@ -223,7 +220,7 @@ jobs:if: ${{ inputs.checks == 'browser' }}env:OS_MEMORY_MIB: ${{ inputs.memory_mib || '2048' }}- run: python3 os/tests/browser_vm.py --iso os/dist/*.iso --firmware '${{ matrix.firmware }}' --memory-mib "$OS_MEMORY_MIB" --wlrctl /usr/bin/wlrctl --browser-script os/root/usr/bin/hn-browser --compositor-config os/root/usr/share/harness-os/labwc/rc.xml+ run: python3 os/tests/browser_vm.py --iso os/dist/*.iso --firmware '${{ matrix.firmware }}' --memory-mib "$OS_MEMORY_MIB" --wlrctl /usr/bin/wlrctl --browser-script os/root/usr/bin/hn-browser --compositor-config os/root/usr/share/harness-os/labwc/rc.xml ${{ inputs.browser_memory && '--memory-profile --zram-config os/root/etc/systemd/zram-generator.conf' || '' }}- name: Show machine failure diagnosticsif: failure()run: |@@ -243,6 +240,54 @@ jobs:os/test-results/**/dsh/**retention-days: 14+ zram:+ if: ${{ inputs.checks == 'zram' && !inputs.publish_run_id && !inputs.development_update }}+ runs-on: ubuntu-24.04+ timeout-minutes: 40+ steps:+ - uses: actions/checkout@v7+ - name: Require a selected source image+ env:+ IMAGE_RUN_ID: ${{ inputs.image_run_id }}+ run: '[[ "$IMAGE_RUN_ID" =~ ^[0-9]+$ ]]'+ - 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: Install private fixture and VM tools+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y --no-install-recommends squashfs-tools xorriso time qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr wlrctl+ test -e /dev/kvm+ sudo chmod a+rw /dev/kvm+ - name: Check one-file fixture and exact capacity contracts+ run: |+ python3 os/tools/check.py+ sudo python3 -m unittest discover -s os/tests -p test_zram.py -v+ go run github.com/rhysd/actionlint/cmd/[email protected] .github/workflows/os.yml+ - name: Cold live boot, interactive install and ordinary browser acceptance+ run: |+ expected_sha="$(python3 -c 'import json; print(json.load(open("os/dist/manifest.json"))["iso"]["sha256"])')"+ sudo python3 os/tests/zram_fixture.py --iso os/dist/*.iso --sha256 "$expected_sha" --config os/root/etc/systemd/zram-generator.conf+ - name: Retain evidence without the private image or disks+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: harness-os-zram-acceptance+ path: |+ os/test-results/zram/*.json+ os/test-results/zram/*.json.gz+ os/test-results/zram/*.log+ os/test-results/zram/*.time+ os/test-results/zram/*/*.json+ os/test-results/zram/*/*.jsonl+ os/test-results/zram/*/*.png+ os/test-results/zram/*/*.txt+ os/test-results/zram/*/*.log+ retention-days: 14+hardware:needs: imageif: ${{ always() && !inputs.publish_run_id && !inputs.development_update && (needs.image.result == 'success' || inputs.checks == 'hardware' && inputs.image_run_id != '') && !cancelled() }}diff --git a/os/root/etc/systemd/zram-generator.conf b/os/root/etc/systemd/zram-generator.confindex 6e8091fa9..6ed84d6bc 100644--- a/os/root/etc/systemd/zram-generator.conf+++ b/os/root/etc/systemd/zram-generator.conf@@ -1,3 +1,3 @@[zram0]-zram-size = min(ram / 2, 4096)+zram-size = min(ram, 4096)compression-algorithm = zstddiff --git a/os/tests/browser_memory.py b/os/tests/browser_memory.pynew file mode 100644index 000000000..a0bff818e--- /dev/null+++ b/os/tests/browser_memory.py@@ -0,0 +1,60 @@+#!/usr/bin/env python3+"""One read-only memory snapshot in the marked disposable browser VM."""+import argparse+import json+import os+from pathlib import Path+import time+++def read(path):+ try:+ return path.read_text(errors='replace')+ except OSError as error:+ return {'error': type(error).__name__, 'errno': error.errno}+++def snapshot(proc=Path('/proc'), sys=Path('/sys')):+ started = time.monotonic()+ result = dict(at=time.time(), observer_pid=os.getpid(), processes=[],+ meminfo=read(proc / 'meminfo'), vmstat=read(proc / 'vmstat'),+ cpu=read(proc / 'stat'), uptime=read(proc / 'uptime'),+ pressure={kind: read(proc / 'pressure' / kind) for kind in ['memory', 'cpu', 'io']},+ swaps=read(proc / 'swaps'), zram={},+ swappiness=read(proc / 'sys/vm/swappiness'),+ zswap={p.name: read(p) for p in (sys / 'module/zswap/parameters').glob('*')})+ for device in (sys / 'block').glob('zram*'):+ result['zram'][device.name] = {name: read(device / name) for name in+ ['disksize', 'mm_stat', 'stat', 'io_stat', 'bd_stat', 'comp_algorithm']}+ for entry in sorted(proc.iterdir(), key=lambda item: item.name):+ if not entry.name.isdecimal():+ continue+ # Preserve the entire rollup, including Pss and SwapPss. RSS alone+ # can make a heavily swapped agent look like a small process.+ row = dict(pid=int(entry.name), comm=read(entry / 'comm'),+ cmdline=read(entry / 'cmdline'), status=read(entry / 'status'),+ stat=read(entry / 'stat'), cgroup=read(entry / 'cgroup'),+ smaps_rollup=read(entry / 'smaps_rollup'))+ if isinstance(row['cmdline'], str):+ row['cmdline'] = row['cmdline'].replace('\0', ' ').rstrip()+ result['processes'].append(row)+ result['duration_seconds'] = time.monotonic() - started+ return result+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--phase', required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ if (os.getuid() != 0 or Path('/etc/harness-live').exists() or+ not Path('/run/harness-browser-memory-disposable').is_file() or+ not Path('/var/lib/harness-os/install.json').is_file()):+ parser.error('Run only as root in the marked disposable installed VM')+ result = snapshot()+ result['phase'] = args.phase+ args.output.write_text(json.dumps(result) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/browser_vm.py b/os/tests/browser_vm.pyindex cdd68bef0..e95fac3c2 100644--- a/os/tests/browser_vm.py+++ b/os/tests/browser_vm.py@@ -10,11 +10,23 @@ import subprocessimport timefrom PIL import Imagefrom footprint_vm import copy_file-from vm import VM+from vm import VM, check_live_media, install_interactivelyfrom session_vm import screen_textclass BrowserVM(VM):+ memory_profile = False++ def memory_snapshot(self, phase):+ if not self.memory_profile:+ return+ started = time.monotonic()+ path = '/tmp/harness-browser-memory-' + phase + '.json'+ self.command('sudo -n timeout 10 python3 /tmp/harness-browser-memory.py --phase ' ++ shlex.quote(phase) + ' --output ' + shlex.quote(path), timeout=15)+ (self.folder / ('memory-' + phase + '.json')).write_bytes(self.read_file(path, timeout=15))+ self.memory_samples.append(dict(phase=phase, host_elapsed_seconds=time.monotonic() - started))+def keys(self, *keys):# Use explicit press/release events. send-key's delayed release follows# the VM clock; a host sleep can finish while the guest is still holding@@ -107,9 +119,52 @@ def page_fills_display(vm, name):time.sleep(.1)+def install_zram_candidate(vm, config, source, result):+ # Change only the private test disk, before its first installed boot. Do+ # not swapoff a running low-memory workspace to apply a startup setting.+ assert config['disk'] == '/dev/vda' and config['expected_serial'] == 'HN_OS_TEST'+ vm.command('test -f /etc/harness-live && test "$(lsblk -dn -o SERIAL /dev/vda)" = HN_OS_TEST')+ data = source.read_bytes()+ copy_file(vm, data, '/tmp/harness-zram-candidate')+ root_device = '/dev/vda3'+ if config['encrypt']:+ vm.command('printf %s ' + shlex.quote(config['password']) ++ ' | cryptsetup open --key-file=- /dev/vda3 hn-browser-candidate')+ root_device = '/dev/mapper/hn-browser-candidate'+ mounted = False+ try:+ vm.command('mkdir -p /mnt/harness-browser-candidate && mount -o subvol=@ ' ++ root_device + ' /mnt/harness-browser-candidate')+ mounted = True+ vm.command('test -f /mnt/harness-browser-candidate/var/lib/harness-os/install.json')+ target = '/etc/systemd/zram-generator.conf'+ base = vm.read_file('/mnt/harness-browser-candidate' + target)+ result['candidates'][target] = dict(source=str(source), sha256=hashlib.sha256(data).hexdigest(),+ original_sha256=hashlib.sha256(base).hexdigest(), changed=data != base)+ vm.command('install -m 644 /tmp/harness-zram-candidate /mnt/harness-browser-candidate' + target)+ vm.command('sync')+ finally:+ if mounted:+ vm.command('umount /mnt/harness-browser-candidate')+ if config['encrypt']:+ vm.command('dmsetup remove --deferred --noudevsync hn-browser-candidate')+++def zram_probe(vm, source, phase, live=False):+ data = Path(__file__).with_name('zram_probe.py').read_bytes()+ copy_file(vm, data, '/tmp/harness-zram-probe.py')+ path = '/tmp/harness-zram-' + phase + '.json'+ vm.command(('' if live else 'sudo -n ') + 'python3 /tmp/harness-zram-probe.py --config-sha256 ' ++ hashlib.sha256(source.read_bytes()).hexdigest() + ' --output ' + path, timeout=15)+ content = vm.read_file(path, timeout=10)+ (vm.folder / ('zram-' + phase + '.json')).write_bytes(content)+ return json.loads(content)++def check_browser(vm, result):vm.command('! pgrep -u "$(id -u)" -x chromium')result['checks'].append('Browser is absent on installed boot')+ vm.memory_snapshot('workspace')vm.command('mkdir -p /tmp/harness-browser-probe')copy_file(vm, TERMINAL.encode(), '/tmp/harness-browser-terminal.py')copy_file(vm, Path(__file__).with_name('browser_guest.py').read_bytes(), '/tmp/harness-browser-page.py')@@ -143,6 +198,7 @@ def check_browser(vm, result):state(vm, path='/first', ready=True)vm.type_probe('browser')state(vm, value='browser')+ vm.memory_snapshot('first-page')result['checks'].append('Super+b cold-starts a maximized browser; its local page fills the display and receives real keyboard input')result['toggles'] = []for index in range(4):@@ -158,6 +214,7 @@ def check_browser(vm, result):page_fills_display(vm, 'toggle-full-display-' + str(index))result['toggles'].append(dict(to_terminal_seconds=to_terminal, to_browser_seconds=to_browser))result['checks'].append('Repeated Super+b switching routes keyboard input only to the intended surface and preserves the terminal process and browser input')+ vm.memory_snapshot('after-toggles')vm.keys('meta_l', 'ret')focused(vm, 'hn', 'explicit-request-terminal')terminal('before-explicit-request')@@ -171,6 +228,7 @@ def check_browser(vm, result):state(vm, path='/second', ready=True)vm.type_probe('window-one')state(vm, path='/second', value='window-one')+ vm.memory_snapshot('second-page')result['checks'].append('An explicit hn-browser URL raises the already running browser from behind Harness')vm.keys('ctrl', 'n')new_tab_ready(vm, 'new-browser-window')@@ -192,6 +250,7 @@ def check_browser(vm, result):vm.type_probe('-returned')state(vm, path='/new-window', value='window-two-returned')state(vm, path='/second', value='window-one')+ vm.memory_snapshot('two-window-return')result['checks'].append('With two browser windows open, Super+b returns to the window the user left and typing leaves the other window unchanged')vm.keys('ctrl', 'shift', 'w')focused(vm, 'chromium', 'original-browser-restored')@@ -209,6 +268,7 @@ def check_browser(vm, result):vm.keys('meta_l', 'b')focused(vm, 'hn', 'browser-final-return')terminal('after-browser-reopen')+ vm.memory_snapshot('reopened')result['checks'].append('New browser windows maximize; close and reopen restores working keyboard focus without losing the terminal')@@ -220,25 +280,43 @@ def main():parser.add_argument('--wlrctl', type=Path, required=True)parser.add_argument('--browser-script', type=Path, required=True)parser.add_argument('--compositor-config', type=Path, required=True)+ parser.add_argument('--memory-profile', action='store_true',+ help='Capture finite read-only memory snapshots; separate from ordinary focus acceptance')+ parser.add_argument('--zram-config', type=Path,+ help='Overlay this startup configuration on the private installed disk before boot')+ parser.add_argument('--expected-zram-config', type=Path,+ help='Require this configuration active from the live and installed cold boots; no overlay')+ parser.add_argument('--interactive-install', action='store_true')+ parser.add_argument('--live-transport', choices=['cdrom', 'usb'], default='cdrom')+ parser.add_argument('--output', type=Path)args = parser.parse_args()+ if args.zram_config and args.expected_zram_config:+ parser.error('Choose a preboot overlay or verification of a prepared image, not both')+ if args.expected_zram_config and not args.interactive_install:+ parser.error('--expected-zram-config requires --interactive-install')if not os.access('/dev/kvm', os.R_OK | os.W_OK):parser.error('Native x86 KVM is required')iso = args.iso.resolve()manifest = json.loads(iso.with_name('manifest.json').read_text())with iso.open('rb') as handle:assert hashlib.file_digest(handle, 'sha256').hexdigest() == manifest['iso']['sha256']- folder = Path(f'os/test-results/{args.firmware}-browser').resolve()+ folder = (args.output or Path(f'os/test-results/{args.firmware}-browser')).resolve()folder.mkdir(parents=True, exist_ok=False)- vm = BrowserVM(folder, iso, args.firmware, args.memory_mib, cpu='Nehalem')+ vm = BrowserVM(folder, iso, args.firmware, args.memory_mib, live_transport=args.live_transport, cpu='Nehalem')+ vm.memory_samples = []config = dict(disk='/dev/vda', expected_serial='HN_OS_TEST', confirm_erase='/dev/vda', username='me',hostname='harness', password='test-password-123', encrypt=args.firmware == 'uefi', serial_console=True)result = dict(status='running', started_at=time.time(), checks=[], firmware=args.firmware,image_source_commit=manifest['source_commit'], iso_sha256=manifest['iso']['sha256'],- test_source_commit=subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip(),+ test_source_commit=subprocess.check_output(['git','-c',f'safe.directory={Path.cwd()}',+ 'rev-parse','HEAD'],text=True).strip(),memory_mib=args.memory_mib, candidates={},+ validation_fixture=manifest.get('validation_fixture'), live_transport=args.live_transport,+ memory_profile=args.memory_profile, cpu='Nehalem', display='virtio-vga (2D)',+ memory_samples=vm.memory_samples,observer=dict(sha256=hashlib.sha256(args.wlrctl.read_bytes()).hexdigest(),version=subprocess.check_output([str(args.wlrctl),'--version'],text=True).strip()),- limitations=['Only the two recorded candidate files replace packaged files in the disposable guest.',+ limitations=['Only the recorded candidate files replace packaged files in the disposable guest.','Native virtual display and physical-keyboard events; not a physical laptop or GPU claim.','Observer and screenshot overhead are included in transition timings.'])try:@@ -246,16 +324,43 @@ def main():vm.wait(r'root@[^\r\n]*[#] ', timeout=180)vm.shell_ready = Truevm.command('stty -echo')+ if args.expected_zram_config:+ result['zram_probe_sha256'] = hashlib.sha256(Path(__file__).with_name('zram_probe.py').read_bytes()).hexdigest()+ result['live_zram'] = zram_probe(vm, args.expected_zram_config, 'live', live=True)+ assert result['live_zram']['oom_kills'] == 0+ if args.live_transport == 'usb':+ check_live_media(vm, result, 'media')copy_file(vm, json.dumps(config).encode(), '/tmp/install-config.json')vm.command('nmcli networking off')- output, _ = vm.command('harness install --config /tmp/install-config.json --yes-erase-disk', timeout=360)- (folder / 'install.log').write_text(output)+ if args.interactive_install:+ assert 'install-first' in manifest.get('capabilities', [])+ from install_first import wait_installer_screen+ wait_installer_screen(vm, 'Repeat password', 'live-installer')+ vm.command('! pgrep -x "hn|harness-tui|opencode|chromium"')+ result['interactive_install_seconds'] = install_interactively(vm, config, folder, direct=True)+ result['checks'].append('USB boots the installer; disk selection, encryption, masked passwords and offline installation succeed')+ if config['encrypt']:+ code = ('import json,sys; k=json.load(sys.stdin)["keyslots"]["0"]["kdf"]; '+ 'print(json.dumps({key:k[key] for key in ["type","time","memory","cpus"]}))')+ vm.command('cryptsetup luksDump --dump-json-metadata /dev/vda3 | python3 -c ' ++ shlex.quote(code) + ' > /tmp/hn-zram-argon.json')+ result['argon'] = json.loads(vm.read_file('/tmp/hn-zram-argon.json'))+ else:+ output, _ = vm.command('harness install --config /tmp/install-config.json --yes-erase-disk', timeout=360)+ (folder / 'install.log').write_text(output)+ if args.zram_config:+ install_zram_candidate(vm, config, args.zram_config, result)+ if args.expected_zram_config:+ result['live_installed_zram'] = zram_probe(vm, args.expected_zram_config, 'live-installed', live=True)+ assert result['live_installed_zram']['oom_kills'] == 0, 'Live installation triggered an OOM kill'vm.command('sync')vm.stop()vm.start(live=False)vm.login_installed(config)result['installed_runtime_ready_seconds_including_test_login'] = round(time.monotonic() - vm.started, 3)vm.command('printf %s ' + shlex.quote(config['password']+'\n') + ' | sudo -S -v')+ if args.zram_config:+ result['installed_zram'] = zram_probe(vm, args.zram_config, 'installed')vm.command('systemctl --user stop harness-update.timer harness-update.service')copy_file(vm, args.wlrctl.read_bytes(), '/tmp/harness-wlrctl')vm.command('chmod 700 /tmp/harness-wlrctl')@@ -268,10 +373,37 @@ def main():copy_file(vm, data, '/tmp/browser-candidate')vm.command('sudo install -m ' + mode + ' /tmp/browser-candidate ' + shlex.quote(target))vm.command('systemd-run --user --quiet --wait --pipe --collect labwc --reconfigure')+ if args.memory_profile:+ data = Path(__file__).with_name('browser_memory.py').read_bytes()+ result['memory_observer_sha256'] = hashlib.sha256(data).hexdigest()+ result['limitations'].append('Memory snapshots add recorded observer cost between phases; this is a diagnostic run.')+ copy_file(vm, data, '/tmp/harness-browser-memory.py')+ vm.command('sudo -n touch /run/harness-browser-memory-disposable')+ vm.memory_profile = True+ if args.expected_zram_config:+ result['install_receipt'] = json.loads(vm.read_file('/var/lib/harness-os/install.json'))+ if config['encrypt']:+ argon = result['argon']+ budget = result['install_receipt']['pbkdf_memory_limit_kib']+ assert argon['type'] == 'argon2id' and argon['time'] >= 4+ assert 64 * 1024 <= argon['memory'] <= budget <= 1024 * 1024+ before = result['installed_zram'] = zram_probe(vm, args.expected_zram_config, 'installed')+ assert sum(p['role'] == 'OpenCode' for p in before['identities']) == 2, before+ assert sum(p['role'] == 'Harness daemon' for p in before['identities']) == 1, before+ assert before['oom_kills'] == 0check_browser(vm, result)+ if args.expected_zram_config:+ after = result['completed_zram'] = zram_probe(vm, args.expected_zram_config, 'completed')+ assert after['identities'] == before['identities'], 'Agent or daemon process changed'+ assert after['oom_kills'] == 0, 'The workload triggered an OOM kill'+ result['checks'].append('Original agent and daemon PID/starttime identities survive the ordinary browser workload without OOM')result['status'] = 'passed'except BaseException as error:result.update(status='failed', error=repr(error))+ try:+ vm.memory_snapshot('failure')+ except Exception as diagnostic:+ result['memory_diagnostic_error'] = repr(diagnostic)try:vm.screenshot('failure')output, _ = vm.command(observe(vm, 'toplevel', 'list'), check=False)@@ -286,7 +418,8 @@ def main():if vm.shell_ready:for name in ['events.jsonl', 'state.json', 'states.json', 'terminal-input']:try:- (folder / name).write_bytes(vm.read_file('/tmp/harness-browser-probe/' + name))+ destination = name + '.txt' if name == 'terminal-input' else name+ (folder / destination).write_bytes(vm.read_file('/tmp/harness-browser-probe/' + name))except Exception:passresult['finished_at'] = time.time()diff --git a/os/tests/test_browser_memory.py b/os/tests/test_browser_memory.pynew file mode 100644index 000000000..86c6e5673--- /dev/null+++ b/os/tests/test_browser_memory.py@@ -0,0 +1,39 @@+from pathlib import Path+import tempfile+import unittest++from browser_memory import snapshot+++class BrowserMemory(unittest.TestCase):+ def test_snapshot_preserves_swapped_processes_pressure_and_compression(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ files = {+ 'proc/meminfo': 'MemTotal: 1024 kB\nMemAvailable: 50 kB\nSwapFree: 1 kB\n',+ 'proc/pressure/memory': 'full avg10=42.00 avg60=1.00 avg300=0.10 total=2500000\n',+ 'proc/101/comm': 'opencode\n',+ 'proc/101/cmdline': 'opencode\0serve\0--service\0',+ 'proc/101/status': 'PPid:\t50\nVmRSS:\t3 kB\nVmSwap:\t800 kB\n',+ 'proc/101/smaps_rollup': 'Rss: 3 kB\nPss: 2 kB\nSwap: 800 kB\nSwapPss: 700 kB\n',+ 'sys/block/zram0/mm_stat': '800000 200000 250000 0 260000 0 0 0 0\n',+ 'sys/block/zram0/comp_algorithm': 'lzo [zstd]\n',+ 'sys/module/zswap/parameters/enabled': 'Y\n',+ }+ for name, value in files.items():+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(value)+ result = snapshot(root / 'proc', root / 'sys')+ self.assertEqual(result['processes'][0]['smaps_rollup'], files['proc/101/smaps_rollup'])+ self.assertEqual(result['processes'][0]['cmdline'], 'opencode serve --service')+ self.assertEqual(result['pressure']['memory'], files['proc/pressure/memory'])+ self.assertEqual(result['zram']['zram0']['mm_stat'], files['sys/block/zram0/mm_stat'])+ self.assertEqual(result['zswap']['enabled'], 'Y\n')+ self.assertEqual(result['processes'][0]['cgroup']['error'], 'FileNotFoundError')+ self.assertEqual(result['pressure']['io']['error'], 'FileNotFoundError')+ self.assertEqual({name: (root / name).read_text() for name in files}, files)+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_zram.py b/os/tests/test_zram.pynew file mode 100644index 000000000..50df4b375--- /dev/null+++ b/os/tests/test_zram.py@@ -0,0 +1,133 @@+import copy+import hashlib+import os+from pathlib import Path+import shutil+import sys+import tempfile+import unittest+from unittest.mock import patch++from payload_compression import compare, extract, measured+from zram_fixture import CHECKSUM, PAYLOAD, TARGET, boot_layout, compare_iso, expected_payload, inventory, replace_config+from zram_probe import check_capacity+++class Capacity(unittest.TestCase):+ def test_exact_generated_capacity_uses_whole_mib_and_preserves_four_gib_cap(self):+ for total, mib in [(970648, 947), (2024000, 1976), (8 * 1024 ** 2, 4096)]:+ size = mib * 1024 ** 2+ swaps = 'Filename Type Size Used Priority\n/dev/zram0 partition ' + str(size // 1024 - 4) + ' 1 100\n'+ result = check_capacity(f'MemTotal: {total} kB\nMemAvailable: 100000 kB\n', size, swaps, 4096)+ self.assertEqual(result['expected_disksize_bytes'], size)++ def test_old_capacity_and_additional_swap_are_rejected(self):+ info = 'MemTotal: 970648 kB\n'+ with self.assertRaises(AssertionError):+ check_capacity(info, 496500736, '', 4096)+ with self.assertRaises(AssertionError):+ check_capacity(info, 993001472, 'header\n/dev/zram0 partition 969724 1 100\n/file file 20 0 -2\n', 4096)+++class IsoBoundary(unittest.TestCase):+ def test_boot_entries_ignore_only_relocated_addresses(self):+ report = '''El Torito cat path : /boot/boot.cat+El Torito boot img : 1 BIOS y none 0x0000 0x00 4 200+El Torito img path : 1 /boot/bios.bin+El Torito img opts : 1 boot-info-table+El Torito boot img : 2 UEFI y none 0x0000 0x00 8192 202+El Torito img path : 2 /boot/efi.img+'''+ self.assertEqual(boot_layout(report), boot_layout(report.replace('4 200', '4 999')))+ self.assertNotEqual(boot_layout(report), boot_layout(report.replace('8192 202', '1024 202')))++ def test_only_expected_files_and_documented_boot_address_bytes_can_change(self):+ with tempfile.TemporaryDirectory() as temp:+ original, candidate = Path(temp) / 'old', Path(temp) / 'new'+ original.mkdir(); candidate.mkdir()+ values = {PAYLOAD: b'old-payload', CHECKSUM: b'old-checksum',+ 'boot/bios.bin': b'x' * 128, 'boot/efi.img': b'efi',+ 'boot/boot.cat': b'catalog', 'boot/kernel': b'kernel'}+ before = dict(entries={}, hardlinks=[])+ for name, data in values.items():+ for root in [original, candidate]:+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ before['entries'][name] = dict(sha256=hashlib.sha256(data).hexdigest(), bytes=len(data), mode=0o100644)+ after = copy.deepcopy(before)+ for name in [PAYLOAD, CHECKSUM, 'boot/boot.cat']:+ after['entries'][name]['sha256'] = 'changed'+ data = bytearray(values['boot/bios.bin']); data[12] = 0+ (candidate / 'boot/bios.bin').write_bytes(data)+ after['entries']['boot/bios.bin']['sha256'] = hashlib.sha256(data).hexdigest()+ layout = dict(paths={'1': 'boot/bios.bin', '2': 'boot/efi.img'},+ options={'1': ['boot-info-table']}, catalog='boot/boot.cat')+ self.assertTrue(compare_iso(before, after, original, candidate, layout)['all_other_paths_content_and_metadata_identical'])+ after['entries']['boot/kernel']['sha256'] = 'unexpected'+ with self.assertRaisesRegex(AssertionError, 'Unexpected ISO changes'):+ compare_iso(before, after, original, candidate, layout)+ after['entries']['boot/kernel'] = before['entries']['boot/kernel']+ data[80] = 0; (candidate / 'boot/bios.bin').write_bytes(data)+ with self.assertRaisesRegex(AssertionError, 'outside its replay address'):+ compare_iso(before, after, original, candidate, layout)++ def test_hidden_efi_partition_preserves_actual_bytes_across_relocation(self):+ # Exact hidden-image report fields from the retained preview 14 failure.+ report = '''El Torito cat path : /boot/syslinux/boot.cat+El Torito boot img : 1 BIOS y none 0x0000 0x00 4 115+El Torito boot img : 2 UEFI y none 0x0000 0x00 0 937480+El Torito img path : 1 /boot/syslinux/isolinux.bin+El Torito img opts : 1 boot-info-table isohybrid-suitable+El Torito img blks : 2 42496+'''+ with patch('zram_fixture.boot_image_digest', return_value='efi-digest') as read:+ layout = boot_layout(report, Path('preview14.iso'))+ read.assert_called_once_with(Path('preview14.iso'), 937480, 42496)+ self.assertEqual(layout['hidden_images']['2'], dict(blocks=42496, sha256='efi-digest'))+ with tempfile.TemporaryDirectory() as temp:+ original, relocated = Path(temp) / 'old.iso', Path(temp) / 'new.iso'+ original.write_bytes(b'\0' * 3 * 2048 + b'e' * 2 * 2048)+ relocated.write_bytes(b'\0' * 5 * 2048 + b'e' * 2 * 2048)+ small = report.replace('937480', '3').replace('42496', '2')+ moved = small.replace(' 3\n', ' 5\n')+ expected = boot_layout(small, original)+ self.assertEqual(expected, boot_layout(moved, relocated))+ with relocated.open('r+b') as handle:+ handle.seek(5 * 2048 + 12); handle.write(b'x')+ self.assertNotEqual(expected, boot_layout(moved, relocated))+ with self.assertRaises(AssertionError):+ boot_layout(moved.replace(' 2 2\n', ' 2 3\n'), relocated)++[email protected](sys.platform == 'linux' and os.geteuid() == 0 and+ all(shutil.which(t) for t in ['mksquashfs', 'unsquashfs']),+ 'Native Linux root/SquashFS fixture runs in the acceptance workflow')+class PayloadBoundary(unittest.TestCase):+ def test_one_file_roundtrip_preserves_metadata_links_and_unrelated_content(self):+ with tempfile.TemporaryDirectory() as temp:+ work = Path(temp); root = work / 'root'; target = root / TARGET+ target.parent.mkdir(parents=True)+ target.write_text('[zram0]\nzram-size = min(ram / 2, 4096)\n')+ target.chmod(0o640); os.utime(target, (123456, 123456))+ os.setxattr(target, 'user.harness-test', b'preserved')+ unrelated = root / 'other'; unrelated.write_bytes(b'runtime bytes unchanged')+ os.chown(unrelated, 1000, 1000); unrelated.chmod(0o4755)+ os.link(unrelated, root / 'hardlink'); (root / 'symlink').symlink_to('other')+ os.link(root / 'symlink', root / 'symlink-link', follow_symlinks=False)+ os.mkfifo(root / 'fifo'); os.link(root / 'fifo', root / 'fifo-link')+ before = inventory(root); data = b'[zram0]\nzram-size = min(ram, 4096)\n'+ self.assertIn(['symlink', 'symlink-link'], before['hardlinks'])+ self.assertIn(['fifo', 'fifo-link'], before['hardlinks'])+ expected = expected_payload(before, data)+ replace_config(root, data)+ self.assertIsNone(compare(expected, inventory(root)))+ image = work / 'candidate.sfs'+ measured(['mksquashfs', root, image, '-noappend', '-no-progress', '-comp', 'zstd',+ '-processors', '2', '-mem', '64M'], work, 'compress', timeout=30)+ extract(image, work / 'extracted', work, 'extract')+ self.assertIsNone(compare(expected, inventory(work / 'extracted')))+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/zram_fixture.py b/os/tests/zram_fixture.pynew file mode 100644index 000000000..5adf930fc--- /dev/null+++ b/os/tests/zram_fixture.py@@ -0,0 +1,238 @@+#!/usr/bin/env python3+"""Private one-file ISO derivative and bounded normal-use zram acceptance."""+import argparse+import copy+import gzip+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import stat+import subprocess+import sys+import tempfile+import time++from payload_compression import canonical, compare, digest, extract, inventory as payload_inventory, measured, repack, tool_versions++TARGET = 'etc/systemd/zram-generator.conf'+PAYLOAD = 'arch/x86_64/airootfs.sfs'+CHECKSUM = 'arch/x86_64/airootfs.sha512'+++def inventory(root):+ result = payload_inventory(root)+ groups = {}+ for name in result['entries']:+ info = (root / name).lstat()+ if not stat.S_ISDIR(info.st_mode):+ groups.setdefault((info.st_dev, info.st_ino), []).append(name)+ result['hardlinks'] = sorted(sorted(group) for group in groups.values() if len(group) > 1)+ return result+++def replace_config(root, candidate):+ path = root / TARGET+ info = path.lstat()+ assert stat.S_ISREG(info.st_mode) and info.st_nlink == 1, 'The configuration must be an ordinary unique file'+ path.write_bytes(candidate)+ os.utime(path, ns=(info.st_atime_ns, info.st_mtime_ns))+++def expected_payload(before, data):+ expected = copy.deepcopy(before)+ expected['entries'][TARGET].update(bytes=len(data), sha256=hashlib.sha256(data).hexdigest())+ return expected+++def boot_image_digest(iso, lba, blocks):+ offset, remaining = lba * 2048, blocks * 2048+ assert lba >= 0 and blocks > 0 and offset + remaining <= iso.stat().st_size+ digest = hashlib.sha256()+ with iso.open('rb') as handle:+ handle.seek(offset)+ while remaining:+ data = handle.read(min(1024 ** 2, remaining))+ assert data, 'Truncated hidden boot image'+ digest.update(data)+ remaining -= len(data)+ return digest.hexdigest()+++def boot_layout(report, iso=None):+ entries, paths, options, addresses, blocks = {}, {}, {}, {}, {}+ catalog = None+ for line in report.splitlines():+ if match := re.match(r'El Torito boot img\s*:\s+(\d+)\s+(.*)', line):+ # LBA changes when the ISO is written again; every other boot+ # entry property (platform, emulation, load segment/size) must not.+ values = match[2].split()+ entries[match[1]], addresses[match[1]] = values[:-1], int(values[-1])+ elif match := re.match(r'El Torito img path\s*:\s+(\d+)\s+(.*)', line):+ paths[match[1]] = match[2].strip().lstrip('/')+ elif match := re.match(r'El Torito img opts\s*:\s+(\d+)\s+(.*)', line):+ options[match[1]] = match[2].split()+ elif match := re.match(r'El Torito img blks\s*:\s+(\d+)\s+(\d+)', line):+ blocks[match[1]] = int(match[2])+ elif match := re.match(r'El Torito cat path\s*:\s+(.*)', line):+ catalog = match[1].strip().lstrip('/')+ assert any('BIOS' in row for row in entries.values()), entries+ assert any('UEFI' in row for row in entries.values()), entries+ hidden = entries.keys() - paths.keys()+ assert paths.keys() <= entries.keys() and hidden <= blocks.keys() and catalog+ assert not hidden or iso is not None, 'The ISO is required to verify hidden boot image bytes'+ hidden_images = {index: dict(blocks=blocks[index], sha256=boot_image_digest(iso, addresses[index], blocks[index]))+ for index in sorted(hidden)}+ return dict(entries=entries, paths=paths, options=options, catalog=catalog, hidden_images=hidden_images)+++def compare_iso(before, after, old_root, new_root, layout):+ assert before['entries'].keys() == after['entries'].keys(), 'ISO paths changed'+ assert before['hardlinks'] == after['hardlinks'], 'ISO hardlinks changed'+ changed = [name for name in before['entries'] if before['entries'][name] != after['entries'][name]]+ patches = {}+ for index, path in layout['paths'].items():+ options = layout['options'].get(index, [])+ ranges = []+ if 'boot-info-table' in options:+ ranges.append((8, 64))+ if 'grub2-boot-info' in options:+ ranges.append((2548, 2556))+ if ranges:+ patches[path] = ranges+ permitted = {PAYLOAD, CHECKSUM, layout['catalog'], *patches}+ assert set(changed) <= permitted, 'Unexpected ISO changes: ' + repr(sorted(set(changed) - permitted))+ assert {PAYLOAD, CHECKSUM} <= set(changed)+ for path in set(changed) & patches.keys():+ old, new = bytearray((old_root / path).read_bytes()), bytearray((new_root / path).read_bytes())+ assert len(old) == len(new)+ # xorriso's documented boot replay may patch only these address fields:+ # https://www.gnu.org/software/xorriso/man_1_xorriso.html+ for start, end in patches[path]:+ old[start:end] = new[start:end] = b'\0' * (end - start)+ assert old == new, 'Boot program changed outside its replay address fields: ' + path+ meta_before = {k: v for k, v in before['entries'][path].items() if k != 'sha256'}+ meta_after = {k: v for k, v in after['entries'][path].items() if k != 'sha256'}+ assert meta_before == meta_after, 'Boot program metadata changed: ' + path+ return dict(changed_paths=sorted(changed), permitted_replay_address_fields=patches,+ all_other_paths_content_and_metadata_identical=True)+++def prepare(iso, manifest, candidate, folder, source):+ result = dict(status='running', base_iso=manifest['iso'], image_source_commit=manifest['source_commit'],+ fixture_source_commit=source, candidate_sha256=digest(candidate), tools=tool_versions())+ path = folder / 'fixture-receipt.json'+ try:+ with tempfile.TemporaryDirectory(prefix='one-file-', dir=folder) as temp:+ work = Path(temp)+ old_iso = work / 'original-iso'+ measured(['xorriso', '-no_rc', '-osirrox', 'on', '-hardlinks', 'on', '-xattr', 'on',+ '-indev', iso, '-extract', '/', old_iso], folder, 'iso-extract-original')+ original_inventory = inventory(old_iso)+ measured(['xorriso', '-no_rc', '-indev', iso, '-report_el_torito', 'plain',+ '-report_system_area', 'plain'], folder, 'iso-original-boot-layout')+ original_layout = boot_layout((folder / 'iso-original-boot-layout.log').read_text(), iso)+ root = work / 'root'+ result['original_payload_sha256'] = digest(old_iso / PAYLOAD)+ extract(old_iso / PAYLOAD, root, folder, 'payload-extract')+ before = inventory(root)+ data = candidate.read_bytes()+ result['original_config_sha256'] = before['entries'][TARGET]['sha256']+ replace_config(root, data)+ expected = expected_payload(before, data)+ assert compare(expected, inventory(root)) is None, 'More than the target file content changed'+ payload = work / 'candidate.sfs'+ measured(['mksquashfs', root, payload, '-noappend', '-no-progress', '-comp', 'zstd',+ '-Xcompression-level', '19', '-b', '1M', '-processors', '2', '-mem', '1G'],+ folder, 'payload-compress')+ shutil.rmtree(root)+ extracted = work / 'verified-root'+ extract(payload, extracted, folder, 'payload-verify')+ difference = compare(expected, inventory(extracted))+ result['payload_difference'] = difference+ assert difference is None, difference+ for name, value in [('original-filesystem', before), ('candidate-filesystem', expected)]:+ with gzip.open(folder / (name + '.json.gz'), 'wb') as handle:+ handle.write(canonical(value))+ result['payload'] = dict(sha256=digest(payload), bytes=payload.stat().st_size,+ changed_path=TARGET, metadata_unchanged=True,+ all_other_paths_and_hardlinks_unchanged=True)+ shutil.rmtree(extracted)+ destination = folder / 'candidate.iso'+ result['iso'] = dict(name=destination.name, **repack(iso, payload, destination, folder, 'iso-candidate'))+ candidate_layout = boot_layout((folder / 'iso-candidate-boot-layout.log').read_text(), destination)+ assert candidate_layout == original_layout, 'Boot entry topology changed'+ result['boot_layout'] = candidate_layout+ new_iso = work / 'candidate-iso'+ measured(['xorriso', '-no_rc', '-osirrox', 'on', '-hardlinks', 'on', '-xattr', 'on',+ '-indev', destination, '-extract', '/', new_iso], folder, 'iso-extract-candidate')+ candidate_inventory = inventory(new_iso)+ result['iso_difference'] = compare_iso(original_inventory, candidate_inventory, old_iso, new_iso, original_layout)+ for name, value in [('original-iso-filesystem', original_inventory), ('candidate-iso-filesystem', candidate_inventory)]:+ with gzip.open(folder / (name + '.json.gz'), 'wb') as handle:+ handle.write(canonical(value))+ assert digest(new_iso / PAYLOAD) == result['payload']['sha256']+ with (new_iso / PAYLOAD).open('rb') as handle:+ assert (new_iso / CHECKSUM).read_text() == hashlib.file_digest(handle, 'sha512').hexdigest() + ' airootfs.sfs\n'+ result['status'] = 'passed'+ return result+ except BaseException as error:+ result.update(status='failed', error=repr(error))+ raise+ finally:+ path.write_text(json.dumps(result, indent=2) + '\n')+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--iso', type=Path, required=True)+ parser.add_argument('--sha256', required=True)+ parser.add_argument('--config', type=Path, required=True)+ parser.add_argument('--output', type=Path, default=Path('os/test-results/zram'))+ args = parser.parse_args()+ assert sys.platform == 'linux' and os.geteuid() == 0, 'Use only the disposable native Linux runner'+ assert os.access('/dev/kvm', os.R_OK | os.W_OK)+ assert not os.environ.get('SOURCE_DATE_EPOCH'), 'Keep every existing filesystem timestamp'+ iso, candidate, folder = args.iso.resolve(), args.config.resolve(), args.output.resolve()+ manifest = json.loads(iso.with_name('manifest.json').read_text())+ assert digest(iso) == args.sha256 == manifest['iso']['sha256']+ assert iso.name == manifest['iso']['name'] and iso.stat().st_size == manifest['iso']['bytes']+ folder.parent.mkdir(parents=True, exist_ok=True)+ assert shutil.disk_usage(folder.parent).free >= 18 * 1024 ** 3+ folder.mkdir(parents=True, exist_ok=False)+ source = subprocess.check_output(['git', '-c', f'safe.directory={Path.cwd()}', 'rev-parse', 'HEAD'], text=True).strip()+ result = dict(status='running', started_at=time.time(), source=source, base_manifest=manifest,+ scope='Private one-file zram acceptance; not release/publication evidence', trials=[])+ try:+ fixture = prepare(iso, manifest, candidate, folder, source)+ derived = copy.deepcopy(manifest)+ derived['iso'] = fixture['iso']+ derived['validation_fixture'] = dict(source=source, base_iso=manifest['iso'],+ base_image_source=manifest['source_commit'],+ changed_payload_file=TARGET, candidate_sha256=digest(candidate))+ (folder / 'manifest.json').write_text(json.dumps(derived, indent=2) + '\n')+ for firmware, memory in [('uefi', 1024), ('bios', 2048)]:+ trial = folder / (firmware + '-browser')+ measured([sys.executable, Path(__file__).with_name('browser_vm.py'),+ '--iso', folder / 'candidate.iso', '--firmware', firmware, '--memory-mib', str(memory),+ '--live-transport', 'usb', '--interactive-install', '--expected-zram-config', candidate,+ '--wlrctl', '/usr/bin/wlrctl', '--browser-script', 'os/root/usr/bin/hn-browser',+ '--compositor-config', 'os/root/usr/share/harness-os/labwc/rc.xml', '--output', trial],+ folder, firmware + '-normal-browser', timeout=1200)+ result['trials'].append(json.loads((trial / 'receipt.json').read_text()))+ # Discard only this test's large private VM files, retaining evidence.+ for name in ['target.qcow2', 'live-usb.qcow2']:+ (trial / name).unlink()+ result['status'] = 'passed'+ except BaseException as error:+ result.update(status='failed', error=repr(error))+ raise+ finally:+ result['finished_at'] = time.time()+ (folder / 'receipt.json').write_text(json.dumps(result, indent=2) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/zram_probe.py b/os/tests/zram_probe.pynew file mode 100644index 000000000..37907bd78--- /dev/null+++ b/os/tests/zram_probe.py@@ -0,0 +1,70 @@+#!/usr/bin/env python3+"""Finite startup/end probes in the private zram acceptance VM."""+import argparse+import hashlib+import importlib.util+import json+import os+from pathlib import Path+import re+import subprocess+++def check_capacity(meminfo, disksize, swaps, page_bytes):+ memory = {key: int(value) for key, value in re.findall(r'^(\w+):\s+(\d+) kB$', meminfo, re.M)}+ expected = min(memory['MemTotal'] // 1024, 4096) * 1024 ** 2+ assert disksize == expected, (disksize, expected)+ rows = [line.split() for line in swaps.splitlines()[1:] if line.strip()]+ assert len(rows) == 1 and rows[0][0] == '/dev/zram0', rows+ assert int(rows[0][2]) == (expected - page_bytes) // 1024, rows+ return dict(memory_kib=memory, expected_disksize_bytes=expected,+ observed_disksize_bytes=disksize, swap_size_kib=int(rows[0][2]))+++def identities():+ result = []+ for path in Path('/proc').iterdir():+ if not path.name.isdecimal():+ continue+ try:+ comm = (path / 'comm').read_text().strip()+ command = (path / 'cmdline').read_text().replace('\0', ' ').rstrip()+ if comm != 'opencode' and command != '/usr/bin/node /usr/lib/harness/cli.mjs start --foreground':+ continue+ stat = (path / 'stat').read_text()+ result.append(dict(pid=int(path.name), start_ticks=int(stat.rsplit(')', 1)[1].split()[19]),+ role='OpenCode' if comm == 'opencode' else 'Harness daemon', command=command))+ except FileNotFoundError:+ continue+ return sorted(result, key=lambda row: row['pid'])+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--config-sha256', required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ assert os.geteuid() == 0+ serial = subprocess.check_output(['lsblk', '-dn', '-o', 'SERIAL', '/dev/vda'], text=True, timeout=5).strip()+ assert serial == 'HN_OS_TEST', 'Only the private VM is permitted'+ config = Path('/etc/systemd/zram-generator.conf').read_bytes()+ assert hashlib.sha256(config).hexdigest() == args.config_sha256+ units = {}+ for unit in ['[email protected]', 'dev-zram0.swap']:+ units[unit] = subprocess.check_output(['systemctl', 'is-active', unit], text=True, timeout=5).strip()+ assert units[unit] == 'active', units+ result = check_capacity(Path('/proc/meminfo').read_text(),+ int(Path('/sys/block/zram0/disksize').read_text()),+ Path('/proc/swaps').read_text(), os.sysconf('SC_PAGE_SIZE'))+ result.update(units=units, config_sha256=args.config_sha256, identities=identities(),+ oom_kills=int(re.search(r'^oom_kill (\d+)$', Path('/proc/vmstat').read_text(), re.M)[1]))+ if Path('/etc/harness-live').exists():+ spec = importlib.util.spec_from_file_location('installer', '/usr/lib/harness-os/install.py')+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ result['preflight_argon_budget_kib'] = module.encryption_memory()+ args.output.write_text(json.dumps(result) + '\n')+++if __name__ == '__main__':+ main()