Files
leleka/scripts/smoke-queue-deadline.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 0ca493be04 test: run the scripted-engine HTTP smokes through the runtime stack (fake_runtime over real gRPC)
fake_runtime is a leleka.runtime.v1 server (the real RuntimeServer) whose engine is the same
engine.sh the smokes already use; fixture.runtime_stack() swaps strata-next's engine child for
it when STRATA_TEST_FAKE_RUNTIME is set, otherwise nothing changes. scripts/test-api-over-runtime.py
runs the ten smokes whose assertions do not depend on strata-next owning the engine process.

The HTTP layer clamps reasoning_tokens to the engine-reported output total, which a text-level
engine's re-tokenized pieces can otherwise exceed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 03:00:55 +02:00

134 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Isolated CPU worker: queued API expiry never sends GEN; active work survives."""
import concurrent.futures
import http.client
import importlib.util
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import sys
import tempfile
import time
def main():
binary = Path(sys.argv[1]).resolve()
spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py'))
fixture = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fixture)
with tempfile.TemporaryDirectory(prefix='strata-queue-') as directory:
root = Path(directory)
fixture.tokenizer(root)
engine = root / 'engine.sh'
engine.write_text("""#!/bin/sh
printf 'READY 262144 stop\n'
while IFS= read -r line; do
case "$line" in
'GEN '*)
printf 'GEN\n' >> "$2/requests"
if [ ! -e "$2/active" ]; then
: > "$2/active"
while [ ! -e "$2/release" ]; do sleep 0.01; done
fi
printf 'T 65\nDONE 1 1 1.0 2.0 stop\n' ;;
QUIT) exit 0 ;;
*) exit 4 ;;
esac
done
""")
engine.chmod(0o700)
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}',
'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_STARTUP_TIMEOUT_S': '5',
'STRATA_MAX_WORKER_RESTARTS': '0', 'STRATA_QUEUE_TIMEOUT_S': '1'}
def request(path, payload=None):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=15)
try:
connection.request('POST' if payload is not None else 'GET', path,
json.dumps(payload) if payload is not None else None,
{'Content-Type': 'application/json', 'anthropic-version': '2023-06-01'})
response = connection.getresponse()
return response.status, response.getheader('Content-Type'), response.read()
finally:
connection.close()
response_payload = {'model': 'strata-local', 'input': 'Hello', 'reasoning': {'effort': 'none'}}
env = fixture.runtime_stack(env, root) # no-op unless STRATA_TEST_FAKE_RUNTIME is set
with tempfile.TemporaryFile() as logs:
runtime = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
try:
deadline = time.monotonic() + 8
while True:
try:
if request('/ready')[0] == 200:
break
except (OSError, http.client.HTTPException):
pass
assert time.monotonic() < deadline, 'runtime not ready'
time.sleep(0.03)
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
active = pool.submit(request, '/v1/responses', response_payload)
try:
while not (root / 'active').exists():
assert time.monotonic() < deadline, 'first GEN missing'
time.sleep(0.01)
for path, payload in [
('/v1/responses', response_payload),
('/v1/chat/completions', {'model': 'strata-local', 'messages': [{'role':'user','content':'Hello'}]}),
('/v1/messages', {'model': 'strata-local', 'max_tokens': 16, 'messages': [{'role':'user','content':'Hello'}]}),
]:
for stream in [False, True]:
start = time.monotonic()
status, content_type, body = request(path, {**payload, 'stream': stream})
elapsed = time.monotonic() - start
assert status == 504 and 'application/json' in content_type, (path, status, body)
error = json.loads(body)['error']
assert 'queue deadline' in error['message'], error
if path != '/v1/messages':
assert error['code'] == 'queue_timeout', error
assert 0.7 <= elapsed < 5, elapsed
assert (root / 'requests').read_text().splitlines() == ['GEN']
assert not active.done(), 'active generation expired under queue deadline'
assert request('/ready')[0] == 200
finally:
(root / 'release').touch()
status, _, body = active.result(timeout=5)
assert status == 200 and json.loads(body)['output'][0]['content'][0]['text'] == 'A'
# All expired jobs must be skipped before the next live GEN.
for stream in [False, True]:
status, content_type, body = request('/v1/responses', {**response_payload, 'stream': stream})
assert status == 200, body
if stream:
events = [json.loads(line[6:]) for line in body.decode().splitlines() if line.startswith('data: ')]
assert events[-1]['type'] == 'response.completed'
final = events[-1]['response']
else:
final = json.loads(body)
assert final['output'][0]['content'][0]['text'] == 'A'
assert (root / 'requests').read_text().splitlines() == ['GEN'] * 3
lifecycle = json.loads(request('/admin/lifecycle')[2])
assert lifecycle['generation_jobs'] == 0, lifecycle
print('Queue deadline passed: 6 JSON/SSE Responses/Chat/Messages expirations, no queued GEN, active preserved, next JSON/SSE exact A, zero generation jobs')
finally:
if runtime.poll() is None:
runtime.send_signal(signal.SIGTERM)
try:
runtime.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(runtime.pid, signal.SIGKILL)
runtime.wait(timeout=5)
if runtime.returncode != 0:
logs.seek(0)
raise AssertionError(logs.read().decode()[-3000:])
if __name__ == '__main__':
main()