Expose native API lifecycle and metrics through qwen controller

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 06:11:14 +02:00
parent 833b13b111
commit 844f50ecea
6 changed files with 489 additions and 0 deletions
+41
View File
@@ -98,6 +98,47 @@ the console connection. Tunnel setup remains separate. The existing plain
explicitly for a managed native unit. The currently running external trial
has no such unit, so these commands safely report it as not provisioned.
### Native API commands in the console controller
Install the API helper after the native launcher integration:
```sh
python3 scripts/install-qwen-native-api.py
qwen-codex-ctl native-api status
qwen-codex-ctl native-api metrics
qwen-codex-ctl native-api lifecycle
qwen-codex-ctl native-api drain --wait 60
# Explicitly reopen admission when maintenance is abandoned or complete:
qwen-codex-ctl native-api resume
```
These use the selected `strata-native` connection and its private key file.
An explicit URL requires an explicit authentication choice and does not change
the selected connection:
```sh
qwen-codex-ctl native-api status --url http://127.0.0.1:18084 --no-auth
qwen-codex-ctl native-api metrics --url http://127.0.0.1:18084 --key-file /private/path/api.key
```
The helper verifies native `/status` identity before any admission mutation.
It uses direct loopback HTTP, ignoring proxy environment variables, refuses
redirects, and bounds each JSON response to 64 KiB. Socket operations time out
after eight seconds; this is not a hard total deadline for a server that keeps
sending partial bytes. Credentials are never command-line token arguments.
`drain --wait SECONDS` polls lifecycle for up to the requested interval (0–3600
seconds, subject to in-flight HTTP I/O). Without a positive wait it returns the
initial snapshot. Timeout, interruption or a concurrent resume produces an
error; the client never automatically stops or resumes the runtime. Inspect
lifecycle after any uncertain mutation result. Serialize operator actions.
No service, SSH tunnel or model is created or switched by these commands.
The retained GPU trial supports `native-api status`; metrics and admission
controls require the newer feature preview and return HTTP 404 on that older
trial. The helper does not upgrade a runtime automatically. Client Python is
part of the existing laptop harness; native production serving remains Rust.
Verification without GPU inference:
```sh
+30
View File
@@ -660,3 +660,33 @@ soak still remain; hosted Actions has not run.
to that trial. Independent QA, GPU maintenance and soak qualification remain.
Drain has no forced timeout or persistence across control-plane restarts;
exact operator semantics are documented in `deploy/README.md`.
## Native API console control — 2026-10-04
- STRA-21 adds `qwen-codex-ctl native-api` commands for status, metrics,
lifecycle, drain and resume, including optional drain waiting. The installer
backs up the launcher and preserves its selected connection. Explicit URL
overrides require explicit authentication and never inherit another target's
key. API identity is checked before admission mutations. There is no automatic
service stop, resume, model switch or tunnel management.
- Eight new Python behavior tests passed: invalid target rejection before I/O,
native identity before mutation, drain completion/timeout/concurrent resume,
response validation, auth selection, direct HTTP without proxy/redirect,
bounded responses and suppression of literal or escaped credential echoes,
installer idempotence and coexistence with native-service in both orders.
All seven existing native-service tests and the installed launcher auth test
passed. `check-local.sh` includes the new tests for future Linux CI; hosted
GitHub Actions have not run.
- Built the current macOS debug control plane and tested the actual installed
controller against an isolated authenticated CPU-only endpoint: all five
commands, repeated drain/resume, drain wait, selected-profile authentication,
explicit key override, and unauthorized mutation rejection passed. Temporary
server, key, config, profile and logs were removed. The normal user connection
was compared before/after and remained byte-identical. This checks console
integration, not model quality or GPU maintenance.
- Read-only `native-api status` succeeded through the preserved GPU tunnel.
PID 4031422/start ticks 558428413 remained unchanged. No inference or admin
mutation was sent to the user trial. Its older runtime still lacks metrics
and admin routes; the client reports unsupported HTTP responses explicitly.
Linux feature-preview binary remains unchanged from STRA-20. Independent QA
and a deliberate future managed GPU deployment remain pending.
+1
View File
@@ -6,6 +6,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-native-api.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Install opt-in native-api 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 API integration v1'
HELPER_MARKER = '# Strata Next native API client v1'
def patched(original):
if MARKER in original:
return original
if '# Strata Next native bearer file 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-api':
from qwen_native_api import main as native_api_main
return native_api_main(sys.argv[2:], connection=connection, read_key=native_key)
''',
" sub = parser.add_subparsers(dest='command', required=True)\n":
" sub = parser.add_subparsers(dest='command', required=True)\n"
" sub.add_parser('native-api', help='native API: status, metrics, lifecycle, drain та resume')\n",
}
text = original
for old, new in anchors.items():
if text.count(old) != 1:
raise RuntimeError('Launcher changed: expected exactly one native-api 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-api-', 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_api.py').read_text()
ast.parse(source)
target = path.with_name('qwen_native_api.py')
if target.exists() and HELPER_MARKER not in target.read_text():
raise RuntimeError('Refusing to overwrite an unrelated qwen_native_api.py')
backup = path.with_name(path.name + '.before-native-api-' + 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 API 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)
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
# Strata Next native API client v1
"""Console client for native runtime observation and admission maintenance."""
import argparse
import http.client
import json
import math
import time
from urllib.parse import urlsplit
ACTIONS = {'status': ('GET', '/status'), 'metrics': ('GET', '/metrics'),
'lifecycle': ('GET', '/admin/lifecycle'), 'drain': ('POST', '/admin/drain'),
'resume': ('POST', '/admin/resume')}
LIMIT = 65536
def endpoint(url):
if not isinstance(url, str) or not url or any(ord(c) <= 32 or ord(c) >= 127 for c in url):
raise ValueError('Native API URL must be plain ASCII without whitespace')
parsed = urlsplit(url)
if (parsed.scheme != 'http' or parsed.hostname not in {'127.0.0.1', 'localhost', '::1'}
or parsed.username is not None or parsed.password is not None
or parsed.path or parsed.query or parsed.fragment):
raise ValueError('Native API needs a plain loopback HTTP URL without credentials or path')
port = parsed.port if parsed.port is not None else 80
if not 1 <= port <= 65535:
raise ValueError('Native API port must be between 1 and 65535')
return ('127.0.0.1' if parsed.hostname == 'localhost' else parsed.hostname), port
def request(url, method, path, token, *, timeout=8):
host, port = endpoint(url)
headers = {'Accept': 'application/json'}
if token:
headers['Authorization'] = 'Bearer ' + token
conn = http.client.HTTPConnection(host, port, timeout=timeout)
try:
conn.request(method, path, headers=headers)
response = conn.getresponse()
if response.status != 200:
# Never follow a redirect or echo server error bodies/credentials.
raise RuntimeError(f'Native API returned HTTP {response.status}; check endpoint support and authentication')
if response.getheader('Content-Type', '').split(';')[0].strip() != 'application/json':
raise RuntimeError('Native API returned a non-JSON response')
data = response.read(LIMIT + 1)
if len(data) > LIMIT:
raise RuntimeError('Native API response exceeded 64 KiB')
if token and token.encode() in data:
raise RuntimeError('Native API response echoed the credential; output suppressed')
def reject_constant(_):
raise ValueError('nonfinite JSON value')
value = json.loads(data, parse_constant=reject_constant)
if not isinstance(value, dict):
raise ValueError('expected object')
if token and token in json.dumps(value, ensure_ascii=False):
raise RuntimeError('Native API response echoed the credential; output suppressed')
return value
except (OSError, http.client.HTTPException, ValueError):
raise RuntimeError('Native API transport or JSON failed; check lifecycle before retrying a mutation') from None
finally:
conn.close()
def lifecycle(value):
if (any(type(value.get(key)) is not bool for key in ('draining', 'drained'))
or any(type(value.get(key)) is not int or value[key] < 0
for key in ('requests_in_flight', 'generation_jobs'))
or value.get('worker') not in {'unconfigured', 'starting', 'restarting', 'ready', 'stopping', 'failed'}):
raise RuntimeError('Invalid native lifecycle response')
if value['drained'] and (not value['draining'] or value['requests_in_flight']
or value['generation_jobs'] or value['worker'] not in {'ready', 'unconfigured'}):
raise RuntimeError('Inconsistent native drained state')
return value
def control(action, target, read_key, *, wait=0, transport=request, clock=time.monotonic, sleep=time.sleep):
if action not in ACTIONS:
raise ValueError('Unsupported native API action')
if not math.isfinite(wait) or not 0 <= wait <= 3600 or (wait and action != 'drain'):
raise ValueError('--wait is only for drain, between 0 and 3600 seconds')
if target.get('backend') != 'strata-native':
raise ValueError('Select strata-native first or pass --url with --key-file/--no-auth')
url = target.get('url')
endpoint(url)
token = read_key(target) if target.get('key_file') else ''
observed = transport(url, 'GET', '/status', token)
if observed.get('service') != 'strata-control' or type(observed.get('ready')) is not bool:
raise RuntimeError('Endpoint is not a native Strata control plane')
if action == 'status':
result = observed
else:
method, path = ACTIONS[action]
result = transport(url, method, path, token)
if action in {'drain', 'resume', 'lifecycle'}:
lifecycle(result)
if action in {'drain', 'resume'} and result['draining'] != (action == 'drain'):
raise RuntimeError('Native admission changed concurrently; inspect lifecycle')
if action == 'metrics' and (result.get('schema_version') != 1 or not isinstance(result.get('generation'), dict)):
raise RuntimeError('Unsupported native metrics response')
deadline = clock() + wait
while action == 'drain' and wait and not result['drained']:
remaining = deadline - clock()
if remaining <= 0:
raise RuntimeError('Drain wait timed out; admission remains closed. Inspect lifecycle or explicitly resume.')
sleep(min(0.25, remaining))
remaining = deadline - clock()
if remaining <= 0:
continue
result = lifecycle(transport(url, 'GET', '/admin/lifecycle', token, timeout=min(8, remaining)))
if not result['draining']:
raise RuntimeError('Drain was resumed concurrently; no shutdown was performed')
return {'action': action, 'url': url, 'connection_changed': False, 'runtime': result}
def main(argv=None, *, connection, read_key):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=tuple(ACTIONS))
parser.add_argument('--url', help='explicit loopback URL; does not change the selected connection')
auth = parser.add_mutually_exclusive_group()
auth.add_argument('--key-file', help='private key file; token is never a CLI argument')
auth.add_argument('--no-auth', action='store_true')
parser.add_argument('--wait', type=float, default=0, metavar='SECONDS', help='wait for drained after drain; never auto-stop')
args = parser.parse_args(argv)
if args.url:
if not args.key_file and not args.no_auth:
parser.error('--url requires --key-file or --no-auth; credentials are never inherited for an override')
target = {'backend': 'strata-native', 'url': args.url, 'key_file': args.key_file}
else:
if args.key_file or args.no_auth:
parser.error('authentication overrides require an explicit --url')
target = connection()
result = control(args.action, target, read_key, wait=args.wait)
print(json.dumps(result, ensure_ascii=False))
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""Native controller behavior checks; no GPU or user endpoint is contacted."""
import contextlib
import importlib.util
import io
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import tempfile
import threading
import unittest
from unittest.mock import patch
import qwen_native_api as client
def load(name):
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + '.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
installer = load('install-qwen-native-api')
service_installer = load('install-qwen-native-service')
TARGET = {'backend': 'strata-native', 'url': 'http://127.0.0.1:18084'}
def state(draining=False, jobs=0):
return dict(draining=draining, drained=draining and jobs == 0,
requests_in_flight=0, generation_jobs=jobs, worker='ready')
class ControlTests(unittest.TestCase):
def test_identity_precedes_mutation_and_ready_false_allows_resume(self):
calls = []
def transport(url, method, path, token):
calls.append((method, path))
return {'service': 'strata-control', 'ready': False} if path == '/status' else state()
result = client.control('resume', TARGET, None, transport=transport)
self.assertFalse(result['connection_changed'])
self.assertEqual(calls, [('GET', '/status'), ('POST', '/admin/resume')])
calls.clear()
def wrong(*args):
calls.append(args[2])
return {'service': 'other', 'ready': True}
with self.assertRaisesRegex(RuntimeError, 'not a native'):
client.control('drain', TARGET, None, transport=wrong)
self.assertEqual(calls, ['/status'])
def test_invalid_target_and_wait_never_send_or_read_key(self):
def unexpected(*args, **kwargs):
self.fail('Invalid input reached I/O')
for url in ['https://127.0.0.1', 'http://remote', 'http://user@localhost',
'http://127.0.0.1/path', 'http://localhost?q=x',
'http://127.0.0.1:0', 'http://127.0.0.1:65536', 'http://localhost\n']:
with self.subTest(url=url), self.assertRaises(ValueError):
client.control('drain', dict(TARGET, url=url, key_file='private'), unexpected, transport=unexpected)
for wait in [-1, float('nan'), float('inf'), 3601]:
with self.assertRaises(ValueError):
client.control('drain', TARGET, unexpected, wait=wait, transport=unexpected)
with self.assertRaises(ValueError):
client.control('metrics', TARGET, unexpected, wait=1, transport=unexpected)
with self.assertRaises(ValueError):
client.control('drain', dict(TARGET, backend='strata'), unexpected, transport=unexpected)
self.assertEqual(client.endpoint('http://localhost:99'), ('127.0.0.1', 99))
self.assertEqual(client.endpoint('http://[::1]:99'), ('::1', 99))
def test_wait_completion_timeout_and_concurrent_resume(self):
for ending in ['complete', 'timeout', 'resume']:
with self.subTest(ending=ending):
calls = []
now = [0]
def sleep(seconds):
now[0] += seconds
def transport(url, method, path, token, **kwargs):
calls.append((method, path))
if path == '/status':
return {'service': 'strata-control', 'ready': True}
if path == '/admin/drain' or ending == 'timeout':
return state(True, 1)
return state(ending == 'complete')
def run():
return client.control('drain', TARGET, None, wait=1, transport=transport,
sleep=sleep, clock=lambda: now[0])
if ending == 'complete':
self.assertTrue(run()['runtime']['drained'])
else:
with self.assertRaisesRegex(RuntimeError, 'timed out' if ending == 'timeout' else 'resumed concurrently'):
run()
self.assertEqual([path for method, path in calls if method == 'POST'], ['/admin/drain'])
def test_rejects_inconsistent_lifecycle_and_metrics(self):
for invalid in [dict(state(), drained=True), dict(state(True), generation_jobs=1),
dict(state(True), worker='starting'), dict(state(), generation_jobs=True)]:
with self.assertRaises(RuntimeError):
client.lifecycle(invalid)
with self.assertRaisesRegex(RuntimeError, 'metrics'):
client.control('metrics', TARGET, None, transport=lambda u, m, p, t:
{'service': 'strata-control', 'ready': True} if p == '/status' else {'schema_version': 2})
def test_cli_auth_is_not_inherited_for_url_overrides(self):
def unexpected(*args):
self.fail('Connection or key should not be read')
for argv in [['status', '--url', TARGET['url']], ['status', '--no-auth'],
['drain', '--key-file', 'private']]:
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
client.main(argv, connection=unexpected, read_key=unexpected)
with patch.object(client, 'control', return_value={}) as control, contextlib.redirect_stdout(io.StringIO()):
client.main(['status', '--url', TARGET['url'], '--no-auth'], connection=unexpected, read_key=unexpected)
self.assertIsNone(control.call_args.args[1]['key_file'])
client.main(['metrics'], connection=lambda: dict(TARGET, key_file='selected'), read_key=unexpected)
self.assertEqual(control.call_args.args[1]['key_file'], 'selected')
class HttpTests(unittest.TestCase):
def test_direct_auth_bounded_json_no_redirect_or_secret_echo(self):
token = 'fixture-private-' + 'x' * 32
reply = [200, 'application/json', b'{"ok":true}']
seen = []
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
seen.append((self.path, self.headers.get('Authorization')))
self.send_response(reply[0])
self.send_header('Content-Type', reply[1])
self.send_header('Content-Length', str(len(reply[2])))
self.send_header('Location', '/redirect-must-not-be-followed')
self.end_headers()
self.wfile.write(reply[2])
def log_message(self, *_):
pass
server = HTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
url = f'http://127.0.0.1:{server.server_port}'
try:
with patch.dict(os.environ, {'http_proxy': 'http://127.0.0.1:1', 'HTTP_PROXY': 'http://127.0.0.1:1'}):
self.assertEqual(client.request(url, 'GET', '/status', token), {'ok': True})
self.assertEqual(seen, [('/status', 'Bearer ' + token)])
for response in [(302, 'application/json', b'{}'), (401, 'application/json', token.encode()),
(200, 'text/plain', b'{}'), (200, 'application/json', b'x' * (client.LIMIT + 1)),
(200, 'application/json', b'{"x":NaN}'), (200, 'application/json', b'[]'),
(200, 'application/json', json.dumps({'echo': token}).encode()),
(200, 'application/json', ('{"echo":"' + ''.join(f'\\u{ord(c):04x}' for c in token) + '"}').encode())]:
reply[:] = response
count = len(seen)
with self.assertRaises(RuntimeError) as error:
client.request(url, 'GET', '/status', token)
self.assertNotIn(token, str(error.exception))
self.assertEqual(len(seen), count + 1)
finally:
server.shutdown()
server.server_close()
thread.join()
class InstallerTests(unittest.TestCase):
SOURCE = '''import argparse, sys
HOST = 'fixture'
def connection(): return {}
def native_key(target): return ''
def ctl_main():
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('status')
# Strata Next native Responses integration v1
# Strata Next native bearer file integration v1
'''
def test_install_coexists_both_orders_is_idempotent_and_preserves_connection(self):
for order in [(installer, service_installer), (service_installer, installer)]:
with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stdout(io.StringIO()):
root = Path(directory)
launcher = root / 'qwen_local.py'
launcher.write_text(self.SOURCE)
connection = root / 'connection.json'
connection.write_text('{"unchanged":true}')
for item in order:
item.install(launcher)
first = launcher.read_bytes()
installer.install(launcher)
service_installer.install(launcher)
self.assertEqual(launcher.read_bytes(), first)
self.assertEqual(connection.read_text(), '{"unchanged":true}')
self.assertEqual(len(list(root.glob('*.before-native-api-*'))), 1)
self.assertEqual((root / 'qwen_native_api.py').stat().st_mode & 0o777, 0o600)
self.assertEqual(first.count(b"sys.argv[1] == 'native-api'"), 1)
self.assertEqual(first.count(b"sys.argv[1] == 'native-service'"), 1)
def test_unrelated_helper_and_missing_anchor_are_preserved(self):
with self.assertRaises(RuntimeError):
installer.patched(self.SOURCE.replace('def ctl_main():', 'def other():'))
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
launcher = root / 'qwen_local.py'
launcher.write_text(self.SOURCE)
(root / 'qwen_native_api.py').write_text('unrelated')
with self.assertRaises(RuntimeError):
installer.install(launcher)
self.assertEqual(launcher.read_text(), self.SOURCE)
if __name__ == '__main__':
unittest.main()