Files
leleka/scripts/smoke-signal-drain.py
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

184 lines
7.6 KiB
Python

#!/usr/bin/env python3
"""CPU-only termination grace: admitted SSE + queued JSON, expiry and default."""
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
ENGINE = r'''
from pathlib import Path
import os, sys, threading
root = Path(sys.argv[-1])
(root / 'worker-pid').write_text(str(os.getpid()))
stop = threading.Event()
count = 0
thread = None
def generate(first):
print('T 79', flush=True)
if first:
while not (root / 'release').exists():
if stop.wait(0.01):
return
if not stop.is_set():
print('T 75\nDONE 2 7 1.0 2.0 stop', flush=True)
print('READY 262144 stop', flush=True)
for line in sys.stdin:
if line.startswith('GEN '):
if thread:
thread.join()
count += 1
(root / 'generations').write_text(str(count))
thread = threading.Thread(target=generate, args=(count == 1,))
thread.start()
elif line.strip() == 'STOP':
(root / 'stopped').touch()
stop.set()
elif line.strip() == 'QUIT':
(root / 'quit').touch()
stop.set()
if thread:
thread.join()
break
'''
def run_case(binary, fixture, signum, grace, complete):
with tempfile.TemporaryDirectory(prefix='strata-signal-drain-') as directory:
root = Path(directory)
fixture.tokenizer(root)
engine = root / 'engine'
engine.write_text('#!' + sys.executable + '\n' + ENGINE)
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_MAX_WORKER_RESTARTS': '0'}
if grace is not None:
env['STRATA_SHUTDOWN_GRACE_S'] = str(grace)
def open_request(path, payload=None):
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
conn.request('GET' if payload is None else 'POST', path,
None if payload is None else json.dumps(payload),
{'Content-Type': 'application/json'})
return conn, conn.getresponse()
def request(path, payload=None):
conn, response = open_request(path, payload)
try:
return response.status, json.loads(response.read())
finally:
conn.close()
def wait_for(predicate):
deadline = time.monotonic() + 8
while True:
try:
if predicate():
return
except OSError:
pass
assert process.poll() is None and time.monotonic() < deadline, 'condition timed out'
time.sleep(0.01)
with tempfile.TemporaryFile() as logs:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs,
start_new_session=True)
conn = None
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
try:
wait_for(lambda: request('/ready')[0] == 200)
assert request('/admin/lifecycle')[1]['shutting_down'] is False
payload = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 8,
'reasoning': {'effort': 'none'}, 'stream': True}
conn, response = open_request('/v1/responses', payload)
assert response.status == 200
events = []
while True:
line = response.readline().decode()
assert line, 'missing initial token'
if line.startswith('data:'):
events.append(json.loads(line[5:]))
if events[-1]['type'] == 'response.output_text.delta':
break
queued = pool.submit(request, '/v1/responses', {**payload, 'stream': False})
wait_for(lambda: request('/admin/lifecycle')[1]['generation_jobs'] == 2)
start = time.monotonic()
process.send_signal(signum)
if grace:
wait_for(lambda: request('/admin/lifecycle')[1]['shutting_down'])
assert request('/ready')[0] == 503
code, state = request('/admin/resume', {})
assert code == 200 and state['shutting_down'] and state['draining']
assert state['requests_in_flight'] == 2 and state['generation_jobs'] == 2
code, error = request('/v1/responses', payload)
assert code == 503 and error['error']['code'] == 'runtime_draining'
assert request('/health')[0] == 200
if complete:
(root / 'release').touch()
events += [json.loads(line[5:]) for line in response.read().decode().splitlines()
if line.startswith('data:')]
conn.close()
conn = None
assert [e['sequence_number'] for e in events] == list(range(len(events)))
code, result = queued.result(timeout=8)
assert process.wait(timeout=5) == 0
elapsed = time.monotonic() - start
assert elapsed < 5, elapsed
assert (root / 'quit').exists()
if complete:
assert events[-1]['type'] == 'response.completed'
assert ''.join(e['delta'] for e in events if e['type'] == 'response.output_text.delta') == 'OK'
assert code == 200 and result['output'][0]['content'][0]['text'] == 'OK'
assert (root / 'generations').read_text() == '2'
assert not (root / 'stopped').exists()
else:
assert events[-1]['type'] == 'response.failed', events[-1]
assert code != 200 and result['error']
assert (root / 'generations').read_text() == '1'
assert (root / 'stopped').exists()
if grace:
assert elapsed >= 0.9, elapsed
worker_pid = int((root / 'worker-pid').read_text())
try:
os.kill(worker_pid, 0)
except ProcessLookupError:
pass
else:
raise AssertionError('worker survived shutdown')
finally:
(root / 'release').touch()
if conn:
conn.close()
if process.poll() is None:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
pool.shutdown(wait=True, cancel_futures=True)
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)
for signum in [signal.SIGTERM, signal.SIGINT]:
for grace, complete in [(5, True), (1, False), (None, False)]:
run_case(binary, fixture, signum, grace, complete)
print('Signal drain: 6 CPU cases passed; SIGTERM/SIGINT, exact SSE + queued JSON, irreversible drain, expiry/default, terminal events and no orphan worker')
if __name__ == '__main__':
main()