From 3aea854d410f6534ac10045cf5d8d76852f9f798 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 00:00:59 +0200 Subject: [PATCH 1/8] fix(ci): route desktop gates to Linux with pinned Rust bootstrap --- .github/workflows/desktop.yml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 89e8c786..272fcfd0 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -1,9 +1,11 @@ name: Desktop foundation on: push: - paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml'] + # Main pushes exclude CLI release tags; feature branches use pull requests. + branches: [main] + paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml', 'scripts/install-pinned-rustup.sh', 'Cargo.toml', 'Cargo.lock'] pull_request: - paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml'] + paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml', 'scripts/install-pinned-rustup.sh', 'Cargo.toml', 'Cargo.lock'] permissions: contents: read jobs: @@ -11,10 +13,15 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest, macos-latest] + # Windows/macOS validation is deferred and unqualified. + os: [ubuntu-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 + - name: Install Linux build tools + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates build-essential python3 python-is-python3 + - name: Install pinned Rust + run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Format run: cargo fmt --manifest-path desktop-core/Cargo.toml --check - name: Tests -- 2.54.0 From b848e433a32f6a97d4f47fad11c73b56087d4947 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 00:25:07 +0200 Subject: [PATCH 2/8] STRA-13: align desktop CI Rust helper target Set the desktop job target directory to desktop-core/target so workspace Rust builds produce the helper at the existing .NET and Python consumer paths. Preserve all workflow checks and event routing. --- .github/workflows/desktop.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 272fcfd0..0e35f11f 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -10,6 +10,8 @@ permissions: contents: read jobs: core: + env: + CARGO_TARGET_DIR: ${{ github.workspace }}/desktop-core/target strategy: fail-fast: false matrix: -- 2.54.0 From 63a56772da9d1745af4dc4d18b9bbb5a6726642e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 00:30:54 +0200 Subject: [PATCH 3/8] test: bound CLI container startup wait --- scripts/smoke-cli-container.py | 50 ++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/scripts/smoke-cli-container.py b/scripts/smoke-cli-container.py index 5b51aaf1..ee38040f 100644 --- a/scripts/smoke-cli-container.py +++ b/scripts/smoke-cli-container.py @@ -9,12 +9,36 @@ import subprocess from docker_smoke_http import ISOLATION, docker, prepare_probe, request +def diagnose_owned_container(name): + """Emit bounded state/log diagnostics for this invocation's unique container.""" + commands = ( + ('inspect', ('inspect', '--format', '{{json .State}}', name)), + ('logs', ('logs', '--tail', '40', name)), + ) + for label, args in commands: + try: + result = docker(*args, check=False, timeout=8) + output = (result.stdout or '') + (result.stderr or '') + if len(output) > 8192: + output = '[earlier output truncated]\n' + output[-8192:] + if output: + print(f'Owned container {label} (exit {result.returncode}):\n{output}', + file=sys.stderr, flush=True) + else: + print(f'Owned container {label}: no output (exit {result.returncode})', + file=sys.stderr, flush=True) + except Exception as error: + print(f'Owned container {label} diagnostics unavailable: {type(error).__name__}', + file=sys.stderr, flush=True) + + def main(image): name = 'strata-cli-smoke-' + uuid.uuid4().hex common = ['--name', name, *ISOLATION] root = Path(__file__).resolve().parents[1] prepare_probe() + primary_error = None try: version = docker('run', '--rm', *common, '--network', 'none', image, '--version').stdout assert version.startswith('strata-next '), version @@ -24,8 +48,12 @@ def main(image): info = json.loads(docker('run', '--rm', *common, '--network', 'none', image, 'engine-info').stdout) assert info['embedded'] is False and info['model_bundled'] is False, info - docker('run', '-d', *common, '--network', 'none', - '-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve') + try: + docker('run', '-d', *common, '--network', 'none', + '-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve', timeout=120) + except subprocess.TimeoutExpired: + diagnose_owned_container(name) + raise deadline = time.monotonic() + 15 while True: try: @@ -42,8 +70,24 @@ def main(image): assert state['ExitCode'] == 0 and not state['OOMKilled'], state print('CLI OCI passed: actual image, exact upstream license, no embedded engine/model, ' 'non-root read-only health200/ready503, graceful stop. No GPU inference qualified.') + except BaseException as error: + primary_error = error + raise finally: - docker('rm', '-f', name, check=False) + cleanup_error = None + try: + result = docker('rm', '-f', name, check=False, timeout=10) + if result.returncode: + cleanup_error = subprocess.CalledProcessError( + result.returncode, ['docker', 'rm', '-f', name], + output=result.stdout, stderr=result.stderr) + except Exception as error: + cleanup_error = error + if cleanup_error is not None: + if primary_error is None: + raise cleanup_error + print(f'Owned container cleanup failed after {type(primary_error).__name__}: ' + f'{type(cleanup_error).__name__}', file=sys.stderr, flush=True) if __name__ == '__main__': -- 2.54.0 From fb3ce6e8c5e8a5ed1b063594a83843b255de2b27 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 00:33:41 +0200 Subject: [PATCH 4/8] STRA-13: isolate CLI container gate image ownership Build the CLI container gate with a run and attempt tag plus a nonce owner label, capture and validate its immutable image ID, and pass that ID to the smoke check. Limit cleanup to the validated owned image and temporary receipt without parent pruning, preserving all other workflow gates. --- .github/workflows/linux.yml | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 7ff823b2..898992f6 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -481,12 +481,41 @@ jobs: command -v docker >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io; } docker version - name: Build actual CLI-only scratch image - run: docker build --file deploy/Dockerfile.static-cli --tag strata-cli-check . + run: | + set -euo pipefail + owned_dir="$(mktemp -d "$RUNNER_TEMP/leleka-cli-check-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-XXXXXX")" + image_tag="leleka-cli-check:${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${owned_dir##*-}" + printf '%s\n' "CLI_CHECK_DIR=$owned_dir" "CLI_CHECK_TAG=$image_tag" >> "$GITHUB_ENV" + # The nonce label makes identical builds distinct image configs on the shared daemon. + docker build --file deploy/Dockerfile.static-cli --tag "$image_tag" \ + --label "io.leleka.ci.cli-check-owner=$image_tag" --iidfile "$owned_dir/image.iid" . + image="$(cat "$owned_dir/image.iid")" + [[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]] + test "$(docker image inspect --format '{{ index .Config.Labels "io.leleka.ci.cli-check-owner" }}' "$image")" = "$image_tag" - name: Check isolated CLI container startup and shutdown - run: python3 scripts/smoke-cli-container.py strata-cli-check + run: | + set -euo pipefail + image="$(cat "$CLI_CHECK_DIR/image.iid")" + [[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]] + test "$(docker image inspect --format '{{ index .Config.Labels "io.leleka.ci.cli-check-owner" }}' "$image")" = "$CLI_CHECK_TAG" + python3 scripts/smoke-cli-container.py "$image" - name: Remove test image if: always() - run: docker image rm strata-cli-check || true + run: | + set -euo pipefail + test -n "${CLI_CHECK_DIR:-}" || exit 0 + trap 'rm -f -- "$CLI_CHECK_DIR/image.iid"; rmdir -- "$CLI_CHECK_DIR"' EXIT + if test -s "$CLI_CHECK_DIR/image.iid"; then + image="$(cat "$CLI_CHECK_DIR/image.iid")" + else + # A failed build may leave the owned tag without writing an IID receipt. + image="$(docker image inspect --format '{{.Id}}' "$CLI_CHECK_TAG" 2>/dev/null || true)" + fi + test -n "$image" || exit 0 + [[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]] + test "$(docker image inspect --format '{{ index .Config.Labels "io.leleka.ci.cli-check-owner" }}' "$image")" = "$CLI_CHECK_TAG" + # No force or parent pruning: cleanup cannot remove other jobs' references or cache. + docker image rm --no-prune "$image" release-cli: permissions: -- 2.54.0 From d7d24c7401b0fdbc49e2fccb34e5da2d17f7a9c4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 00:34:59 +0200 Subject: [PATCH 5/8] test: preserve container smoke failures on cleanup --- scripts/smoke-cli-container.py | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/scripts/smoke-cli-container.py b/scripts/smoke-cli-container.py index ee38040f..99ba96b0 100644 --- a/scripts/smoke-cli-container.py +++ b/scripts/smoke-cli-container.py @@ -9,6 +9,13 @@ import subprocess from docker_smoke_http import ISOLATION, docker, prepare_probe, request +def report_best_effort(message): + try: + print(message, file=sys.stderr, flush=True) + except Exception: + pass + + def diagnose_owned_container(name): """Emit bounded state/log diagnostics for this invocation's unique container.""" commands = ( @@ -22,14 +29,14 @@ def diagnose_owned_container(name): if len(output) > 8192: output = '[earlier output truncated]\n' + output[-8192:] if output: - print(f'Owned container {label} (exit {result.returncode}):\n{output}', - file=sys.stderr, flush=True) + report_best_effort( + f'Owned container {label} (exit {result.returncode}):\n{output}') else: - print(f'Owned container {label}: no output (exit {result.returncode})', - file=sys.stderr, flush=True) + report_best_effort( + f'Owned container {label}: no output (exit {result.returncode})') except Exception as error: - print(f'Owned container {label} diagnostics unavailable: {type(error).__name__}', - file=sys.stderr, flush=True) + report_best_effort( + f'Owned container {label} diagnostics unavailable: {type(error).__name__}') def main(image): @@ -52,7 +59,11 @@ def main(image): docker('run', '-d', *common, '--network', 'none', '-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve', timeout=120) except subprocess.TimeoutExpired: - diagnose_owned_container(name) + try: + diagnose_owned_container(name) + except Exception as error: + report_best_effort( + f'Owned container diagnostics failed: {type(error).__name__}') raise deadline = time.monotonic() + 15 while True: @@ -86,8 +97,9 @@ def main(image): if cleanup_error is not None: if primary_error is None: raise cleanup_error - print(f'Owned container cleanup failed after {type(primary_error).__name__}: ' - f'{type(cleanup_error).__name__}', file=sys.stderr, flush=True) + report_best_effort( + f'Owned container cleanup failed after {type(primary_error).__name__}: ' + f'{type(cleanup_error).__name__}') if __name__ == '__main__': -- 2.54.0 From bbc8018e8ba83058a85e3513c1c3e566d6a7e2c7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 00:53:28 +0200 Subject: [PATCH 6/8] Bound runtime image probe waits and cleanup --- scripts/build-runtime-image.py | 99 ++++++++++++++++++++++- scripts/test-runtime-image.py | 139 +++++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+), 3 deletions(-) diff --git a/scripts/build-runtime-image.py b/scripts/build-runtime-image.py index 282bc9df..a67b400c 100644 --- a/scripts/build-runtime-image.py +++ b/scripts/build-runtime-image.py @@ -9,6 +9,7 @@ import re import shutil import stat import subprocess +import sys import tempfile import uuid @@ -17,6 +18,9 @@ NAME = 'strata-next-linux-x86_64-musl' FILES = {NAME, 'PROVENANCE.json', 'SHA256SUMS'} # Official Ubuntu 26.04 linux/amd64 manifest, observed 2026-10-04; glibc is probed. BASE = 'ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794' +PROBE_INFRA_TIMEOUT = 120 +PROBE_APP_TIMEOUT = 30 +PROBE_OUTPUT_LIMIT = 64 * 1024 def digest(path): @@ -124,18 +128,107 @@ def docker(*args, timeout=30, check=True): check=check, timeout=timeout) +def _bounded_output(value, stream): + if not isinstance(value, str) or len(value.encode('utf-8')) > PROBE_OUTPUT_LIMIT: + raise ValueError(f'isolated CLI {stream} exceeds {PROBE_OUTPUT_LIMIT}-byte limit') + return value + + +def _report_best_effort(message): + try: + print(message, file=sys.stderr, flush=True) + except BaseException: + pass + + +def _safe_report(message): + try: + _report_best_effort(message) + except BaseException: + pass + + +def _diagnose_owned_container(name): + for label, args in ( + ('inspect', ('inspect', '--format', '{{json .State}}', name)), + ('logs', ('logs', '--tail', '40', name)), + ): + try: + result = docker(*args, timeout=8, check=False) + output = (result.stdout or '') + (result.stderr or '') + if len(output.encode('utf-8')) > PROBE_OUTPUT_LIMIT: + output = '[earlier output truncated]\n' + output[-PROBE_OUTPUT_LIMIT:] + _safe_report( + f'Owned runtime-image probe {label} (exit {result.returncode}):\n{output}') + except BaseException as error: + _safe_report( + f'Owned runtime-image probe {label} unavailable: {type(error).__name__}') + + def isolated_run(image, arguments, *, entrypoint=None): name = 'strata-image-probe-' + uuid.uuid4().hex - args = ['run', '--name', name, '--rm', '--platform', 'linux/amd64', '--network', 'none', + args = ['create', '--name', name, '--platform', 'linux/amd64', '--network', 'none', '--read-only', '--user', '65532:65532', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void'] if entrypoint: args += ['--entrypoint', entrypoint] + primary_error = None try: - return docker(*args, image, *arguments).stdout + created = docker(*args, image, *arguments, timeout=PROBE_INFRA_TIMEOUT) + _bounded_output(created.stdout, 'create output') + docker('start', name, timeout=PROBE_INFRA_TIMEOUT) + + waited = docker('wait', name, timeout=PROBE_APP_TIMEOUT, check=False) + _bounded_output(waited.stdout, 'wait status') + _bounded_output(waited.stderr, 'wait stderr') + if waited.returncode: + raise subprocess.CalledProcessError( + waited.returncode, ['docker', 'wait', name], + output=waited.stdout, stderr=waited.stderr) + if not re.fullmatch(r'(?:0|[1-9][0-9]{0,2})\n?', waited.stdout): + raise ValueError('docker wait returned a malformed CLI exit status') + exit_status = int(waited.stdout.rstrip('\n')) + if exit_status > 255: + raise ValueError('docker wait returned a CLI exit status outside 0..255') + + logs = docker('logs', name, timeout=30, check=False) + stdout = _bounded_output(logs.stdout, 'stdout') + stderr = _bounded_output(logs.stderr, 'stderr') + if logs.returncode: + raise subprocess.CalledProcessError( + logs.returncode, ['docker', 'logs', name], output=stdout, stderr=stderr) + if exit_status: + raise subprocess.CalledProcessError( + exit_status, ['docker', 'container', 'probe', name], + output=stdout, stderr=stderr) + if stderr: + _report_best_effort(f'Runtime-image probe stderr:\n{stderr}') + return stdout + except BaseException as error: + primary_error = error + try: + _diagnose_owned_container(name) + except BaseException as diagnostic_error: + _safe_report( + f'Owned runtime-image probe diagnostics failed: {type(diagnostic_error).__name__}') + raise finally: - docker('rm', '-f', name, check=False) + cleanup_error = None + try: + result = docker('rm', '-f', name, timeout=10, check=False) + if result.returncode: + cleanup_error = subprocess.CalledProcessError( + result.returncode, ['docker', 'rm', '-f', name], + output=result.stdout, stderr=result.stderr) + except BaseException as error: + cleanup_error = error + if cleanup_error is not None: + if primary_error is None: + raise cleanup_error + _safe_report( + f'Owned runtime-image probe cleanup failed after ' + f'{type(primary_error).__name__}: {type(cleanup_error).__name__}') def assemble(args): diff --git a/scripts/test-runtime-image.py b/scripts/test-runtime-image.py index ea44f90d..6a251163 100644 --- a/scripts/test-runtime-image.py +++ b/scripts/test-runtime-image.py @@ -3,6 +3,7 @@ import importlib.util import hashlib import json +import subprocess from pathlib import Path import shutil import tempfile @@ -156,5 +157,143 @@ class PackageTests(unittest.TestCase): b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1) +class IsolatedProbeTests(unittest.TestCase): + def setUp(self): + reporter = patch.object(b, '_report_best_effort') + reporter.start() + self.addCleanup(reporter.stop) + + def fake_docker(self, calls, *, wait_stdout='0\n', wait_stderr='', wait_rc=0, + logs_stdout='probe output\n', logs_stderr='', logs_rc=0, + start_error=None, wait_error=None, cleanup_error=None, logs_size=None): + container = None + + def invoke(*args, timeout=30, check=True): + nonlocal container + calls.append((args, timeout, check)) + if args[0] == 'create': + container = args[args.index('--name') + 1] + return SimpleNamespace(stdout='a' * 64 + '\n', stderr='', returncode=0) + if args[0] == 'start': + self.assertEqual(args[1], container) + if start_error is not None: + raise start_error + return SimpleNamespace(stdout=container + '\n', stderr='', returncode=0) + if args[0] == 'wait': + self.assertEqual(args[1], container) + if wait_error is not None: + raise wait_error + return SimpleNamespace(stdout=wait_stdout, stderr=wait_stderr, returncode=wait_rc) + if args[0] == 'logs': + self.assertEqual(args[-1], container) + stdout = logs_stdout if logs_size is None else 'x' * logs_size + return SimpleNamespace(stdout=stdout, stderr=logs_stderr, returncode=logs_rc) + if args[:2] == ('inspect', '--format'): + self.assertEqual(args[-1], container) + raise OSError('synthetic inspect unavailable') + if args[0] == 'inspect': + self.assertEqual(args[-1], container) + raise OSError('synthetic inspect unavailable') + if args[:2] == ('rm', '-f'): + self.assertEqual(args[-1], container) + if cleanup_error is not None: + raise cleanup_error + return SimpleNamespace(stdout='', stderr='', returncode=0) + raise AssertionError(f'unexpected Docker call: {args!r}') + + return invoke + + def test_probe_uses_long_infrastructure_deadline_and_original_cli_deadline(self): + calls = [] + with patch.object(b, 'docker', side_effect=self.fake_docker(calls)): + output = b.isolated_run('sha256:' + 'a' * 64, ['engine-info'], entrypoint='strata-next') + self.assertEqual(output, 'probe output\n') + operations = [call[0][0] for call in calls] + self.assertEqual(operations, ['create', 'start', 'wait', 'logs', 'rm']) + create, start, wait, logs, remove = calls + self.assertEqual(create[1], 120) + self.assertEqual(start[1], 120) + self.assertEqual(wait[1], 30) + self.assertEqual(logs[1], 30) + self.assertEqual(remove[1], 10) + self.assertNotIn('--rm', create[0]) + self.assertEqual(create[0][create[0].index('--network') + 1], 'none') + self.assertIn('--read-only', create[0]) + self.assertIn('--cap-drop', create[0]) + self.assertIn('65532:65532', create[0]) + self.assertIn('strata-next', create[0]) + self.assertEqual(start[0][1], create[0][create[0].index('--name') + 1]) + self.assertEqual(wait[0][1], start[0][1]) + self.assertEqual(logs[0][-1], start[0][1]) + self.assertEqual(remove[0][-1], start[0][1]) + + def test_probe_rejects_malformed_wait_status_and_bounds_both_streams(self): + for status in ('', '0\n1\n', '-1\n', '256\n'): + with self.subTest(status=status): + calls = [] + with patch.object(b, 'docker', side_effect=self.fake_docker(calls, wait_stdout=status)): + with self.assertRaisesRegex(ValueError, 'malformed CLI exit status|outside 0..255'): + b.isolated_run('image', ['engine-help']) + self.assertEqual([x[0][0] for x in calls[:3]], ['create', 'start', 'wait']) + self.assertEqual(calls[-1][0][0:2], ('rm', '-f')) + + for stream in ('stdout', 'stderr'): + with self.subTest(stream=stream): + calls = [] + kwargs = {'logs_size': b.PROBE_OUTPUT_LIMIT + 1} if stream == 'stdout' else { + 'logs_stderr': 'x' * (b.PROBE_OUTPUT_LIMIT + 1)} + with patch.object(b, 'docker', side_effect=self.fake_docker(calls, **kwargs)): + with self.assertRaisesRegex(ValueError, f'CLI {stream} exceeds'): + b.isolated_run('image', ['engine-help']) + self.assertEqual(calls[-1][0][0:2], ('rm', '-f')) + + def test_nonzero_cli_exit_preserves_both_streams(self): + calls = [] + with patch.object(b, 'docker', side_effect=self.fake_docker( + calls, wait_stdout='17\n', logs_stdout='help stdout', logs_stderr='help stderr')): + with self.assertRaises(subprocess.CalledProcessError) as raised: + b.isolated_run('image', ['engine-help']) + self.assertEqual(raised.exception.returncode, 17) + self.assertEqual(raised.exception.output, 'help stdout') + self.assertEqual(raised.exception.stderr, 'help stderr') + self.assertEqual([x[0][0] for x in calls[:4]], ['create', 'start', 'wait', 'logs']) + self.assertEqual(calls[-1][0][0:2], ('rm', '-f')) + + def test_infrastructure_timeout_keeps_original_across_broken_reporting_and_cleanup(self): + calls = [] + timeout = subprocess.TimeoutExpired(['docker', 'start'], 120) + with patch.object(b, 'docker', side_effect=self.fake_docker( + calls, start_error=timeout, + cleanup_error=subprocess.TimeoutExpired(['docker', 'rm'], 10))), \ + patch.object(b, '_report_best_effort', side_effect=BrokenPipeError('closed stderr')): + with self.assertRaises(subprocess.TimeoutExpired) as raised: + b.isolated_run('image', ['engine-info']) + self.assertIs(raised.exception, timeout) + operations = [x[0][0] for x in calls] + self.assertEqual(operations, ['create', 'start', 'inspect', 'logs', 'rm']) + container = calls[0][0][calls[0][0].index('--name') + 1] + self.assertTrue(all(call[0][-1] == container for call in calls[2:])) + self.assertTrue(all(call[1] <= 10 for call in calls[2:])) + + def test_application_timeout_is_not_extended_by_infrastructure_deadlines(self): + calls = [] + timeout = subprocess.TimeoutExpired(['docker', 'wait'], 30) + with patch.object(b, 'docker', side_effect=self.fake_docker(calls, wait_error=timeout)): + with self.assertRaises(subprocess.TimeoutExpired) as raised: + b.isolated_run('image', ['engine-help']) + self.assertIs(raised.exception, timeout) + self.assertEqual([x[1] for x in calls[:3]], [120, 120, 30]) + self.assertEqual(calls[-1][0][:2], ('rm', '-f')) + + def test_cleanup_failure_after_success_is_not_silently_ignored(self): + calls = [] + with patch.object(b, 'docker', side_effect=self.fake_docker( + calls, cleanup_error=OSError('synthetic cleanup failure'))): + with self.assertRaisesRegex(OSError, 'synthetic cleanup failure'): + b.isolated_run('image', ['engine-info']) + self.assertEqual(calls[-1][0][0:2], ('rm', '-f')) + self.assertEqual(calls[-1][1], 10) + + if __name__ == '__main__': unittest.main() -- 2.54.0 From 4aeec3c541ef098b4514b197445c074cc4037f9c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 01:19:30 +0200 Subject: [PATCH 7/8] Add offline PLE config parity preflight --- scripts/check-local.sh | 1 + scripts/check-ple-config-parity.py | 398 +++++++++++++++++++++++++++++ scripts/test-ple-config-parity.py | 273 ++++++++++++++++++++ 3 files changed, 672 insertions(+) create mode 100755 scripts/check-ple-config-parity.py create mode 100644 scripts/test-ple-config-parity.py diff --git a/scripts/check-local.sh b/scripts/check-local.sh index f14cb531..4940d65a 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -14,6 +14,7 @@ python3 "${repo_root}/scripts/test-static-cuda-profile.py" python3 "${repo_root}/scripts/test-static-cuda-elf.py" python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-runtime-image.py" +python3 "${repo_root}/scripts/test-ple-config-parity.py" python3 "${repo_root}/scripts/test-gitea-release.py" python3 "${repo_root}/scripts/test-keyless-routing.py" diff --git a/scripts/check-ple-config-parity.py b/scripts/check-ple-config-parity.py new file mode 100755 index 00000000..224fcb03 --- /dev/null +++ b/scripts/check-ple-config-parity.py @@ -0,0 +1,398 @@ +#!/usr/bin/env python3 +"""Offline, secret-safe preflight for the Qwen GPU-PLE profile migration. + +This can prove selected settings and the explicitly supplied KAR file digest. +It cannot certify deployed parity: credential, model-pack, MTP and incomplete +environment identity remain unverified unless separately established. The +legacy input must be an operator-supplied redacted projection, not the complete +original config; this proves no credential equivalence. Credential-bearing JSON +is rejected with a static category after parsing and must not be supplied. +""" + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +PINNED_ARCHIVE_SHA256 = '536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5' +PINNED_NATIVE_SHARD = 'Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf' +PINNED_NATIVE_MANIFEST = 'qwen3.8-flash-next-iq3-s.json' +MAX_JSON_BYTES = 1024 * 1024 +MAX_ARCHIVE_BYTES = 100 * 1024**3 +LEGACY_KEYS = {'exe', 'args', 'cwd', 'log'} +FILE_CONFIG_KEYS = { + 'queue_timeout_s', 'mtp_pack', 'response_history_dir', 'assets', + 'native_model', 'gpu_requirement', 'cuda_memory', 'engine_probe', + 'shutdown_grace_s', 'max_in_flight_requests', 'api_key_file', 'bind', + 'model', 'engine', +} +ENGINE_KEYS = { + 'executable', 'args', 'startup_timeout_s', 'generation_timeout_s', + 'max_restarts', 'tokenizer_dir', +} +ASSET_KEYS = {'manifest', 'directory'} +NATIVE_MODEL_KEYS = {'manifest', 'source_dir', 'output', 'runtime_profile'} +CUDA_MEMORY_KEYS = {'required_mib', 'reserve_mib'} +NONSECRET_ENV = { + 'STRATA_BIND', 'STRATA_MODEL_ID', 'STRATA_ENGINE_EXE', + 'STRATA_ENGINE_ARGS_JSON', 'STRATA_STARTUP_TIMEOUT_S', + 'STRATA_GENERATION_TIMEOUT_S', 'STRATA_MAX_WORKER_RESTARTS', + 'STRATA_TOKENIZER_DIR', 'STRATA_MAX_IN_FLIGHT_REQUESTS', + 'STRATA_QUEUE_TIMEOUT_S', 'STRATA_SHUTDOWN_GRACE_S', + 'STRATA_RESPONSE_HISTORY_DIR', 'CUDA_VISIBLE_DEVICES', +} +REQUIRED_SETTINGS = { + '--max-context': '262144', '--kv': 'int8', '--kv-resident': '32768', + '--spec': '4', '--spec-min-p': '0.5', '--expert-cache': 'auto', + '--prefill': 'auto', '--vram-reserve-mib': '700', +} +PLE_FLAGS = ('--ple-kar', '--ple-kar-level', '--ple-kar-gpu-cache-mib') +UNVERIFIED = { + 'authentication_equivalence', 'legacy_pack_content_equivalence', + 'mtp_content_equivalence', 'native_runtime_defaults', 'http_capacity_policy', + 'worker_slot_count', 'request_model_identity', 'source_config_projection', +} + + +class InvalidInput(ValueError): + pass + + +def _pairs(pairs): + result = {} + for key, value in pairs: + if key in result: + raise InvalidInput('duplicate_json_key') + result[key] = value + return result + + +def _constant(_value): + raise InvalidInput('nonstandard_json_constant') + + +def read_json(path): + try: + with Path(path).open('rb') as stream: + data = stream.read(MAX_JSON_BYTES + 1) + if len(data) > MAX_JSON_BYTES: + raise InvalidInput('json_size_limit') + return json.loads(data.decode('utf-8'), object_pairs_hook=_pairs, + parse_constant=_constant) + except InvalidInput: + raise + except (OSError, UnicodeError, json.JSONDecodeError): + raise InvalidInput('invalid_json') from None + + +def _keys(value, allowed, category): + if not isinstance(value, dict) or not set(value).issubset(allowed): + raise InvalidInput(category) + + +def _string(value): + return isinstance(value, str) and bool(value) + + +def _strings(value): + return isinstance(value, list) and all(isinstance(item, str) for item in value) + + +def validate_legacy(value): + if isinstance(value, dict) and 'api_key' in value: + raise InvalidInput('legacy_credential_present') + _keys(value, LEGACY_KEYS, 'legacy_schema') + if set(value) != LEGACY_KEYS or not all(_string(value[key]) for key in ('exe', 'cwd', 'log')): + raise InvalidInput('legacy_schema') + if not _strings(value['args']): + raise InvalidInput('legacy_schema') + + +def validate_candidate(value): + _keys(value, FILE_CONFIG_KEYS, 'candidate_schema') + if 'engine' not in value or not isinstance(value['engine'], dict): + raise InvalidInput('candidate_schema') + _keys(value['engine'], ENGINE_KEYS, 'candidate_schema') + engine = value['engine'] + if not _string(engine.get('executable')) or not _strings(engine.get('args', [])): + raise InvalidInput('candidate_schema') + for key, low, high in (('startup_timeout_s', 1, 3600), + ('generation_timeout_s', 1, 86400), + ('max_restarts', 0, 3)): + if key in engine and (type(engine[key]) is not int or not low <= engine[key] <= high): + raise InvalidInput('candidate_schema') + if 'tokenizer_dir' in engine and not _string(engine['tokenizer_dir']): + raise InvalidInput('candidate_schema') + if 'native_model' not in value or not isinstance(value['native_model'], dict): + raise InvalidInput('candidate_schema') + _keys(value['native_model'], NATIVE_MODEL_KEYS, 'candidate_schema') + if set(value['native_model']) != NATIVE_MODEL_KEYS or value['native_model'].get('runtime_profile') != 'qwen4exp-flash-next': + raise InvalidInput('candidate_schema') + for key in ('manifest', 'source_dir', 'output'): + if not _string(value['native_model'].get(key)): + raise InvalidInput('candidate_schema') + assets = value.get('assets', []) + if not isinstance(assets, list) or not all(isinstance(asset, dict) for asset in assets): + raise InvalidInput('candidate_schema') + for asset in assets: + _keys(asset, ASSET_KEYS, 'candidate_schema') + if set(asset) != ASSET_KEYS or not all(_string(asset[key]) for key in ASSET_KEYS): + raise InvalidInput('candidate_schema') + if 'cuda_memory' in value: + _keys(value['cuda_memory'], CUDA_MEMORY_KEYS, 'candidate_schema') + if set(value['cuda_memory']) != CUDA_MEMORY_KEYS: + raise InvalidInput('candidate_schema') + if any(type(value['cuda_memory'][key]) is not int or value['cuda_memory'][key] <= 0 + for key in CUDA_MEMORY_KEYS): + raise InvalidInput('candidate_schema') + if 'gpu_requirement' in value and value['gpu_requirement'] != 'cuda-13.0-linux': + raise InvalidInput('candidate_schema') + for key in ('mtp_pack', 'response_history_dir', 'api_key_file', 'bind', 'model'): + if key in value and not _string(value[key]): + raise InvalidInput('candidate_schema') + if 'queue_timeout_s' in value and (type(value['queue_timeout_s']) is not int or + not 1 <= value['queue_timeout_s'] <= 86400): + raise InvalidInput('candidate_schema') + if 'shutdown_grace_s' in value and (type(value['shutdown_grace_s']) is not int or + not 0 <= value['shutdown_grace_s'] <= 20): + raise InvalidInput('candidate_schema') + if 'max_in_flight_requests' in value and (type(value['max_in_flight_requests']) is not int or + value['max_in_flight_requests'] <= 0): + raise InvalidInput('candidate_schema') + if 'engine_probe' in value and type(value['engine_probe']) is not bool: + raise InvalidInput('candidate_schema') + if 'mtp_pack' not in value or not _string(value['mtp_pack']): + raise InvalidInput('candidate_schema') + if 'tokenizer_dir' in engine: + raise InvalidInput('candidate_schema') + + +def validate_context(value): + _keys(value, {'legacy', 'candidate', 'environment_complete'}, 'service_context_schema') + if set(value) != {'legacy', 'candidate', 'environment_complete'} or not isinstance(value['environment_complete'], bool): + raise InvalidInput('service_context_schema') + for side in ('legacy', 'candidate'): + item = value[side] + allowed = {'bind', 'cwd', 'log', 'effective_slots', 'environment'} + required = allowed - {'effective_slots'} + _keys(item, allowed, 'service_context_schema') + if not required.issubset(item) or not all(_string(item[k]) for k in ('bind', 'cwd', 'log')): + raise InvalidInput('service_context_schema') + if ('effective_slots' in item and + (type(item['effective_slots']) is not int or item['effective_slots'] < 0)): + raise InvalidInput('service_context_schema') + env = item['environment'] + if not isinstance(env, dict) or not set(env).issubset(NONSECRET_ENV): + raise InvalidInput('service_context_schema') + if not all(isinstance(v, str) for v in env.values()): + raise InvalidInput('service_context_schema') + + +def option_values(arguments, name): + found = [] + index = 0 + while index < len(arguments): + token = arguments[index] + if token == name: + if index + 1 >= len(arguments) or arguments[index + 1].startswith('--'): + raise InvalidInput('engine_arguments') + found.append(arguments[index + 1]) + index += 2 + elif token.startswith(name + '='): + found.append(token[len(name) + 1:]) + index += 1 + else: + index += 1 + if len(found) > 1: + raise InvalidInput('duplicate_engine_option') + return found + + +def strip_legacy_migrations(arguments): + result = [] + migrated = {'--pack', '--native', '--mtp'} + seen = set() + index = 0 + while index < len(arguments): + token = arguments[index] + name = token.split('=', 1)[0] + if name in migrated: + if name in seen or token != name or index + 1 >= len(arguments) or arguments[index + 1].startswith('--'): + raise InvalidInput('legacy_model_arguments') + seen.add(name) + index += 2 + else: + result.append(token) + index += 1 + if seen != migrated: + raise InvalidInput('legacy_model_arguments') + return result + + +def ple_selection(arguments, archive_path): + """Return argv without its PLE tuple and whether the exact tuple was present.""" + seen = [token for token in arguments + if any(token == flag or token.startswith(flag + '=') for flag in PLE_FLAGS)] + if not seen: + return list(arguments), False + expected = [PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64'] + if arguments[-len(expected):] != expected: + raise InvalidInput('ple_arguments') + if len(seen) != len(PLE_FLAGS): + raise InvalidInput('ple_arguments') + return list(arguments[:-len(expected)]), True + + +def check_archive(path, expected): + if not re.fullmatch(r'[0-9a-f]{64}', expected) or expected != PINNED_ARCHIVE_SHA256: + raise InvalidInput('archive_pin') + try: + if Path(path).is_symlink() or not Path(path).is_file(): + raise InvalidInput('archive_file') + digest = hashlib.sha256() + size = 0 + with Path(path).open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + size += len(chunk) + if size > MAX_ARCHIVE_BYTES: + raise InvalidInput('archive_size_limit') + digest.update(chunk) + if digest.hexdigest() != expected: + raise InvalidInput('archive_digest') + except InvalidInput: + raise + except OSError: + raise InvalidInput('archive_file') from None + + +def compare(legacy, candidate, context, archive_path, archive_sha, expected_executable, + expected_bind, expected_log): + validate_legacy(legacy) + validate_candidate(candidate) + validate_context(context) + check_archive(archive_path, archive_sha) + mismatches = [] + unverified = sorted(UNVERIFIED) + + engine = candidate['engine'] + legacy_args = legacy['args'] + candidate_args = engine.get('args', []) + legacy_env = context['legacy']['environment'] + candidate_env = context['candidate']['environment'] + effective_executable = candidate_env.get('STRATA_ENGINE_EXE', engine['executable']) + effective_bind = candidate_env.get('STRATA_BIND', candidate.get('bind', '127.0.0.1:8081')) + if effective_executable != expected_executable or not _string(expected_executable): + mismatches.append('executable_selection') + slots = [context[side].get('effective_slots') for side in ('legacy', 'candidate')] + if any(value is None for value in slots): + unverified.append('worker_slot_count') + elif slots != [1, 1]: + mismatches.append('slot_count') + if context['legacy']['cwd'] != context['candidate']['cwd']: + mismatches.append('working_directory') + if context['candidate']['bind'] != expected_bind or effective_bind != context['candidate']['bind']: + mismatches.append('bind_selection') + if context['candidate']['log'] != expected_log: + mismatches.append('log_selection') + for name in set(legacy_env) | set(candidate_env): + if legacy_env.get(name) == candidate_env.get(name): + continue + if name == 'STRATA_BIND': + # The bind delta is explicit and independently checked above. + continue + if name == 'STRATA_ENGINE_EXE' and candidate_env.get(name) == expected_executable: + # The executable delta is explicit and independently checked above. + continue + mismatches.append('environment_delta') + break + effective_args = candidate_args + if 'STRATA_ENGINE_ARGS_JSON' in candidate_env: + try: + override = json.loads(candidate_env['STRATA_ENGINE_ARGS_JSON'], object_pairs_hook=_pairs, + parse_constant=_constant) + except (InvalidInput, json.JSONDecodeError): + mismatches.append('engine_arguments') + else: + if not _strings(override): + mismatches.append('engine_arguments') + else: + effective_args = override + if effective_args != candidate_args: + mismatches.append('engine_arguments') + if 'STRATA_ENGINE_ARGS_JSON' in legacy_env: + mismatches.append('environment_delta') + if not context['environment_complete']: + unverified.append('effective_environment') + + try: + legacy_base, _had_legacy_ple = ple_selection(legacy_args, archive_path) + legacy_base = strip_legacy_migrations(legacy_base) + candidate_base, had_candidate_ple = ple_selection(effective_args, archive_path) + expected_base = legacy_base + [ + PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64'] + if not had_candidate_ple or candidate_base != legacy_base or effective_args != expected_base: + mismatches.append('engine_arguments') + for flag, wanted in REQUIRED_SETTINGS.items(): + if option_values(legacy_args, flag) != [wanted] or option_values(effective_args, flag) != [wanted]: + mismatches.append('profile_settings') + for flag in ('--pack', '--native', '--gguf', '--mtp'): + if option_values(effective_args, flag): + mismatches.append('native_asset_mapping') + legacy_mtp = option_values(legacy_args, '--mtp') + legacy_native = option_values(legacy_args, '--native') + if legacy_mtp != [candidate.get('mtp_pack')]: + mismatches.append('mtp_asset_mapping') + if (len(legacy_native) != 1 or Path(legacy_native[0]).name != PINNED_NATIVE_SHARD or + Path(candidate['native_model']['source_dir']) != Path(legacy_native[0]).parent or + Path(candidate['native_model']['manifest']).name != PINNED_NATIVE_MANIFEST): + mismatches.append('model_selection') + except InvalidInput as error: + mismatches.append(error.args[0] if error.args and error.args[0] in { + 'legacy_model_arguments', 'duplicate_engine_option', 'engine_arguments', 'ple_arguments' + } else 'engine_arguments') + + if candidate.get('mtp_pack') not in [asset['directory'] for asset in candidate.get('assets', [])]: + mismatches.append('mtp_asset_mapping') + if context['legacy']['bind'] == '' or context['legacy']['log'] == '': + mismatches.append('service_context') + if candidate.get('api_key_file') is None: + mismatches.append('authentication_configuration') + # The candidate's strict schema is checked, but source pack/MTP contents and + # credentials are intentionally not opened by this preflight. + return { + 'status': 'mismatch' if mismatches else 'incomplete' if unverified else 'verified', + 'mismatches': sorted(set(mismatches)), + 'unverified': sorted(set(unverified)), + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--legacy-config', required=True, + help='operator-supplied redacted projection (exe/args/cwd/log only; never the original file or api_key)') + parser.add_argument('--candidate-config', required=True) + parser.add_argument('--service-context', required=True) + parser.add_argument('--archive', required=True) + parser.add_argument('--archive-sha256', required=True) + parser.add_argument('--expected-executable', required=True) + parser.add_argument('--expected-bind', required=True) + parser.add_argument('--expected-log', required=True) + args = parser.parse_args(argv) + try: + result = compare(read_json(args.legacy_config), read_json(args.candidate_config), + read_json(args.service_context), args.archive, args.archive_sha256, + args.expected_executable, args.expected_bind, args.expected_log) + except InvalidInput as error: + result = {'status': 'mismatch', 'mismatches': [error.args[0]], 'unverified': sorted(UNVERIFIED)} + except Exception: + result = {'status': 'mismatch', 'mismatches': ['internal_validation_error'], + 'unverified': sorted(UNVERIFIED)} + print(json.dumps(result, sort_keys=True)) + return {'verified': 0, 'mismatch': 1, 'incomplete': 2}[result['status']] + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/test-ple-config-parity.py b/scripts/test-ple-config-parity.py new file mode 100644 index 00000000..95d98812 --- /dev/null +++ b/scripts/test-ple-config-parity.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Synthetic, offline tests for the secret-safe PLE parity preflight.""" +import importlib.util +import hashlib +import io +import json +from pathlib import Path +import tempfile +import unittest +from contextlib import redirect_stdout +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('parity', Path(__file__).with_name('check-ple-config-parity.py')) +parity = importlib.util.module_from_spec(spec) +spec.loader.exec_module(parity) + + +class ParityTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.archive = self.root / 'synthetic.kar' + self.archive.write_bytes(b'synthetic archive bytes') + self.archive_sha = hashlib.sha256(self.archive.read_bytes()).hexdigest() + self.legacy_args = [ + '--pack', '/models/current-pack', '--native', + '/models/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf', + '--max-context', '262144', '--kv', 'int8', '--kv-resident', '32768', + '--spec', '4', '--spec-min-p', '0.5', '--expert-cache', 'auto', + '--prefill', 'auto', '--vram-reserve-mib', '700', '--mtp', '/models/mtp-v1', + ] + self.candidate_executable = '/runtime/strata-next' + self.ple = ['--ple-kar', str(self.archive), '--ple-kar-level', '2', + '--ple-kar-gpu-cache-mib', '64'] + self.legacy = {'exe': '/legacy/strata', 'args': list(self.legacy_args), + 'cwd': '/srv/qwen', 'log': '/var/log/old-engine.log'} + self.candidate = { + 'bind': '127.0.0.1:18081', + 'api_key_file': str(self.root / 'unread-api-key'), + 'max_in_flight_requests': 1, + 'engine': {'executable': self.candidate_executable, + 'args': self.legacy_args_after_migration() + self.ple, + 'startup_timeout_s': 600, 'max_restarts': 0}, + 'native_model': {'manifest': '/fixtures/qwen3.8-flash-next-iq3-s.json', + 'source_dir': '/models', 'output': '/models/new-pack', + 'runtime_profile': 'qwen4exp-flash-next'}, + 'assets': [{'manifest': '/fixtures/mtp-manifest.json', + 'directory': '/models/mtp-v1'}], + 'mtp_pack': '/models/mtp-v1', + } + self.context = { + 'legacy': {'bind': '192.168.1.196:18081', 'cwd': '/srv/qwen', + 'log': '/var/log/old-engine.log', 'effective_slots': 1, + 'environment': {}}, + 'candidate': {'bind': '127.0.0.1:18081', 'cwd': '/srv/qwen', + 'log': 'systemd-journal', 'effective_slots': 1, + 'environment': {}}, + 'environment_complete': True, + } + self.expected_sha = parity.PINNED_ARCHIVE_SHA256 + + def legacy_args_after_migration(self): + result = [] + skip = False + for token in self.legacy_args: + if skip: + skip = False + elif token in {'--pack', '--native', '--mtp'}: + skip = True + else: + result.append(token) + return result + + def run_compare(self, *, legacy=None, candidate=None, context=None): + with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha): + return parity.compare(legacy or self.legacy, candidate or self.candidate, + context or self.context, self.archive, self.archive_sha, + self.candidate_executable, '127.0.0.1:18081', 'systemd-journal') + + def test_baseline_to_gpu_ple_is_incomplete_not_full_pass(self): + result = self.run_compare() + self.assertEqual(result['status'], 'incomplete') + self.assertEqual(result['mismatches'], []) + self.assertEqual(set(result['unverified']), parity.UNVERIFIED) + self.assertIn('request_model_identity', result['unverified']) + + def test_already_ple_selected_in_original_is_preserved_exactly(self): + legacy = json.loads(json.dumps(self.legacy)) + legacy['args'] += self.ple + candidate = json.loads(json.dumps(self.candidate)) + candidate['engine']['args'] = self.legacy_args_after_migration() + self.ple + self.assertEqual(self.run_compare(legacy=legacy, candidate=candidate)['mismatches'], []) + + def test_partial_duplicate_changed_or_reordered_ple_fails(self): + cases = [ + self.ple[:-2], + self.ple + self.ple, + ['--ple-kar', str(self.archive), '--ple-kar-level', '3', '--ple-kar-gpu-cache-mib', '64'], + ['--ple-kar-level', '2', '--ple-kar', str(self.archive), '--ple-kar-gpu-cache-mib', '64'], + ] + for flags in cases: + with self.subTest(flags=flags): + legacy = json.loads(json.dumps(self.legacy)) + legacy['args'] += flags + result = self.run_compare(legacy=legacy) + self.assertIn('ple_arguments', result['mismatches']) + + def test_malformed_candidate_ple_tuple_is_rejected(self): + cases = [ + self.ple[:-2], + self.ple + self.ple, + ['--ple-kar', str(self.archive), '--ple-kar-level', '1', + '--ple-kar-gpu-cache-mib', '64'], + ['--ple-kar-level', '2', '--ple-kar', str(self.archive), + '--ple-kar-gpu-cache-mib', '64'], + ] + for flags in cases: + with self.subTest(flags=flags): + candidate = json.loads(json.dumps(self.candidate)) + candidate['engine']['args'] = self.legacy_args_after_migration() + flags + result = self.run_compare(candidate=candidate) + self.assertIn('ple_arguments', result['mismatches']) + + def test_changes_to_non_ple_model_mtp_and_profile_settings_fail(self): + cases = [] + altered = json.loads(json.dumps(self.candidate)) + altered['engine']['args'][1] = '262143' + cases.append((altered, 'profile_settings')) + altered = json.loads(json.dumps(self.legacy)) + altered['args'][3] = '/models/Other-IQ3_S.gguf' + cases.append((altered, 'model_selection')) + altered = json.loads(json.dumps(self.candidate)) + altered['mtp_pack'] = '/models/mtp-other' + altered['assets'][0]['directory'] = '/models/mtp-other' + cases.append((altered, 'mtp_asset_mapping')) + altered = json.loads(json.dumps(self.candidate)) + altered['engine']['args'].insert(0, '--force') + altered['engine']['args'].insert(1, 'other') + cases.append((altered, 'engine_arguments')) + for value, expected in cases: + with self.subTest(expected=expected): + if expected in ('model_selection',): + result = self.run_compare(legacy=value) + else: + result = self.run_compare(candidate=value) + self.assertIn(expected, result['mismatches']) + + def test_every_retained_profile_setting_must_match_on_both_sides(self): + for flag, wanted in parity.REQUIRED_SETTINGS.items(): + with self.subTest(flag=flag, side='legacy'): + legacy = json.loads(json.dumps(self.legacy)) + index = legacy['args'].index(flag) + legacy['args'][index + 1] = f'{wanted}-changed' + self.assertIn('profile_settings', + self.run_compare(legacy=legacy)['mismatches']) + with self.subTest(flag=flag, side='candidate'): + candidate = json.loads(json.dumps(self.candidate)) + index = candidate['engine']['args'].index(flag) + candidate['engine']['args'][index + 1] = f'{wanted}-changed' + self.assertIn('profile_settings', + self.run_compare(candidate=candidate)['mismatches']) + + def test_service_context_requires_bind_workdir_log_and_one_slot(self): + for key, value in [('cwd', '/srv/other'), ('bind', '0.0.0.0:18081'), + ('log', '/tmp/other.log'), ('effective_slots', 2)]: + context = json.loads(json.dumps(self.context)) + context['candidate'][key] = value + result = self.run_compare(context=context) + expected = {'cwd': 'working_directory', 'bind': 'bind_selection', + 'log': 'log_selection', 'effective_slots': 'slot_count'}[key] + self.assertIn(expected, result['mismatches']) + context = json.loads(json.dumps(self.context)) + context['environment_complete'] = False + self.assertIn('effective_environment', self.run_compare(context=context)['unverified']) + for side in ('legacy', 'candidate'): + context = json.loads(json.dumps(self.context)) + context[side].pop('effective_slots') + result = self.run_compare(context=context) + self.assertNotIn('slot_count', result['mismatches']) + self.assertIn('worker_slot_count', result['unverified']) + + def test_only_declared_bind_and_executable_environment_deltas_are_allowed(self): + context = json.loads(json.dumps(self.context)) + context['candidate']['environment'] = { + 'STRATA_BIND': '127.0.0.1:18081', + 'STRATA_ENGINE_EXE': self.candidate_executable, + } + self.assertEqual(self.run_compare(context=context)['mismatches'], []) + context['candidate']['environment']['CUDA_VISIBLE_DEVICES'] = '1' + self.assertIn('environment_delta', self.run_compare(context=context)['mismatches']) + + def test_http_request_capacity_is_not_confused_with_worker_slot_count(self): + candidate = json.loads(json.dumps(self.candidate)) + candidate.pop('max_in_flight_requests') + result = self.run_compare(candidate=candidate) + self.assertNotIn('slot_count', result['mismatches']) + self.assertIn('http_capacity_policy', result['unverified']) + + def test_archive_bytes_are_stream_checked_against_pin(self): + with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha): + parity.check_archive(self.archive, self.archive_sha) + self.archive.write_bytes(b'corrupted fixture') + with self.assertRaisesRegex(parity.InvalidInput, 'archive_digest'): + parity.check_archive(self.archive, self.archive_sha) + with self.assertRaisesRegex(parity.InvalidInput, 'archive_pin'): + parity.check_archive(self.archive, '0' * 64) + + def test_strict_json_rejects_duplicates_constants_invalid_utf8_and_nonobject(self): + path = self.root / 'config.json' + for raw in (b'{"x":1,"x":2}', b'{"x":NaN}', b'\xff', b'[]'): + with self.subTest(raw=raw): + path.write_bytes(raw) + with self.assertRaises(parity.InvalidInput): + value = parity.read_json(path) + parity.validate_legacy(value) + + def test_unknown_legacy_and_native_keys_are_rejected(self): + legacy = dict(self.legacy, future_secret_setting='opaque') + with self.assertRaisesRegex(parity.InvalidInput, 'legacy_schema'): + parity.validate_legacy(legacy) + with self.assertRaisesRegex(parity.InvalidInput, 'legacy_credential_present'): + parity.validate_legacy(dict(self.legacy, api_key='must-not-be-read')) + candidate = json.loads(json.dumps(self.candidate)) + candidate['future_runtime_setting'] = True + with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'): + parity.validate_candidate(candidate) + candidate = json.loads(json.dumps(self.candidate)) + candidate['engine']['future_runtime_setting'] = True + with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'): + parity.validate_candidate(candidate) + + def test_candidate_secret_file_is_not_opened_and_output_never_contains_secret(self): + secret_path = Path(self.candidate['api_key_file']) + secret_path.write_text('synthetic-secret-do-not-print') + original_open = Path.open + + def guarded_open(path, *args, **kwargs): + if path == secret_path: + raise AssertionError('secret file must not be opened') + return original_open(path, *args, **kwargs) + + with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), \ + patch.object(Path, 'open', guarded_open): + output = parity.compare(self.legacy, self.candidate, self.context, self.archive, + self.archive_sha, self.candidate_executable, + '127.0.0.1:18081', 'systemd-journal') + encoded = json.dumps(output) + self.assertNotIn('synthetic-secret', encoded) + self.assertEqual(output['status'], 'incomplete') + + def test_cli_prints_safe_json_and_returns_two_for_positive_incomplete_fixture(self): + legacy_path = self.root / 'legacy.json' + candidate_path = self.root / 'candidate.json' + context_path = self.root / 'context.json' + for path, value in ((legacy_path, self.legacy), (candidate_path, self.candidate), + (context_path, self.context)): + path.write_text(json.dumps(value)) + stdout = io.StringIO() + argv = ['--legacy-config', str(legacy_path), '--candidate-config', str(candidate_path), + '--service-context', str(context_path), '--archive', str(self.archive), + '--archive-sha256', self.archive_sha, '--expected-executable', self.candidate_executable, + '--expected-bind', '127.0.0.1:18081', '--expected-log', 'systemd-journal'] + with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), redirect_stdout(stdout): + result = parity.main(argv) + self.assertEqual(result, 2) + self.assertNotIn('synthetic-secret', stdout.getvalue()) + self.assertNotIn(str(self.root), stdout.getvalue()) + self.assertEqual(json.loads(stdout.getvalue())['status'], 'incomplete') + + +if __name__ == '__main__': + unittest.main() -- 2.54.0 From b9519f967af43514331e29e778bd2605d8e4b98b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 8 Oct 2026 01:26:32 +0200 Subject: [PATCH 8/8] Harden config parity input file handling --- scripts/check-ple-config-parity.py | 77 ++++++++++++++++++++------- scripts/test-ple-config-parity.py | 84 ++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 18 deletions(-) diff --git a/scripts/check-ple-config-parity.py b/scripts/check-ple-config-parity.py index 224fcb03..2d266d74 100755 --- a/scripts/check-ple-config-parity.py +++ b/scripts/check-ple-config-parity.py @@ -12,7 +12,9 @@ is rejected with a static category after parsing and must not be supplied. import argparse import hashlib import json +import os import re +import stat import sys from pathlib import Path @@ -22,6 +24,8 @@ PINNED_NATIVE_SHARD = 'Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf' PINNED_NATIVE_MANIFEST = 'qwen3.8-flash-next-iq3-s.json' MAX_JSON_BYTES = 1024 * 1024 MAX_ARCHIVE_BYTES = 100 * 1024**3 +MAX_ASSET_BUNDLES = 16 +U64_MAX = (1 << 64) - 1 LEGACY_KEYS = {'exe', 'args', 'cwd', 'log'} FILE_CONFIG_KEYS = { 'queue_timeout_s', 'mtp_pack', 'response_history_dir', 'assets', @@ -76,7 +80,9 @@ def _constant(_value): def read_json(path): try: - with Path(path).open('rb') as stream: + with open_regular(path, 'invalid_json') as stream: + if os.fstat(stream.fileno()).st_size > MAX_JSON_BYTES: + raise InvalidInput('json_size_limit') data = stream.read(MAX_JSON_BYTES + 1) if len(data) > MAX_JSON_BYTES: raise InvalidInput('json_size_limit') @@ -84,10 +90,38 @@ def read_json(path): parse_constant=_constant) except InvalidInput: raise - except (OSError, UnicodeError, json.JSONDecodeError): + except (OSError, UnicodeError, json.JSONDecodeError, RecursionError, OverflowError): raise InvalidInput('invalid_json') from None +def open_regular(path, category): + # O_NOFOLLOW and O_NONBLOCK are required together: never fall back to + # following a symlink or waiting for a FIFO on unsupported platforms. + if not hasattr(os, 'O_NOFOLLOW') or not hasattr(os, 'O_NONBLOCK'): + raise InvalidInput('safe_file_open_unavailable') + flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK + if hasattr(os, 'O_CLOEXEC'): + flags |= os.O_CLOEXEC + try: + fd = os.open(os.fspath(path), flags) + except (OSError, TypeError, ValueError): + raise InvalidInput(category) from None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise InvalidInput(category) + return os.fdopen(fd, 'rb') + except BaseException as error: + try: + os.close(fd) + except OSError: + pass + if isinstance(error, InvalidInput): + raise + if isinstance(error, OSError): + raise InvalidInput(category) from None + raise + + def _keys(value, allowed, category): if not isinstance(value, dict) or not set(value).issubset(allowed): raise InvalidInput(category) @@ -135,7 +169,8 @@ def validate_candidate(value): if not _string(value['native_model'].get(key)): raise InvalidInput('candidate_schema') assets = value.get('assets', []) - if not isinstance(assets, list) or not all(isinstance(asset, dict) for asset in assets): + if (not isinstance(assets, list) or len(assets) > MAX_ASSET_BUNDLES or + not all(isinstance(asset, dict) for asset in assets)): raise InvalidInput('candidate_schema') for asset in assets: _keys(asset, ASSET_KEYS, 'candidate_schema') @@ -145,8 +180,9 @@ def validate_candidate(value): _keys(value['cuda_memory'], CUDA_MEMORY_KEYS, 'candidate_schema') if set(value['cuda_memory']) != CUDA_MEMORY_KEYS: raise InvalidInput('candidate_schema') - if any(type(value['cuda_memory'][key]) is not int or value['cuda_memory'][key] <= 0 - for key in CUDA_MEMORY_KEYS): + required, reserve = (value['cuda_memory'][key] for key in ('required_mib', 'reserve_mib')) + if (type(required) is not int or type(reserve) is not int or required <= 0 or reserve < 0 or + required > U64_MAX or reserve > U64_MAX or required + reserve > U64_MAX): raise InvalidInput('candidate_schema') if 'gpu_requirement' in value and value['gpu_requirement'] != 'cuda-13.0-linux': raise InvalidInput('candidate_schema') @@ -160,7 +196,7 @@ def validate_candidate(value): not 0 <= value['shutdown_grace_s'] <= 20): raise InvalidInput('candidate_schema') if 'max_in_flight_requests' in value and (type(value['max_in_flight_requests']) is not int or - value['max_in_flight_requests'] <= 0): + not 1 <= value['max_in_flight_requests'] <= 256): raise InvalidInput('candidate_schema') if 'engine_probe' in value and type(value['engine_probe']) is not bool: raise InvalidInput('candidate_schema') @@ -250,24 +286,29 @@ def check_archive(path, expected): if not re.fullmatch(r'[0-9a-f]{64}', expected) or expected != PINNED_ARCHIVE_SHA256: raise InvalidInput('archive_pin') try: - if Path(path).is_symlink() or not Path(path).is_file(): - raise InvalidInput('archive_file') - digest = hashlib.sha256() - size = 0 - with Path(path).open('rb') as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b''): - size += len(chunk) - if size > MAX_ARCHIVE_BYTES: - raise InvalidInput('archive_size_limit') - digest.update(chunk) - if digest.hexdigest() != expected: - raise InvalidInput('archive_digest') + stream = open_regular(path, 'archive_file') + with stream: + if os.fstat(stream.fileno()).st_size > MAX_ARCHIVE_BYTES: + raise InvalidInput('archive_size_limit') + _verify_archive_stream(stream, expected) except InvalidInput: raise except OSError: raise InvalidInput('archive_file') from None +def _verify_archive_stream(stream, expected): + digest = hashlib.sha256() + size = 0 + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + size += len(chunk) + if size > MAX_ARCHIVE_BYTES: + raise InvalidInput('archive_size_limit') + digest.update(chunk) + if digest.hexdigest() != expected: + raise InvalidInput('archive_digest') + + def compare(legacy, candidate, context, archive_path, archive_sha, expected_executable, expected_bind, expected_log): validate_legacy(legacy) diff --git a/scripts/test-ple-config-parity.py b/scripts/test-ple-config-parity.py index 95d98812..512e6a3b 100644 --- a/scripts/test-ple-config-parity.py +++ b/scripts/test-ple-config-parity.py @@ -4,7 +4,10 @@ import importlib.util import hashlib import io import json +import os from pathlib import Path +import subprocess +import sys import tempfile import unittest from contextlib import redirect_stdout @@ -215,6 +218,87 @@ class ParityTests(unittest.TestCase): value = parity.read_json(path) parity.validate_legacy(value) + def test_json_parser_recursion_and_overflow_errors_are_bounded(self): + path = self.root / 'nested.json' + path.write_text('{}') + for error in (RecursionError, OverflowError): + with self.subTest(error=error.__name__): + with patch.object(parity.json, 'loads', side_effect=error): + with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'): + parity.read_json(path) + + def test_safe_file_open_accepts_regular_files_and_rejects_symlinks(self): + config = self.root / 'regular.json' + config.write_text('{}') + self.assertEqual(parity.read_json(config), {}) + config_link = self.root / 'config-link.json' + config_link.symlink_to(config) + with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'): + parity.read_json(config_link) + + archive_link = self.root / 'archive-link.kar' + archive_link.symlink_to(self.archive) + with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha): + with self.assertRaisesRegex(parity.InvalidInput, 'archive_file'): + parity.check_archive(archive_link, self.archive_sha) + + @unittest.skipUnless(hasattr(os, 'mkfifo'), 'named FIFO unavailable') + def test_named_fifo_is_rejected_quickly_for_json_and_archive(self): + fifo = self.root / 'input.fifo' + os.mkfifo(fifo) + module_path = Path(__file__).with_name('check-ple-config-parity.py') + code = ( + "import importlib.util,sys; " + "s=importlib.util.spec_from_file_location('p',sys.argv[1]); " + "m=importlib.util.module_from_spec(s); s.loader.exec_module(m); " + "\ntry:\n" + " if sys.argv[3]=='json': m.read_json(sys.argv[2])\n" + " else: m.check_archive(sys.argv[2],m.PINNED_ARCHIVE_SHA256)\n" + "except m.InvalidInput: pass\nelse: raise SystemExit(9)" + ) + for kind in ('json', 'archive'): + with self.subTest(kind=kind): + result = subprocess.run( + [sys.executable, '-c', code, str(module_path), str(fifo), kind], + capture_output=True, text=True, timeout=2) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_nonregular_open_failure_closes_the_descriptor(self): + opened = [] + real_open = os.open + + def capture(path, flags): + fd = real_open(path, flags) + opened.append(fd) + return fd + + with patch.object(parity.os, 'open', capture): + with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'): + parity.open_regular(self.root, 'invalid_json') + self.assertEqual(len(opened), 1) + with self.assertRaises(OSError): + os.fstat(opened[0]) + + def test_candidate_resource_limits_match_runtime_bounds(self): + cases = [] + candidate = json.loads(json.dumps(self.candidate)) + candidate['max_in_flight_requests'] = 257 + cases.append(candidate) + candidate = json.loads(json.dumps(self.candidate)) + candidate['assets'] = [{'manifest': f'/m/{i}', 'directory': f'/a/{i}'} + for i in range(parity.MAX_ASSET_BUNDLES + 1)] + cases.append(candidate) + for memory in ({'required_mib': parity.U64_MAX + 1, 'reserve_mib': 0}, + {'required_mib': parity.U64_MAX, 'reserve_mib': 1}, + {'required_mib': 1, 'reserve_mib': -1}): + candidate = json.loads(json.dumps(self.candidate)) + candidate['cuda_memory'] = memory + cases.append(candidate) + for candidate in cases: + with self.subTest(candidate=candidate): + with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'): + parity.validate_candidate(candidate) + def test_unknown_legacy_and_native_keys_are_rejected(self): legacy = dict(self.legacy, future_secret_setting='opaque') with self.assertRaisesRegex(parity.InvalidInput, 'legacy_schema'): -- 2.54.0