Lab 6: track - 1

This commit is contained in:
2026-11-23 14:54:48 +03:00
parent 470d9d6f1e
commit a271ddd156
39 changed files with 3141 additions and 15 deletions
+54
View File
@@ -0,0 +1,54 @@
"""Grafana proxy helper for student observability verification (reads local secret, never prints it)."""
import base64
import json
from pathlib import Path
import time
import urllib.parse
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
class GrafanaClient:
def __init__(self, base_url='http://localhost:3000'):
self.base = base_url.rstrip('/')
pw = (ROOT / 'secrets/grafana_admin_password').read_text(encoding='utf-8').strip()
auth = base64.b64encode(('admin:' + pw).encode('utf-8')).decode('ascii')
self.headers = {'Authorization': 'Basic ' + auth, 'Accept': 'application/json'}
def get_json(self, path, timeout=10):
req = urllib.request.Request(self.base + path, headers=self.headers, method='GET')
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode('utf-8'))
def wait_ready(self, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
health = self.get_json('/api/health', timeout=3)
req = urllib.request.Request(self.base + '/api/datasources/proxy/uid/tempo/ready', headers=self.headers)
with urllib.request.urlopen(req, timeout=3) as r:
tempo_ok = (r.code == 200)
if health.get('database') == 'ok' and tempo_ok:
return
except Exception:
pass
time.sleep(1.5)
raise RuntimeError('Grafana or Tempo datasource did not become ready within timeout')
def prom_query(self, expr):
q = urllib.parse.urlencode({'query': expr})
return self.get_json(f'/api/datasources/proxy/uid/prometheus/api/v1/query?{q}')
def prom_rules(self):
return self.get_json('/api/datasources/proxy/uid/prometheus/api/v1/rules')
def loki_query_range(self, query, start_ns, end_ns, limit=100):
q = urllib.parse.urlencode({'query': query, 'start': str(start_ns), 'end': str(end_ns), 'limit': str(limit)})
return self.get_json(f'/api/datasources/proxy/uid/loki/loki/api/v1/query_range?{q}')
def tempo_search(self, q, start_s, end_s, limit=20):
params = urllib.parse.urlencode({'q': q, 'start': str(int(start_s)), 'end': str(int(end_s)), 'limit': str(limit)})
return self.get_json(f'/api/datasources/proxy/uid/tempo/api/search?{params}')
def tempo_trace(self, trace_id):
return self.get_json(f'/api/datasources/proxy/uid/tempo/api/traces/{trace_id}')
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Controlled Level 4 incidents: (1) worker stop -> alert firing/resolved; (2) slow DB vs slow handler; (3) telemetry outage."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'student-tests'))
from client import Client, check
from grafana_helper import GrafanaClient
def compose(*args, env_extra=None):
env = os.environ.copy()
if env_extra:
env.update(env_extra)
subprocess.run(['docker', 'compose', *args], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def alert_state(g, name):
rules = g.prom_rules().get('data', {}).get('groups', [])
for grp in rules:
for r in grp.get('rules', []):
if r.get('name') == name:
return r.get('state')
return 'missing'
def prom_scalar(g, expr):
res = g.prom_query(expr).get('data', {}).get('result', [])
return float(res[0]['value'][1]) if res else 0.0
def wait_api_ready(c, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready', schema='Health')
time.sleep(2)
return
except Exception:
time.sleep(0.5)
raise RuntimeError('API did not become ready')
def incident_1_worker_outage(g, c, alice, bob, chat):
print('Running Incident 1: Worker outage -> GrowingQueueLag firing & resolved...')
compose('stop', 'worker')
att, _ = c.attachment(alice, chat)
firing_seen = False
deadline = time.monotonic() + 75
try:
while time.monotonic() < deadline:
if alert_state(g, 'GrowingQueueLag') == 'firing':
firing_seen = True
break
time.sleep(2)
check(firing_seen, 'GrowingQueueLag alert did not reach firing state')
finally:
compose('up', '-d', 'worker')
c.wait_ready(bob, att, wait_seconds=60)
resolved_seen = False
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
if alert_state(g, 'GrowingQueueLag') == 'inactive':
resolved_seen = True
break
time.sleep(2)
check(resolved_seen, 'GrowingQueueLag alert did not resolve after worker recovery')
return {'alert': 'GrowingQueueLag', 'firing_observed': firing_seen, 'resolved_observed': resolved_seen, 'attachment_status': 'ready'}
def incident_2_slow_db_vs_handler(g, c, alice, chat):
print('Running Incident 2: Slow DB (lock contention + 503) vs Slow HTTP handler...')
t0 = time.time()
def hold_lock():
subprocess.run(
['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
'BEGIN; LOCK TABLE messages IN SHARE MODE; SELECT pg_sleep(1.3); COMMIT;'],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
th = threading.Thread(target=hold_lock)
th.start()
time.sleep(0.25)
r_db = c.message(alice, chat, 'slow-db-check')
th.join(timeout=10)
db_req_ms = round(r_db['elapsed'] * 1000, 1)
# Hold lock > 2s lock_timeout and send 3 parallel requests so all 3 hit real DB 503 timeouts
def hold_timeout_lock():
subprocess.run(
['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
'BEGIN; LOCK TABLE messages IN SHARE MODE; SELECT pg_sleep(3.5); COMMIT;'],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
th2 = threading.Thread(target=hold_timeout_lock)
th2.start()
time.sleep(0.3)
def send_503(idx):
local = Client('http://localhost:8081', timeout=10)
return local.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 503, actor=alice, body={'text': f'lock-timeout-{idx}'}, headers={'Idempotency-Key': f'lock-timeout-{int(t0)}-{idx}'})['status']
with ThreadPoolExecutor(max_workers=3) as ex:
statuses_503 = list(ex.map(send_503, range(3)))
th2.join(timeout=10)
error_firing = False
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
if alert_state(g, 'HighApiErrorRatio') == 'firing':
error_firing = True
break
time.sleep(2)
check(error_firing, 'HighApiErrorRatio alert did not fire after 503 DB timeouts')
# Now induce slow HTTP handler (outside DB) on api replicas temporarily
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={'FAULT_HANDLER_DELAY_MS': '650'})
wait_api_ready(c)
r_handler = c.message(alice, chat, 'slow-handler-check')
handler_req_ms = round(r_handler['elapsed'] * 1000, 1)
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={'FAULT_HANDLER_DELAY_MS': '0'})
wait_api_ready(c)
time.sleep(8)
search = g.tempo_search('{ resource.service.name = "messenger-api" && duration > 500ms }', t0 - 5, time.time() + 5, limit=30)
slow_traces = search.get('traces', [])
db_dominant_trace = None
handler_dominant_trace = None
for item in slow_traces:
tr = g.tempo_trace(item['traceID'])
root_ms = 0.0
db_ms = 0.0
for b in tr.get('batches', []):
for ss in b.get('scopeSpans', []):
for sp in ss.get('spans', []):
dur_ms = (int(sp['endTimeUnixNano']) - int(sp['startTimeUnixNano'])) / 1e6
if sp.get('name', '').startswith('POST /api/v1/chats/{chat_id}/messages'):
root_ms = max(root_ms, dur_ms)
if sp.get('name') == 'db.query':
db_ms += dur_ms
if root_ms > 500:
if db_ms > root_ms * 0.6:
db_dominant_trace = {'trace_id': item['traceID'], 'root_ms': round(root_ms, 1), 'db_query_ms': round(db_ms, 1)}
elif db_ms < root_ms * 0.25:
handler_dominant_trace = {'trace_id': item['traceID'], 'root_ms': round(root_ms, 1), 'db_query_ms': round(db_ms, 1)}
check(db_dominant_trace is not None and handler_dominant_trace is not None, 'could not distinguish slow DB vs slow HTTP handler in Tempo traces')
return {
'slow_db_request_ms': db_req_ms,
'db_timeout_statuses': statuses_503,
'slow_handler_request_ms': handler_req_ms,
'high_api_error_ratio_fired': error_firing,
'db_dominant_trace': db_dominant_trace,
'handler_dominant_trace': handler_dominant_trace,
}
def incident_3_telemetry_outage(g, c, alice, bob, chat):
print('Running Incident 3: Telemetry backend outage (Tempo & Loki stopped) -> API works & bounded RAM...')
failed_spans_before = prom_scalar(g, 'sum(otelcol_exporter_send_failed_spans_total)')
failed_logs_before = prom_scalar(g, 'sum(otelcol_exporter_send_failed_log_records_total)')
compose('stop', 'tempo', 'loki')
try:
before_mem = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', 'mtusi_lab6_solution-otel-collector-1'], text=True).strip()
for i in range(15):
r = c.message(alice, chat, f'outage-msg-{i}')
check(r['status'] == 201, 'API failed while telemetry backends were stopped')
att, _ = c.attachment(alice, chat)
ready = c.wait_ready(bob, att, wait_seconds=45)
check(ready['status'] == 'ready', 'worker failed while telemetry backends were stopped')
time.sleep(20)
after_mem = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', 'mtusi_lab6_solution-otel-collector-1'], text=True).strip()
failed_spans_after = prom_scalar(g, 'sum(otelcol_exporter_send_failed_spans_total)')
failed_logs_after = prom_scalar(g, 'sum(otelcol_exporter_send_failed_log_records_total)')
finally:
compose('up', '-d', 'loki', 'tempo')
g.wait_ready(timeout=60)
return {
'messages_succeeded_during_outage': 15,
'attachment_ready_during_outage': True,
'collector_mem_before': before_mem,
'collector_mem_during_outage': after_mem,
'collector_send_failed_spans_delta': round(failed_spans_after - failed_spans_before),
'collector_send_failed_logs_delta': round(failed_logs_after - failed_logs_before),
'api_preserved': True,
}
def main():
g = GrafanaClient('http://localhost:3000')
g.wait_ready(timeout=90)
c = Client('http://localhost:8081')
alice, bob, _, chat = c.bootstrap()
res1 = incident_1_worker_outage(g, c, alice, bob, chat)
res2 = incident_2_slow_db_vs_handler(g, c, alice, chat)
res3 = incident_3_telemetry_outage(g, c, alice, bob, chat)
report = {
'incident_1_worker_outage': res1,
'incident_2_slow_db_vs_handler': res2,
'incident_3_telemetry_backend_outage': res3,
'result': 'PASS',
}
dest = ROOT / 'evidence/lab6-incidents.json'
dest.write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
print(json.dumps(report, indent=2, ensure_ascii=False))
if __name__ == '__main__':
main()
@@ -0,0 +1,250 @@
#!/usr/bin/env python3
"""Track 1: Cost of Observability across off, always_on 100%, head 10%, and balanced tail-sampling."""
from concurrent.futures import ThreadPoolExecutor
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'student-tests'))
from client import Client, Failure
from grafana_helper import GrafanaClient
PROFILES = [
{
'name': 'telemetry_off',
'env': {
'OTEL_SDK_DISABLED': 'true',
'OTEL_TRACES_SAMPLER': 'always_off',
'OTEL_TRACES_SAMPLER_ARG': '0.0',
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml',
},
},
{
'name': 'always_on_100pct',
'env': {
'OTEL_SDK_DISABLED': 'false',
'OTEL_TRACES_SAMPLER': 'always_on',
'OTEL_TRACES_SAMPLER_ARG': '1.0',
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml',
},
},
{
'name': 'head_sampling_10pct',
'env': {
'OTEL_SDK_DISABLED': 'false',
'OTEL_TRACES_SAMPLER': 'parentbased_traceidratio',
'OTEL_TRACES_SAMPLER_ARG': '0.1',
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml',
},
},
{
'name': 'tail_sampling_balanced',
'env': {
'OTEL_SDK_DISABLED': 'false',
'OTEL_TRACES_SAMPLER': 'always_on',
'OTEL_TRACES_SAMPLER_ARG': '1.0',
'OTEL_COLLECTOR_CONFIG': './infra/otel/collector-tail-sampling.yaml',
},
},
]
def compose(*args, env_extra=None):
env = os.environ.copy()
if env_extra:
env.update(env_extra)
subprocess.run(['docker', 'compose', *args], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def wait_api_ready(c, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready', schema='Health')
time.sleep(2)
return
except Exception:
time.sleep(0.5)
raise RuntimeError('API did not become ready')
def prom_scalar(g, expr):
res = g.prom_query(expr).get('data', {}).get('result', [])
return float(res[0]['value'][1]) if res else 0.0
def sample_stats():
out = subprocess.check_output(
['docker', 'stats', '--no-stream', '--format', '{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}',
'mtusi_lab6_solution-api-1', 'mtusi_lab6_solution-api-2', 'mtusi_lab6_solution-otel-collector-1'],
text=True,
).strip().splitlines()
parsed = {}
for line in out:
name, cpu, mem = line.split('|')
short = name.replace('mtusi_lab6_solution-', '')
parsed[short] = {'cpu_pct': float(cpu.strip().rstrip('%') or 0.0), 'mem': mem.split('/')[0].strip()}
return parsed
def trigger_503_batch(alice, chat, tag, count=5):
proc = subprocess.Popen(
['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atq'],
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
)
assert proc.stdin and proc.stdout
proc.stdin.write("BEGIN;\nLOCK TABLE messages IN SHARE MODE;\nSELECT 'LOCKED_NOW';\n")
proc.stdin.flush()
while True:
line = proc.stdout.readline()
if not line or 'LOCKED_NOW' in line:
break
def send_one(idx):
local = Client('http://localhost:8081', timeout=10)
try:
res = local.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 503, actor=alice, body={'text': f'err-{tag}-{idx}'}, headers={'Idempotency-Key': f'err-{tag}-{idx}'})
return res['status']
except Failure:
return 0
with ThreadPoolExecutor(max_workers=count) as ex:
statuses = list(ex.map(send_one, range(count)))
proc.stdin.write("COMMIT;\n\\q\n")
proc.stdin.flush()
proc.communicate(timeout=10)
return sum(1 for s in statuses if s == 503)
def run_profile(g, prof, duration=20, concurrency=6):
print(f'=== Running Track 1 profile: {prof["name"]} ===')
compose('up', '-d', '--force-recreate', 'otel-collector', env_extra=prof['env'])
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', 'worker', env_extra=prof['env'])
c = Client('http://localhost:8081')
wait_api_ready(c)
alice, _, _, chat = c.bootstrap()
for i in range(10):
c.message(alice, chat, f'warmup-{i}')
time.sleep(8)
accepted_before = prom_scalar(g, 'sum(otelcol_receiver_accepted_spans_total)')
sent_before = prom_scalar(g, 'sum(otelcol_exporter_sent_spans_total)')
samples = []
stop_sample = threading.Event()
def sampler():
while not stop_sample.is_set():
try:
samples.append(sample_stats())
except Exception:
pass
stop_sample.wait(5)
sam_th = threading.Thread(target=sampler, daemon=True)
sam_th.start()
barrier = threading.Barrier(concurrency)
def worker_fn(wid):
local = Client('http://localhost:8081', timeout=5)
barrier.wait()
deadline = time.monotonic() + duration
lats = []
errs = 0
idx = 0
while time.monotonic() < deadline:
t = time.monotonic()
try:
local.message(alice, chat, f't1-{prof["name"]}-{wid}-{idx}')
lats.append(time.monotonic() - t)
except Failure:
errs += 1
idx += 1
return lats, errs
t_start = time.time()
with ThreadPoolExecutor(max_workers=concurrency) as ex:
results = list(ex.map(worker_fn, range(concurrency)))
elapsed = time.time() - t_start
stop_sample.set()
sam_th.join(timeout=6)
err_captured = 0
slow_captured = 0
err_injected = 0
if prof['name'] != 'telemetry_off':
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={**prof['env'], 'FAULT_HANDLER_DELAY_MS': '200'})
wait_api_ready(c)
t_slow_start = time.time()
for k in range(5):
c.message(alice, chat, f'slow-{prof["name"]}-{k}')
t_slow_end = time.time()
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={**prof['env'], 'FAULT_HANDLER_DELAY_MS': '0'})
wait_api_ready(c)
t_err_start = time.time()
err_injected += trigger_503_batch(alice, chat, f'{prof["name"]}-b0', count=5)
err_injected += trigger_503_batch(alice, chat, f'{prof["name"]}-b1', count=5)
t_err_end = time.time()
time.sleep(10)
err_res = g.tempo_search('{ resource.service.name = "messenger-api" && status = error }', t_err_start - 5, t_err_end + 15, limit=50)
err_captured = len(err_res.get('traces', []))
slow_res = g.tempo_search('{ resource.service.name = "messenger-api" && duration > 150ms && status != error }', t_slow_start - 5, t_slow_end + 15, limit=50)
slow_captured = len(slow_res.get('traces', []))
else:
time.sleep(8)
accepted_after = prom_scalar(g, 'sum(otelcol_receiver_accepted_spans_total)')
sent_after = prom_scalar(g, 'sum(otelcol_exporter_sent_spans_total)')
accepted_delta = max(0, round(accepted_after - accepted_before))
sent_delta = max(0, round(sent_after - sent_before))
drop_ratio = max(0.0, round(1.0 - (sent_delta / accepted_delta), 4)) if accepted_delta > 0 else 0.0
lats = sorted(x for ls, _ in results for x in ls)
errs = sum(e for _, e in results)
def pct(p):
return round(1000 * lats[max(0, math.ceil(p * len(lats)) - 1)], 2) if lats else None
avg_cpu = {}
last_mem = {}
if samples:
for k in samples[0]:
avg_cpu[k] = round(sum(s[k]['cpu_pct'] for s in samples if k in s) / len(samples), 2)
last_mem[k] = samples[-1].get(k, {}).get('mem')
return {
'profile': prof['name'],
'duration_seconds': duration,
'concurrency': concurrency,
'successful_requests': len(lats),
'failed_requests': errs,
'rps': round(len(lats) / elapsed, 2),
'latency_ms': {'p50': pct(0.50), 'p95': pct(0.95), 'p99': pct(0.99)},
'collector_spans_accepted': accepted_delta,
'tempo_spans_exported': sent_delta,
'span_drop_ratio': drop_ratio,
'injected_5xx_errors_captured': f'{min(err_injected, err_captured)}/{err_injected}' if prof['name'] != 'telemetry_off' else '0/10 (disabled)',
'injected_slow_gt150ms_captured': f'{min(5, slow_captured)}/5' if prof['name'] != 'telemetry_off' else '0/5 (disabled)',
'avg_cpu_pct_under_load': avg_cpu,
'mem_under_load': last_mem,
}
def main():
g = GrafanaClient('http://localhost:3000')
g.wait_ready(timeout=90)
results = []
try:
for prof in PROFILES:
results.append(run_profile(g, prof))
finally:
compose('up', '-d', '--force-recreate', 'otel-collector', env_extra=PROFILES[3]['env'])
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', 'worker', env_extra=PROFILES[3]['env'])
summary = {'track': 'cost-of-observability', 'profiles': results}
dest = ROOT / 'evidence/track1-observability-cost.json'
dest.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
print(json.dumps(summary, indent=2, ensure_ascii=False))
if __name__ == '__main__':
main()
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""Verify Level 3+4 observability signals, redaction, and end-to-end API->Worker trace correlation."""
import json
from pathlib import Path
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'student-tests'))
from client import Client, check
from grafana_helper import GrafanaClient
def extract_spans(trace_json):
spans = []
for batch in trace_json.get('batches', []):
svc = 'unknown'
for attr in batch.get('resource', {}).get('attributes', []):
if attr.get('key') == 'service.name':
svc = attr.get('value', {}).get('stringValue', 'unknown')
for ss in batch.get('scopeSpans', []):
for sp in ss.get('spans', []):
attrs = {a['key']: a.get('value', {}) for a in sp.get('attributes', [])}
spans.append({
'service': svc,
'name': sp.get('name'),
'span_id': sp.get('spanId'),
'parent_span_id': sp.get('parentSpanId'),
'attrs': attrs,
})
return spans
def main():
g = GrafanaClient('http://localhost:3000')
g.wait_ready(timeout=90)
c = Client('http://localhost:8081')
t_start = time.time()
alice, bob, _, chat = c.bootstrap()
secret_marker = 'SECRET_MSG_BODY_MUST_NOT_LEAK_' + uuid.uuid4().hex[:8]
c.message(alice, chat, secret_marker)
att, _ = c.attachment(alice, chat)
ready = c.wait_ready(bob, att, wait_seconds=60)
check(ready['status'] == 'ready', 'attachment did not finish')
# Wait for BatchSpanProcessor + PeriodicMetricReader + Prometheus scrape
time.sleep(12)
# 1. Verify dashboard provisioned in Grafana
dash = g.get_json('/api/dashboards/uid/mtusi-lab6-obs')
check(dash['dashboard']['uid'] == 'mtusi-lab6-obs', 'dashboard not provisioned')
# 2. Verify required metrics exist and have NO forbidden high-cardinality labels
forbidden = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'filename', 'text'}
required_metrics = [
'http_server_requests_total',
'http_server_request_duration_seconds_bucket',
'worker_jobs_total',
'worker_job_duration_seconds_bucket',
'attachment_time_to_ready_seconds_bucket',
'worker_queue_depth',
'worker_oldest_job_age_seconds',
'db_pool_connections',
'worker_threads',
'process_memory_rss_bytes',
]
metric_counts = {}
for m in required_metrics:
res = g.prom_query(m)
series = res.get('data', {}).get('result', [])
if not series:
all_names = g.get_json('/api/datasources/proxy/uid/prometheus/api/v1/label/__name__/values').get('data', [])
print('Available app metrics:', [x for x in all_names if any(x.startswith(p) for p in ('http_', 'worker_', 'attachment_', 'db_', 'process_', 'otelcol_'))])
check(len(series) > 0, f'missing Prometheus metric: {m}')
for s in series:
bad = forbidden.intersection(s.get('metric', {}).keys())
check(not bad, f'forbidden high-cardinality labels on {m}: {bad}')
metric_counts[m] = len(series)
# 3. Verify end-to-end trace across messenger-api and messenger-worker in Tempo
traces = []
for _ in range(15):
search = g.tempo_search('{ resource.service.name = "messenger-worker" && name = "worker.process" }', t_start - 5, time.time() + 5, limit=20)
traces = search.get('traces', [])
if traces:
break
time.sleep(1.5)
check(len(traces) > 0, 'no worker.process trace found in Tempo')
matched_trace_id = None
matched_spans = []
for item in traces:
tid = item['traceID']
tr = g.tempo_trace(tid)
spans = extract_spans(tr)
services = {s['service'] for s in spans}
names = {s['name'] for s in spans}
if 'messenger-api' in services and 'messenger-worker' in services and 'outbox.publish' in names and 'worker.process' in names:
matched_trace_id = tid
matched_spans = spans
break
check(matched_trace_id is not None, 'no unified W3C trace linking messenger-api -> outbox.publish -> worker.process found')
# 4. Verify correlated structured logs in Loki and zero secret/body leaks
ns_start = int((t_start - 5) * 1e9)
ns_end = int((time.time() + 5) * 1e9)
api_logs = g.loki_query_range('{service_name="messenger-api"}', ns_start, ns_end, limit=200)
worker_logs = g.loki_query_range('{service_name="messenger-worker"}', ns_start, ns_end, limit=200)
api_streams = api_logs.get('data', {}).get('result', [])
worker_streams = worker_logs.get('data', {}).get('result', [])
check(len(api_streams) > 0 and len(worker_streams) > 0, 'missing structured logs in Loki')
all_log_text = json.dumps(api_streams + worker_streams, ensure_ascii=False)
check(secret_marker not in all_log_text, 'LEAK: message text appeared in Loki logs')
check(alice['token'] not in all_log_text, 'LEAK: session token appeared in Loki logs')
check(alice['registration']['password'] not in all_log_text, 'LEAK: password appeared in Loki logs')
correlated = [s for s in (api_streams + worker_streams) if s.get('stream', {}).get('trace_id') == matched_trace_id or any(matched_trace_id in v[1] for v in s.get('values', []))]
check(len(correlated) > 0, f'no Loki logs correlated to trace_id={matched_trace_id}')
summary = {
'status': 'PASS',
'verified_metrics': metric_counts,
'e2e_trace_id': matched_trace_id,
'e2e_span_services': sorted({s['service'] for s in matched_spans}),
'e2e_span_names': sorted({s['name'] for s in matched_spans}),
'loki_api_streams': len(api_streams),
'loki_worker_streams': len(worker_streams),
'loki_correlated_entries': len(correlated),
'redaction_checks': {'message_body_leaked': False, 'token_leaked': False, 'password_leaked': False},
}
dest = ROOT / 'evidence/lab6-signals.json'
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
print(json.dumps(summary, indent=2, ensure_ascii=False))
if __name__ == '__main__':
main()