diff --git a/deploy/README.md b/deploy/README.md index 0267e867..e3964ae9 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -63,8 +63,38 @@ systemctl --user daemon-reload The service is not enabled at login/boot by these instructions. A running user manager is required. The existing trial endpoint remains externally launched; -this feature does not migrate it or add managed `qwen-codex-ctl start/stop` yet. -Use the existing `connect strata-native` command once the service is ready. +these instructions do not migrate it. Use the existing `connect strata-native` +command once a provisioned service is ready. + +### Console controller + +Install the opt-in controller commands on the laptop after the native Responses +launcher integration (the installer preserves the selected connection): + +```sh +python3 scripts/install-qwen-native.py +python3 scripts/install-qwen-native-service.py +qwen-codex-ctl native-service status --host rnr5090 --unit strata-next.service +qwen-codex-ctl native-service start --host rnr5090 --unit strata-next.service +qwen-codex-ctl native-service logs --host rnr5090 --unit strata-next.service +qwen-codex-ctl native-service stop --host rnr5090 --unit strata-next.service +``` + +These operate on an **already provisioned** systemd user unit through SSH; +they never install, enable, migrate or switch a model. The host defaults to the +launcher's configured SSH alias, and the unit to `strata-next.service`. Optional +unit names must follow `strata-next-NAME.service`. Start/stop are idempotent; +SSH calls time out after 90 seconds. Logs show the selected unit's last 100 +entries. No service credentials are copied or stored by this helper. + +The JSON status describes the **process**; `model_readiness: not_checked` is +explicit. Model initialization can continue after process startup. The separate +`qwen-codex-ctl connect strata-native --url http://127.0.0.1:18084 --no-auth` +checks inference readiness through the existing SSH tunnel before switching +the console connection. Tunnel setup remains separate. The existing plain +`start/stop` commands retain their previous behavior; use `native-service` +explicitly for a managed native unit. The currently running external trial +has no such unit, so these commands safely report it as not provisioned. Verification without GPU inference: diff --git a/docs/build-validation.md b/docs/build-validation.md index 1fa2122e..5054454e 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -515,3 +515,26 @@ soak still remain; hosted Actions has not run. GPU shutdown under a systemd-managed service and login/boot persistence have not been qualified by this CPU-only smoke. Instructions are in [deployment](../deploy/README.md#native-linux-service-lifecycle). + +## Console service control — 2026-10-04 + +- STRA-16 adds explicit `qwen-codex-ctl native-service start/stop/status/logs` + for a named systemd user unit over SSH. It does not select a model, provision + a unit, create a tunnel, or infer model readiness from process state. +- Seven focused Python checks passed: idempotent operations, selector rejection + before SSH, missing/invalid status, bounded unit-specific logs, installer + backup/idempotence/profile preservation and refusal to overwrite an unrelated + helper. The test is included in `scripts/check-local.sh` for future Linux CI. +- The installed real controller completed status/start/start/status/logs/stop/ + stop/status against `strata-next-controller-smoke-20261004.service` on + rnr5090. This isolated CPU-only native service reported the expected model + identity via HTTP and correctly remained unready without an engine. The + second start and second stop reported `changed: false`. The normal default + `strata-next.service` was absent and was not created by a status call. +- The laptop integration is installed with a private backup; the normal + connection remains unchanged. This is client-side Python only; inference + still runs directly through Rust and the existing engine. +- Real GPU service migration, managed GPU stop during active generation and + login/boot persistence remain unqualified. The external trial endpoint is + preserved; these commands do not adopt it. Raw smoke results are private in + `~/.cache/strata-next/native-console-20261004/controller-service-quality.json`. diff --git a/scripts/check-local.sh b/scripts/check-local.sh index f69c8e02..71eb5b5b 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -5,6 +5,7 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" python3 "${repo_root}/scripts/test-benchmark-harness.py" +python3 "${repo_root}/scripts/test-native-service.py" python3 "${repo_root}/scripts/test-keyless-routing.py" cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check diff --git a/scripts/install-qwen-native-service.py b/scripts/install-qwen-native-service.py new file mode 100644 index 00000000..b8c55317 --- /dev/null +++ b/scripts/install-qwen-native-service.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Install opt-in native-service commands after install-qwen-native.py. + +Keeps the selected connection unchanged and backs up the launcher before patching. +""" +import argparse +import ast +import hashlib +import os +from pathlib import Path +import tempfile + +MARKER = '# Strata Next native service integration v1' +HELPER_MARKER = '# Strata Next native service client v1' + + +def patched(original): + if MARKER in original: + return original + if '# Strata Next native Responses integration v1' not in original: + raise RuntimeError('Install native Responses first with scripts/install-qwen-native.py') + anchors = { + 'def ctl_main():\n': '''def ctl_main(): + if len(sys.argv) > 1 and sys.argv[1] == 'native-service': + from qwen_native_service import main as native_service_main + return native_service_main(sys.argv[2:], default_host=HOST) +''', + " sub = parser.add_subparsers(dest='command', required=True)\n": + " sub = parser.add_subparsers(dest='command', required=True)\n" + " sub.add_parser('native-service', help='керувати явним native systemd user service через SSH')\n", + } + text = original + for old, new in anchors.items(): + if text.count(old) != 1: + raise RuntimeError('Launcher changed: expected exactly one native-service anchor') + text = text.replace(old, new) + text += '\n' + MARKER + '\n' + ast.parse(text) + return text + + +def atomic(path, text, mode): + fd, temporary = tempfile.mkstemp(prefix='native-service-', dir=path.parent) + try: + with os.fdopen(fd, 'w') as output: + output.write(text) + os.chmod(temporary, mode) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def install(path): + os.umask(0o077) + original = path.read_text() + text = patched(original) + source = Path(__file__).with_name('qwen_native_service.py').read_text() + ast.parse(source) + target = path.with_name('qwen_native_service.py') + if target.exists() and HELPER_MARKER not in target.read_text(): + raise RuntimeError('Refusing to overwrite an unrelated qwen_native_service.py') + backup = path.with_name(path.name + '.before-native-service-' + hashlib.sha256(original.encode()).hexdigest()[:12]) + if text != original and not backup.exists(): + with backup.open('x') as output: + output.write(original) + if not target.exists() or target.read_text() != source: + atomic(target, source, 0o600) + if path.read_text() != original: + raise RuntimeError('Launcher changed during installation; retry against the current file') + if text != original: + atomic(path, text, path.stat().st_mode & 0o777) + print('Native service commands installed; connection unchanged') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--path', type=Path, default=Path.home()/'.local/share/codex-qwen/qwen_local.py') + install(parser.parse_args().path) diff --git a/scripts/qwen_native_service.py b/scripts/qwen_native_service.py new file mode 100644 index 00000000..1ec2b59e --- /dev/null +++ b/scripts/qwen_native_service.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +# Strata Next native service client v1 +"""Explicit client-side systemd control over SSH; no inference serving code.""" +import argparse +import json +import re +import shlex +import subprocess + +PROPERTIES = ('LoadState', 'ActiveState', 'SubState', 'MainPID', 'Result') + + +def validate(host, unit): + # SSH aliases/DNS names only. Refuse options, user overrides and shell text. + if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,252}', host): + raise ValueError('host must be an SSH alias or DNS name without options or a username') + if not re.fullmatch(r'strata-next(?:-[a-z0-9][a-z0-9-]{0,79})?\.service', unit): + raise ValueError('unit must be strata-next.service or strata-next-NAME.service') + + +def ssh(host, arguments): + result = subprocess.run( + ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '--', host, + shlex.join(arguments)], + text=True, capture_output=True, timeout=90, + ) + if result.returncode: + raise RuntimeError('Native service SSH command failed: ' + result.stderr[-1500:].strip()) + return result.stdout + + +def control(action, host, unit, *, runner=ssh): + validate(host, unit) + if action not in {'start', 'stop', 'status', 'logs'}: + raise ValueError('unsupported native service action') + + def state(): + text = runner(host, ['systemctl', '--user', 'show', + *['--property=' + p for p in PROPERTIES], '--', unit]) + result = dict(line.split('=', 1) for line in text.splitlines() if '=' in line) + if result.get('LoadState') != 'loaded': + raise RuntimeError('Native unit is not loaded; provision the user service first: ' + unit) + if (result.get('ActiveState') not in {'active', 'inactive', 'failed', 'activating', + 'deactivating', 'reloading', 'maintenance', 'refreshing'} + or not result.get('MainPID', '').isascii() + or not result.get('MainPID', '').isdigit()): + raise RuntimeError('Incomplete or invalid native service status') + return {key: result.get(key, '') for key in PROPERTIES} + + before = state() + if action == 'logs': + return runner(host, ['journalctl', '--user', '--unit=' + unit, '--lines=100', + '--no-pager', '--output=short-iso']) + changed = False + if ((action == 'start' and before['ActiveState'] not in {'active', 'activating'}) + or (action == 'stop' and before['ActiveState'] != 'inactive')): + runner(host, ['systemctl', '--user', action, '--', unit]) + changed = True + after = state() if changed else before + if action == 'start' and after['ActiveState'] not in {'active', 'activating'}: + raise RuntimeError('Native service failed to start: ' + after['ActiveState']) + if action == 'stop' and after['ActiveState'] != 'inactive': + raise RuntimeError('Native service did not stop: ' + after['ActiveState']) + return {'host': host, 'unit': unit, 'action': action, 'changed': changed, + 'process': after, 'model_readiness': 'not_checked', + 'connection_changed': False} + + +def main(argv=None, *, default_host='rnr5090'): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('start', 'stop', 'status', 'logs')) + parser.add_argument('--host', default=default_host, help='existing SSH alias; no credentials are copied') + parser.add_argument('--unit', default='strata-next.service') + args = parser.parse_args(argv) + result = control(args.action, args.host, args.unit) + print(result if isinstance(result, str) else json.dumps(result, ensure_ascii=False), end='\n') + + +if __name__ == '__main__': + main() diff --git a/scripts/test-native-service.py b/scripts/test-native-service.py new file mode 100644 index 00000000..2e46e6dd --- /dev/null +++ b/scripts/test-native-service.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Behavior checks for opt-in native service control; never contact a real host.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + +import qwen_native_service as client + +spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-qwen-native-service.py')) +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) + + +class FakeHost: + def __init__(self): + self.active = False + self.calls = [] + self.loaded = True + + def __call__(self, host, command): + self.calls.append((host, command)) + if command[0] == 'journalctl': + return 'fixture log\n' + action = command[2] + if action == 'show': + return ('LoadState=' + ('loaded' if self.loaded else 'not-found') + '\n' + 'ActiveState=' + ('active' if self.active else 'inactive') + '\n' + 'SubState=' + ('running' if self.active else 'dead') + '\n' + 'MainPID=' + ('123' if self.active else '0') + '\nResult=success\n' + 'Environment=must-not-be-returned\n') + if action in {'start', 'stop'}: + self.active = action == 'start' + return '' + raise AssertionError(command) + + +class ControlTests(unittest.TestCase): + def test_idempotent_start_stop_and_readiness_is_not_inferred(self): + host = FakeHost() + def call(action): + return client.control(action, 'rnr5090', 'strata-next-test.service', runner=host) + self.assertFalse(call('status')['changed']) + self.assertTrue(call('start')['changed']) + again = call('start') + self.assertFalse(again['changed']) + self.assertEqual(again['model_readiness'], 'not_checked') + self.assertFalse(again['connection_changed']) + self.assertNotIn('Environment', again['process']) + self.assertTrue(call('stop')['changed']) + self.assertFalse(call('stop')['changed']) + mutations = [args for _, args in host.calls if args[2] in {'start', 'stop'}] + self.assertEqual([args[2] for args in mutations], ['start', 'stop']) + self.assertTrue(all(args[-2:] == ['--', 'strata-next-test.service'] for args in mutations)) + + def test_rejected_selectors_never_reach_ssh(self): + host = FakeHost() + for bad in ['-oProxyCommand=x', 'host;id', 'host\nother', 'user@host', 'host name']: + with self.assertRaises(ValueError): + client.control('start', bad, 'strata-next.service', runner=host) + for bad in ['sshd.service', 'strata-next.service;id', '../strata-next.service', 'strata-next@a.service']: + with self.assertRaises(ValueError): + client.control('stop', 'rnr5090', bad, runner=host) + self.assertEqual(host.calls, []) + + def test_missing_service_is_not_created_or_started(self): + host = FakeHost() + host.loaded = False + with self.assertRaisesRegex(RuntimeError, 'provision'): + client.control('start', 'rnr5090', 'strata-next.service', runner=host) + self.assertEqual(len(host.calls), 1) + self.assertEqual(host.calls[0][1][2], 'show') + + def test_invalid_status_fails_closed(self): + with self.assertRaisesRegex(RuntimeError, 'invalid'): + client.control('start', 'rnr5090', 'strata-next.service', + runner=lambda *_: 'LoadState=loaded\nActiveState=active\nMainPID=oops') + + def test_logs_are_scoped_and_bounded(self): + host = FakeHost() + self.assertEqual(client.control('logs', 'rnr5090', 'strata-next-test.service', runner=host), 'fixture log\n') + self.assertEqual(host.calls[-1][1], ['journalctl', '--user', '--unit=strata-next-test.service', + '--lines=100', '--no-pager', '--output=short-iso']) + + +class InstallerTests(unittest.TestCase): + SOURCE = '''import argparse, sys +HOST = 'fixture' +def ctl_main(): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest='command', required=True) + sub.add_parser('status') +# Strata Next native Responses integration v1 +''' + + def test_install_reinstall_backup_and_no_profile_write(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + launcher = root / 'qwen_local.py' + launcher.write_text(self.SOURCE) + connection = root / 'connection.json' + connection.write_text('{"untouched":true}') + installer.install(launcher) + first = launcher.read_bytes() + installer.install(launcher) + self.assertEqual(launcher.read_bytes(), first) + self.assertEqual(connection.read_text(), '{"untouched":true}') + backups = list(root.glob('qwen_local.py.before-native-service-*')) + self.assertEqual(len(backups), 1) + self.assertEqual(backups[0].read_text(), self.SOURCE) + self.assertTrue((root / 'qwen_native_service.py').is_file()) + + def test_changed_launcher_or_unrelated_helper_is_preserved(self): + with self.assertRaises(RuntimeError): + installer.patched(self.SOURCE.replace('def ctl_main():', 'def different():')) + with self.assertRaises(RuntimeError): + installer.patched('unrelated launcher') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + launcher = root / 'qwen_local.py' + launcher.write_text(self.SOURCE) + (root / 'qwen_native_service.py').write_text('unrelated helper') + with self.assertRaises(RuntimeError): + installer.install(launcher) + self.assertEqual(launcher.read_text(), self.SOURCE) + + +if __name__ == '__main__': + unittest.main()