Files
mtusi2026lab6/research/observability_cost.py
T

207 lines
10 KiB
Python

"""Track 1: same synthetic offered workload, off/full/25%/10%, 3 repeats."""
import concurrent.futures
import json
import math
import os
import re
import statistics
import subprocess
import threading
import time
import urllib.request
from datetime import UTC, datetime
from common import ROOT, TEMPO, Client, cgroups, compose, get, scalar, wait_for
PROFILES = [('off', '0', '0'), ('full', '1', '1'), ('sample25', '1', '.25'), ('sample10', '1', '.1')]
DURATION = 10
OFFERED = 40
def percentile(values, fraction):
return sorted(values)[min(len(values)-1, math.ceil(len(values)*fraction)-1)]
def observation(name):
return scalar('sum(messenger_telemetry_export{service_name="messenger-api",observation="'+name+'"})')
def telemetry_snapshot(instance_ids):
# Read Collector endpoints directly after quiescence: no extra Prometheus
# scrape delay may move warmup payload into the measurement baseline.
with urllib.request.urlopen('http://127.0.0.1:19464/metrics', timeout=5) as response:
text = response.read().decode()
counts = {name: 0.0 for name in ('spans_recorded', 'spans_exported', 'spans_export_failed',
'spans_pending', 'spans_in_flight', 'spans_queue_lost',
'traces_wire_bytes', 'logs_wire_bytes', 'metrics_wire_bytes')}
for line in text.splitlines():
if line.startswith('messenger_telemetry_export{') and any('service_instance_id="'+value+'"' in line for value in instance_ids):
match = re.search(r'observation="([^"]+)"', line)
if match and match[1] in counts:
counts[match[1]] += float(line.rsplit(' ', 1)[1])
with urllib.request.urlopen('http://127.0.0.1:18888/metrics', timeout=5) as response:
text = response.read().decode()
accepted = [float(line.rsplit(' ', 1)[1]) for line in text.splitlines()
if line.startswith('otelcol_receiver_accepted_spans') and not line.startswith('#')]
counts['collector_accepted_spans'] = sum(accepted)
return counts
def exists(trace_id):
if not trace_id or trace_id == '0'*32:
return False
try:
return bool(get(TEMPO + '/api/traces/' + trace_id).get('batches'))
except Exception:
return False
class DockerSamples:
def __init__(self):
self.stop = threading.Event()
self.rows = []
self.ids = compose('ps', '-q').split()
self.thread = threading.Thread(target=self.run, daemon=True)
def run(self):
while not self.stop.is_set():
raw = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *self.ids], text=True)
self.rows.append({'at': time.monotonic(), 'containers': [json.loads(line) for line in raw.splitlines()]})
self.stop.wait(1)
def __enter__(self):
self.thread.start()
return self
def __exit__(self, *args):
self.stop.set()
self.thread.join(timeout=5)
def run_profile(client, profile, repeat):
name, enabled, ratio = profile
env = {**os.environ, 'OTEL_ENABLED': enabled, 'OTEL_SAMPLE_RATIO': ratio}
command = ['docker','compose','-f','compose.yaml','-f','compose.observability-fault.yaml',
'up','-d','--no-deps','--force-recreate','api','worker','dispatcher']
subprocess.run(command, env=env, cwd=ROOT, check=True, capture_output=True)
wait_for(lambda: client.request('GET','/api/v1/users/me')[0] == 200, 30)
# Establish each process/meter and warm the same endpoint before taking baselines.
instance_ids = set()
for _ in range(40):
status, _, headers = client.request('GET','/api/v1/users/me')
assert status == 200
instance_ids.add({key.lower():value for key,value in headers.items()}['x-instance-id'])
time.sleep(.1)
assert len(instance_ids) == 2
time.sleep(10)
before = telemetry_snapshot(instance_ids)
memory_before = cgroups(['api','worker','collector'])
compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-c',
"INSERT INTO test_faults(point,action) VALUES ('after_upload_commit','error'),('after_upload_commit','error')")
calls = []
dropped = 0
lock_future = None
started = time.monotonic()
def request(index):
begin = time.monotonic()
if index in (80, 240):
result = client.request('POST',f'/api/v1/chats/{client.chat}/attachments?filename=fixture.png',
(ROOT/'tests/fixtures/sample.png').read_bytes(), {'Content-Type':'image/png'})
else:
result = client.request('GET','/api/v1/users/me')
status, _, headers = result
headers = {key.lower():value for key,value in headers.items()}
return {'index':index,'status':status,'duration_s':time.monotonic()-begin,
'trace_id':headers.get('x-trace-id'), 'sampled':headers.get('x-trace-sampled')=='true',
'kind':'controlled_upload_error' if index in (80,240) else 'read'}
with DockerSamples() as samples, concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
pending = set()
for index in range(DURATION*OFFERED):
target = started + index/OFFERED
delay = target-time.monotonic()
if delay > 0:
time.sleep(delay)
if index == 160:
lock_future = executor.submit(compose,'exec','-T','postgres','psql','-U','messenger','-d','messenger','-c',
'BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(0.35); COMMIT;')
ready = [future for future in pending if future.done()]
for future in ready:
calls.append(future.result())
pending.remove(future)
if len(pending) >= 15:
dropped += 1
else:
pending.add(executor.submit(request,index))
for future in pending:
calls.append(future.result())
if lock_future:
lock_future.result()
elapsed = time.monotonic()-started
assert sum(x['status']==500 for x in calls)==2, 'Expected exactly two controlled upload errors'
assert all(x['status'] in (200,500) for x in calls), 'Unexpected business failure'
time.sleep(10)
after = telemetry_snapshot(instance_ids)
memory_after = cgroups(['api','worker','collector'])
rare = [row for row in calls if row['status']==500 or (row['kind']=='read' and row['duration_s']>=.15)]
for row in rare:
row['found_in_tempo'] = exists(row['trace_id'])
if enabled=='1' and row['sampled']:
assert row['found_in_tempo'], 'Sampled rare trace failed ingestion'
latency = [row['duration_s'] for row in calls]
deltas = {key: after[key]-before[key] for key in before}
return {'profile':name,'instance_ids':sorted(instance_ids),'enabled':enabled,'sampling_ratio':float(ratio),'repeat':repeat,
'offered_rps':OFFERED,'duration_s':DURATION,'elapsed_s':round(elapsed,6),
'scheduled':DURATION*OFFERED,'not_sent':dropped,'sent':len(calls),
'successful':sum(row['status']==200 for row in calls),'controlled_500':2,
'successful_rps':sum(row['status']==200 for row in calls)/elapsed,
'latency_s':{'p50':percentile(latency,.5),'p95':percentile(latency,.95),'p99':percentile(latency,.99)},
'sampled_requests':sum(row['sampled'] for row in calls),
'rare_probes':rare,'telemetry_before':before,'telemetry_after':after,'telemetry_delta':deltas,
'cgroups_before':memory_before,'cgroups_after':memory_after,
'docker_samples':samples.rows,'requests':sorted(calls,key=lambda row:row['index'])}
def main():
report = {'started_at':datetime.now(UTC).isoformat(),'track':'observability cost','runs':[],
'method':{'profiles':PROFILES,'repeats':3,'offered_rps':OFFERED,'measurement_s':DURATION,
'latency_clock':'client perf_counter, includes network and queueing',
'rare_slow':'one 350ms exclusive users-table lock/run',
'rare_errors':'two actual API500 after durable upload COMMIT/run through private local fault hooks',
'wire_bytes':'protobuf body length on each SDK HTTP send, retries included; excludes HTTP/TLS headers',
'sdk_queue_losses':'conservation after 10s quiescence, separate from sampled-out spans',
'baseline':'40 warmup requests at 10/s, then10s silence; direct Collector endpoints avoid Prometheus scrape delay',
'post_window':'10s silence before direct Collector counters; bytes include periodic metric exports in observation window',
'resources':'same image/CPU/RAM; sequential profiles, all services on one Docker host'}}
client = Client()
try:
for repeat in range(1,4):
order = PROFILES[repeat-1:]+PROFILES[:repeat-1]
for profile in order:
row = run_profile(client,profile,repeat)
report['runs'].append(row)
(ROOT/'evidence/observability-cost.json').write_text(json.dumps(report,indent=2))
print(profile[0],repeat,'PASS',round(row['successful_rps'],2),'RPS',flush=True)
finally:
subprocess.run(['docker','compose','up','-d','--no-deps','--force-recreate','api','worker','dispatcher'],cwd=ROOT,check=True,capture_output=True)
report['passed'] = len(report['runs'])==12
report['finished_at'] = datetime.now(UTC).isoformat()
summary={}
for name,_,_ in PROFILES:
runs=[row for row in report['runs'] if row['profile']==name]
summary[name]={'median_success_rps':statistics.median(row['successful_rps'] for row in runs),
'median_p95_s':statistics.median(row['latency_s']['p95'] for row in runs),
'median_trace_wire_bytes':statistics.median(row['telemetry_delta']['traces_wire_bytes'] for row in runs),
'rare_total':sum(len(row['rare_probes']) for row in runs),
'rare_sampled':sum(sum(x['sampled'] for x in row['rare_probes']) for row in runs),
'export_failed_spans':sum(row['telemetry_delta']['spans_export_failed'] for row in runs),
'queue_lost_spans':sum(row['telemetry_delta']['spans_queue_lost'] for row in runs)}
report['summary']=summary
(ROOT/'evidence/observability-cost.json').write_text(json.dumps(report,indent=2))
print(json.dumps(summary,indent=2))
if __name__=='__main__':
main()