Files
2026-11-22 19:20:51 +03:00

429 lines
15 KiB
Python

#!/usr/bin/env python3
"""Track 1. Three prefetch settings, three image sizes, then a full queue.
The worker is recreated with WORKER_CONCURRENCY 1, 2 and 4. Each run uploads
the same burst and records throughput, max queue depth, p95 time to ready and
worker RSS. Then the worker is stopped, uploads continue until 429, and the
worker is started again. Already accepted ids must reach ready.
Prints counts and ids only. No tokens or file bytes.
"""
import json
import math
import os
import struct
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import zlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client # noqa: E402
SETTINGS = (1, 2, 4)
SIZES = (('small', 128, 128), ('medium', 640, 480), ('large', 2560, 1920))
PER_SIZE = 5
EVIDENCE = ROOT / 'evidence' / 'track1.json'
def read_env():
values = {}
for line in (ROOT / '.env').read_text(encoding='utf-8').splitlines():
text = line.strip()
if not text or text.startswith('#') or '=' not in text:
continue
key, value = text.split('=', 1)
values[key.strip()] = value.strip()
return values
def docker(args, check=True):
completed = subprocess.run(['docker', *args], text=True, capture_output=True)
if check and completed.returncode != 0:
tail = (completed.stderr or completed.stdout or '').strip().splitlines()
raise SystemExit('docker %s failed\n%s' % (' '.join(args), '\n'.join(tail[-20:])))
return completed
def worker_name():
completed = compose(['ps', '-a', '--format', '{{.Service}}\t{{.Name}}'])
for line in completed.stdout.splitlines():
service, _, name = line.partition('\t')
if service.strip() == 'worker':
return name.strip()
raise SystemExit('worker container was not found')
def wait_prefetch_since(name, value, since):
needle = 'prefetch' if value is None else 'prefetch %s' % value
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
logs = docker(['logs', '--since', since, '--tail', '40', name], check=False)
text = (logs.stdout or '') + (logs.stderr or '')
if needle in text:
return
time.sleep(0.3)
raise SystemExit('worker did not log %s after start' % needle)
def compose(args, env=None, check=True):
merged = os.environ.copy()
if env:
merged.update(env)
completed = subprocess.run(
['docker', 'compose', '--env-file', '.env', *args],
cwd=ROOT,
env=merged,
text=True,
capture_output=True,
)
if check and completed.returncode != 0:
tail = (completed.stderr or completed.stdout or '').strip().splitlines()
raise SystemExit('compose %s failed\n%s' % (' '.join(args), '\n'.join(tail[-20:])))
return completed
def png(width, height):
"""Solid RGB PNG. The file is small; the worker still decodes width*height."""
row = b'\x00' + bytes((40, 90, 160)) * width
raw = row * height
def chunk(tag, data):
return struct.pack('>I', len(data)) + tag + data + struct.pack('>I', zlib.crc32(tag + data) & 0xFFFFFFFF)
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, 1)) + chunk(b'IEND', b'')
def percentile(values, p):
if not values:
return None
ordered = sorted(values)
index = max(0, math.ceil(p * len(ordered)) - 1)
return round(ordered[index], 3)
def parse_mib(text):
match_number = ''
for char in text:
if char.isdigit() or char == '.':
match_number += char
elif match_number:
break
if not match_number:
return None
number = float(match_number)
lower = text.lower()
if 'gib' in lower or lower.startswith(match_number + 'gb'):
return number * 1024
if 'kib' in lower:
return number / 1024
return number
def worker_rss_mib():
completed = subprocess.run(
['docker', 'stats', '--no-stream', '--format', '{{.Name}}\t{{.MemUsage}}'],
text=True,
capture_output=True,
)
if completed.returncode != 0:
return None
peak = None
for line in completed.stdout.splitlines():
if 'worker' not in line:
continue
usage = line.split('\t', 1)[-1].split('/')[0].strip()
value = parse_mib(usage)
if value is not None:
peak = value if peak is None else max(peak, value)
return None if peak is None else round(peak, 1)
def queue_ready():
completed = compose(
['exec', '-T', 'rabbitmq', 'rabbitmqctl', 'list_queues', 'name', 'messages_ready', '--quiet'],
check=False,
)
if completed.returncode != 0:
return None
for line in completed.stdout.splitlines():
parts = line.split()
if len(parts) >= 2 and parts[0] == 'attachment.jobs':
return int(parts[1])
return 0
class Probe(threading.Thread):
"""RSS only. rabbitmqctl is slow and was starving the memory samples."""
def __init__(self):
super().__init__(daemon=True)
self.rss = []
self._stop = threading.Event()
def run(self):
while not self._stop.is_set():
rss = worker_rss_mib()
if rss is not None:
self.rss.append(rss)
def finish(self):
self._stop.set()
self.join(timeout=5)
class Depth(threading.Thread):
def __init__(self):
super().__init__(daemon=True)
self.depth = []
self._stop = threading.Event()
def run(self):
while not self._stop.is_set():
value = queue_ready()
if value is not None:
self.depth.append(value)
self._stop.wait(0.3)
def finish(self):
self._stop.set()
self.join(timeout=5)
def wait_http(base):
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
try:
urllib.request.urlopen(base + '/health/ready', timeout=2).read()
return
except (OSError, urllib.error.URLError):
time.sleep(2)
raise SystemExit('API did not become ready')
def wait_prefetch(value):
needle = 'prefetch %s' % value
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
logs = compose(['logs', 'worker', '--tail', '40'], check=False)
if needle in (logs.stdout or '') or needle in (logs.stderr or ''):
return
time.sleep(1)
raise SystemExit('worker did not log %s' % needle)
def upload_one(client, actor, chat_id, body, filename):
local = Client(client.base, timeout=30)
started = time.monotonic()
try:
response = local.call(
'POST',
'/api/v1/chats/%s/attachments?filename=%s' % (chat_id, filename),
[202, 429],
actor=actor,
raw=body,
headers={'Content-Type': 'image/png'},
schema='Attachment',
)
except Exception as exc:
return {'status': 0, 'error': type(exc).__name__, 'accepted_at': started}
item = {'status': response['status'], 'accepted_at': time.monotonic()}
if response['status'] == 202:
item['id'] = response['json']['id']
return item
def wait_ready(client, actor, items, timeout, worker_started=None):
pending = {item['id']: item for item in items if item.get('id')}
deadline = time.monotonic() + timeout
while pending and time.monotonic() < deadline:
for attachment_id in list(pending):
body = client.call(
'GET',
'/api/v1/attachments/' + attachment_id,
actor=actor,
schema='Attachment',
)['json']
now = time.monotonic()
if body['status'] == 'ready':
item = pending.pop(attachment_id)
item['seconds_to_ready'] = round(now - item['accepted_at'], 3)
if worker_started is not None:
item['drain_s'] = round(now - worker_started, 3)
elif body['status'] == 'failed':
item = pending.pop(attachment_id)
item['failed'] = body.get('error_code')
if pending:
time.sleep(0.25)
return [item['id'] for item in pending.values()]
def summarize(concurrency, items, probe, depth, queued_at_start):
ready = [item for item in items if 'seconds_to_ready' in item]
drains = [item['drain_s'] for item in ready if 'drain_s' in item]
drain_elapsed = max(drains) if drains else 0.001
by_size = {}
for size, _width, _height in SIZES:
sample = [item['seconds_to_ready'] for item in ready if item.get('size') == size]
by_size[size] = {
'n': len(sample),
'p95_s': percentile(sample, 0.95),
}
failed = [item['id'] for item in items if item.get('failed')]
return {
'label': 'compare',
'concurrency_prefetch': concurrency,
'uploaded': len(items),
'ready': len(ready),
'failed': failed,
'drain_s': round(drain_elapsed, 3),
'throughput_ready_per_s': round(len(ready) / drain_elapsed, 3),
'queue_ready_at_start': queued_at_start,
'queue_ready_max': max(depth.depth) if depth.depth else queued_at_start,
'p95_s': percentile([item['seconds_to_ready'] for item in ready], 0.95),
'p95_drain_s': percentile(drains, 0.95),
'p95_by_size': by_size,
'rss_max_mib': max(probe.rss) if probe.rss else None,
'rss_samples': len(probe.rss),
}
def run_setting(client, actor, chat, concurrency, pictures):
"""Stop the worker, accept one backlog, then drain it at this prefetch."""
print('setting prefetch=%s' % concurrency, flush=True)
compose(
['up', '-d', '--no-deps', '--force-recreate', 'worker'],
env={'WORKER_CONCURRENCY': str(concurrency)},
)
wait_prefetch(concurrency)
name = worker_name()
docker(['stop', '-t', '10', name])
with ThreadPoolExecutor(max_workers=6) as pool:
uploaded = list(pool.map(
lambda job: dict(upload_one(client, actor, chat['id'], job[1], job[0] + '.png'), size=job[0]),
pictures,
))
rejected = sum(1 for item in uploaded if item['status'] == 429)
if rejected:
raise SystemExit('comparison burst hit 429 (%s) at prefetch %s' % (rejected, concurrency))
accepted_n = sum(1 for item in uploaded if item['status'] == 202)
queued_at_start = 0
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
queued_at_start = queue_ready() or 0
if queued_at_start >= accepted_n:
break
time.sleep(0.4)
probe = Probe()
depth = Depth()
probe.start()
depth.start()
since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 2))
docker(['start', name])
wait_prefetch_since(name, concurrency, since)
worker_started = time.monotonic()
missing = wait_ready(client, actor, uploaded, 240, worker_started)
probe.finish()
depth.finish()
summary = summarize(concurrency, uploaded, probe, depth, queued_at_start)
summary['still_pending'] = missing
print(json.dumps(summary, ensure_ascii=False), flush=True)
if missing or summary['failed'] or summary['ready'] != len(pictures):
raise SystemExit('prefetch %s did not finish the burst' % concurrency)
return summary
def run_overload(client, actor, chat, limit):
print('overload cap=%s' % limit, flush=True)
name = worker_name()
docker(['stop', '-t', '10', name])
body = png(32, 32)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=8) as pool:
uploaded = list(pool.map(
lambda index: upload_one(client, actor, chat['id'], body, 'overload-%s.png' % index),
range(limit + 8),
))
accepted = [item for item in uploaded if item.get('status') == 202]
rejected = sum(1 for item in uploaded if item.get('status') == 429)
depth = queue_ready()
print('accepted=%s rejected=%s queue_ready=%s' % (len(accepted), rejected, depth), flush=True)
since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 2))
docker(['start', name])
wait_prefetch_since(name, None, since)
missing = wait_ready(client, actor, accepted, 180)
follow = upload_one(client, actor, chat['id'], body, 'after-drain.png')
follow_missing = []
if follow.get('status') == 202:
follow_missing = wait_ready(client, actor, [follow], 120)
elapsed = time.monotonic() - started
summary = {
'label': 'overload',
'cap': limit,
'attempted': len(uploaded),
'accepted': len(accepted),
'rejected_429': rejected,
'queue_ready_while_stopped': depth,
'pending_after_restart': missing,
'follow_up_status': follow.get('status'),
'follow_up_pending': follow_missing,
'elapsed_s': round(elapsed, 3),
'accepted_ids': [item['id'] for item in accepted],
}
print(json.dumps({key: value for key, value in summary.items() if key != 'accepted_ids'}, ensure_ascii=False), flush=True)
if rejected < 1 or not accepted or missing or follow.get('status') != 202 or follow_missing:
raise SystemExit('overload recovery did not complete')
return summary
def main():
values = read_env()
port = values.get('LB_PORT') or '8080'
limit = int(values.get('MAX_INFLIGHT_JOBS') or '20')
base = 'http://127.0.0.1:%s' % port
pictures = []
for name, width, height in SIZES:
body = png(width, height)
pictures.extend((name, body) for _ in range(PER_SIZE))
if '--skip-build' in sys.argv:
print('skip build', flush=True)
compose(['up', '-d'])
else:
print('build and start', flush=True)
compose(['up', '-d', '--build'])
wait_http(base)
client = Client(base, timeout=30)
actor, _bob, _eve, chat = client.bootstrap()
rows = []
try:
for concurrency in SETTINGS:
rows.append(run_setting(client, actor, chat, concurrency, pictures))
overload = run_overload(client, actor, chat, limit)
finally:
saved = values.get('WORKER_CONCURRENCY') or '2'
compose(
['up', '-d', '--no-deps', '--force-recreate', 'worker'],
env={'WORKER_CONCURRENCY': saved},
)
report = {
'base_url': base,
'sizes': [{'name': name, 'width': width, 'height': height, 'count': PER_SIZE} for name, width, height in SIZES],
'note': 'Each setting stops the worker, accepts the same backlog, then starts that prefetch. prefetch equals WORKER_CONCURRENCY. p95_s is client time from the 202 to ready. throughput is ready count divided by drain time after the worker starts. rss_max_mib is the worker container during the drain.',
'runs': rows,
'overload': {key: value for key, value in overload.items() if key != 'accepted_ids'},
}
EVIDENCE.parent.mkdir(parents=True, exist_ok=True)
EVIDENCE.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print('wrote %s' % EVIDENCE, flush=True)
if __name__ == '__main__':
main()