forked from mtusi2026/mtusi2026lab6
255 lines
12 KiB
Python
255 lines
12 KiB
Python
"""Drive the local Lab6 workload and record the three phases of the SLO experiment."""
|
|
import argparse
|
|
from collections import Counter
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from contextlib import contextmanager
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
from uuid import uuid4
|
|
|
|
from observability import (
|
|
BASE, COMPOSE, ROOT, Client, actor_and_chat, api_log, check, compose, lab_only,
|
|
prometheus, save, trace_by_id, upload, wait_for,
|
|
)
|
|
|
|
ALERTS = ('APIFastBurn', 'APISlowBurn', 'ReadyFastBurn', 'ReadySlowBurn', 'QueueLagHigh')
|
|
MESSAGE_RATE = 4
|
|
UPLOAD_RATE = 1
|
|
|
|
|
|
@contextmanager
|
|
def locked_messages(seconds):
|
|
# A lock on one business table keeps SELECT 1/readiness and other routes alive.
|
|
# pg_sleep bounds the fault even if the client running the experiment dies.
|
|
cmd = [*COMPOSE, 'exec', '-T', 'db', 'psql', '-X', '-q', '-v', 'ON_ERROR_STOP=1',
|
|
'-U', 'messenger', '-d', 'messenger']
|
|
with subprocess.Popen(cmd, cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, text=True, encoding='utf-8') as session:
|
|
assert session.stdin is not None and session.stdout is not None
|
|
session.stdin.write("SET application_name = 'lab6_slo_lock';\n"
|
|
"SET lock_timeout = '3s';\n"
|
|
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE;\n"
|
|
"\\echo LAB6_LOCKED\n"
|
|
f"SELECT pg_sleep({seconds});\nCOMMIT;\n\\echo LAB6_RELEASED\n")
|
|
session.stdin.close()
|
|
check(session.stdout.readline().strip() == 'LAB6_LOCKED', 'database lock setup failed')
|
|
started = time.time()
|
|
try:
|
|
yield started
|
|
finally:
|
|
session.wait(timeout=seconds + 10)
|
|
check('LAB6_RELEASED' in session.stdout.read() and session.returncode == 0, 'database lock not released')
|
|
|
|
|
|
class Workload:
|
|
def __init__(self, actor, chat):
|
|
self.actor = actor
|
|
self.chat = chat
|
|
self.client = threading.local()
|
|
self.shutdown = threading.Event()
|
|
self.rows = []
|
|
self.dropped = []
|
|
self.pool = ThreadPoolExecutor(max_workers=12)
|
|
self.thread = threading.Thread(target=self.schedule)
|
|
|
|
def one(self, kind):
|
|
if not hasattr(self.client, 'value'):
|
|
self.client.value = Client(BASE, timeout=4)
|
|
client = self.client.value
|
|
started = time.time()
|
|
try:
|
|
if kind == 'message':
|
|
response = client.call(
|
|
'POST', f'/api/v1/chats/{self.chat["id"]}/messages', [201, 503], actor=self.actor,
|
|
body={'text': 'Synthetic constant-rate SLO study'}, headers={'Idempotency-Key': uuid4().hex},
|
|
schema='Message',
|
|
)
|
|
else:
|
|
response = upload(client, self.actor, self.chat)
|
|
self.rows.append({'t': started, 'kind': kind, 'status': response['status'],
|
|
'request_id': response['headers']['X-Request-Id'],
|
|
'latency_s': round(time.time() - started, 6),
|
|
**({'attachment': response['json']['id']} if kind == 'upload' else {})})
|
|
except (AssertionError, OSError):
|
|
self.rows.append({'t': started, 'kind': kind, 'status': 'transport_or_contract_error',
|
|
'latency_s': round(time.time() - started, 6)})
|
|
|
|
def schedule(self):
|
|
tick = time.monotonic()
|
|
i = 0
|
|
inflight = set()
|
|
while not self.shutdown.is_set():
|
|
for kind in ('message', 'upload') if i % (MESSAGE_RATE // UPLOAD_RATE) == 0 else ('message',):
|
|
inflight = {task for task in inflight if not task.done()}
|
|
if len(inflight) >= 12:
|
|
self.dropped.append({'t': time.time(), 'kind': kind})
|
|
else:
|
|
inflight.add(self.pool.submit(self.one, kind))
|
|
i += 1
|
|
tick += 1 / MESSAGE_RATE
|
|
self.shutdown.wait(max(0, tick - time.monotonic()))
|
|
|
|
def __enter__(self):
|
|
self.thread.start()
|
|
return self
|
|
|
|
def __exit__(self, *_):
|
|
self.shutdown.set()
|
|
self.thread.join()
|
|
self.pool.shutdown()
|
|
|
|
|
|
def snapshot():
|
|
active = prometheus('ALERTS{alertname=~"' + '|'.join(ALERTS) + '"}')
|
|
return {
|
|
't': time.time(),
|
|
'alerts': {item['alertname']: item['alertstate'] for item in active},
|
|
'depth': next(iter(prometheus('messenger_queue_depth')), {}).get('value'),
|
|
'oldest_seconds': next(iter(prometheus('messenger_queue_oldest_age_seconds')), {}).get('value'),
|
|
'worker_cpu_cores': next(iter(prometheus('sum(rate(messenger_container_cpu_seconds_total{service_name="messenger-worker"}[15s]))')),
|
|
{}).get('value'),
|
|
'api_cpu_cores': next(iter(prometheus('sum(rate(messenger_container_cpu_seconds_total{service_name="messenger-api"}[15s]))')),
|
|
{}).get('value'),
|
|
'worker_ram_bytes': next(iter(prometheus('sum(messenger_container_memory_bytes{service_name="messenger-worker"})')),
|
|
{}).get('value'),
|
|
'api_ram_bytes': next(iter(prometheus('sum(messenger_container_memory_bytes{service_name="messenger-api"})')),
|
|
{}).get('value'),
|
|
}
|
|
|
|
|
|
def observe(samples, seconds):
|
|
until = time.monotonic() + seconds
|
|
while time.monotonic() < until:
|
|
tick = time.monotonic()
|
|
samples.append(snapshot())
|
|
time.sleep(max(0, min(2 - (time.monotonic() - tick), until - time.monotonic())))
|
|
|
|
|
|
def during(rows, start, stop):
|
|
return [row for row in rows if start <= row['t'] < stop]
|
|
|
|
|
|
def quantiles(values):
|
|
ordered = sorted(values)
|
|
return {f'p{p}_ms': round(1000 * ordered[math.ceil(len(ordered) * p / 100) - 1], 3)
|
|
for p in (50, 95, 99)} if ordered else {}
|
|
|
|
|
|
def summary(rows, start, stop):
|
|
result = {}
|
|
for kind in ('message', 'upload'):
|
|
items = [r for r in during(rows, start, stop) if r['kind'] == kind]
|
|
statuses = Counter(str(r['status']) for r in items)
|
|
result[kind] = {'statuses': dict(statuses), 'successful_per_s':
|
|
round((statuses['201'] + statuses['202']) / (stop - start), 3),
|
|
**quantiles([row['latency_s'] for row in items])}
|
|
return result
|
|
|
|
|
|
def alert_timing(samples, start, stop, names):
|
|
result = {}
|
|
for name in names:
|
|
firing = [s['t'] for s in samples if s['t'] >= start and s['alerts'].get(name) == 'firing']
|
|
if not firing:
|
|
result[name] = None
|
|
continue
|
|
resolved = next((s['t'] for s in samples if s['t'] > max(firing) and name not in s['alerts']), None)
|
|
result[name] = {
|
|
'firing_after_s': round(min(firing) - start, 3),
|
|
'resolved_after_restoration_s': round(resolved - stop, 3) if resolved is not None else None,
|
|
}
|
|
return result
|
|
|
|
|
|
def diagnose_db(rows):
|
|
failing = [row for row in rows if row['status'] == 503]
|
|
check(bool(failing), 'no application 503 from the database lock')
|
|
for row in failing[:5]:
|
|
log = wait_for(lambda: api_log(row['request_id']), 'missing incident log', timeout=8)
|
|
trace = wait_for(lambda: trace_by_id(log['trace_id']), 'missing incident trace', timeout=8)
|
|
sql = [span for span in trace if span['name'] == 'postgresql query' and span['duration_ms'] >= 900]
|
|
if sql:
|
|
return {'log': log, 'slow_postgresql_spans': sql, 'trace_id': log['trace_id']}
|
|
raise AssertionError('incident trace lacks a slow PostgreSQL child span')
|
|
|
|
|
|
def validate_result(result):
|
|
check(not result['firing_during_baseline'] and not result['firing_after_short_spike'],
|
|
'unexpected firing during baseline or brief fault')
|
|
summaries = result['client_summary']
|
|
check(summaries['short_db_spike']['message']['statuses'].get('503', 0) > 0, 'short spike did not generate errors')
|
|
events = [*result['database_alerts'].values(), *result['worker_alerts'].values()]
|
|
check(all(event and event['resolved_after_restoration_s'] is not None for event in events),
|
|
'expected alert was not detected and resolved')
|
|
recovery = result['worker_recovery']
|
|
check(recovery['uploads_ready'] == recovery['uploads_accepted'] >= 30 and recovery['max_backlog'] >= 30,
|
|
'backlog did not grow and drain as expected')
|
|
check(result['prometheus_samples'][-1]['depth'] in (0, 1), 'unfinished recovery')
|
|
# Count the sampled phases as a conservative lower bound for offered traffic.
|
|
observed = sum(sum(item['statuses'].values()) for phase in summaries.values() for item in phase.values())
|
|
check(result['dropped_by_generator'] <= observed * .01, 'load generator skipped more than 1% of requests')
|
|
|
|
|
|
def experiment(output):
|
|
lab_only()
|
|
client = Client(BASE)
|
|
actor, chat = actor_and_chat(client, 'slo')
|
|
samples, phases = [], {}
|
|
with Workload(actor, chat) as load:
|
|
baseline = time.time()
|
|
observe(samples, 82)
|
|
phases['baseline'] = [baseline, time.time()]
|
|
with locked_messages(2.5) as start:
|
|
observe(samples, 2)
|
|
phases['short_db_spike'] = [start, time.time()]
|
|
observe(samples, 30)
|
|
with locked_messages(65) as start:
|
|
observe(samples, 63)
|
|
phases['database_lock'] = [start, time.time()]
|
|
observe(samples, 36)
|
|
compose('stop', 'worker')
|
|
start = time.time()
|
|
try:
|
|
observe(samples, 62)
|
|
finally:
|
|
compose('start', 'worker')
|
|
phases['worker_stopped'] = [start, time.time()]
|
|
observe(samples, 50)
|
|
|
|
at = [item['attachment'] for item in during(load.rows, *phases['worker_stopped']) if 'attachment' in item]
|
|
ready = sum(client.call('GET', '/api/v1/attachments/' + identifier, actor=actor,
|
|
schema='Attachment')['json']['status'] == 'ready' for identifier in at)
|
|
db = alert_timing(samples, *phases['database_lock'], ALERTS[:2])
|
|
worker = alert_timing(samples, *phases['worker_stopped'], ALERTS[2:])
|
|
short_firing = sorted({name for s in during(samples, phases['short_db_spike'][0], phases['database_lock'][0])
|
|
for name, state in s['alerts'].items() if state == 'firing'})
|
|
baseline_firing = sorted({name for s in during(samples, *phases['baseline'])
|
|
for name, state in s['alerts'].items() if state == 'firing'})
|
|
diagnosis = diagnose_db(during(load.rows, *phases['database_lock']))
|
|
worker_samples = during(samples, *phases['worker_stopped'])
|
|
result = {
|
|
'profile': {'messages_per_s': MESSAGE_RATE, 'uploads_per_s': UPLOAD_RATE, 'max_inflight': 12,
|
|
'png_bytes': len((ROOT / 'tests/fixtures/sample.png').read_bytes()), 'monitor_interval_s': 2},
|
|
'phases_utc_unix': phases, 'client_summary': {phase: summary(load.rows, *times) for phase, times in phases.items()},
|
|
'dropped_by_generator': len(load.dropped),
|
|
'firing_during_baseline': baseline_firing, 'firing_after_short_spike': short_firing,
|
|
'database_alerts': db, 'worker_alerts': worker,
|
|
'worker_recovery': {'uploads_accepted': len(at), 'uploads_ready': ready,
|
|
'max_backlog': max(s['depth'] or 0 for s in worker_samples),
|
|
'max_oldest_s': max(s['oldest_seconds'] or 0 for s in worker_samples)},
|
|
'database_diagnosis': diagnosis, 'prometheus_samples': samples,
|
|
}
|
|
save(output, 'slo-experiment.json', result)
|
|
validate_result(result)
|
|
print(json.dumps({key: result[key] for key in ('database_alerts', 'worker_alerts', 'worker_recovery')}, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--output', type=Path, default=ROOT / 'evidence')
|
|
experiment(parser.parse_args().output)
|