feat(api): bound queue waiting without expiring active work (#41)

* feat(api): add opt-in native queue deadline

* fix(queue): reject claims made after queue deadline
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 12:46:32 +02:00
committed by GitHub
parent 01b6c8f346
commit 9409dc92ff
12 changed files with 410 additions and 20 deletions
+11
View File
@@ -67,6 +67,17 @@ def main():
assert result['tokenizer_validated']
assert result['max_in_flight_requests'] == 2
assert result['generation_timeout_s'] is None
assert result['queue_timeout_s'] is None
for seconds in [1, 86400]:
assert run({'STRATA_QUEUE_TIMEOUT_S': str(seconds)})['queue_timeout_s'] == seconds
for seconds in ['0', '-1', '86401', '1.5', 'bad']:
run({'STRATA_QUEUE_TIMEOUT_S': seconds}, success=False)
config.write_text(json.dumps({**base, 'queue_timeout_s': 12}))
assert run()['queue_timeout_s'] == 12
assert run({'STRATA_QUEUE_TIMEOUT_S': '3'})['queue_timeout_s'] == 3
config.write_text(json.dumps({**base, 'queue_timeout_s': 0}))
run(success=False)
config.write_text(json.dumps(base))
assert result['shutdown_grace_s'] == 0
for seconds in [0, 20]:
assert run({'STRATA_SHUTDOWN_GRACE_S': str(seconds)})['shutdown_grace_s'] == seconds
+132
View File
@@ -0,0 +1,132 @@
#!/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'}}
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()