ЛР6: наблюдаемость, сквозные traces и исследование sampling

This commit is contained in:
2026-11-20 11:58:34 +03:00
parent 470d9d6f1e
commit 3b0f4ab281
80 changed files with 22966 additions and 50 deletions
+52
View File
@@ -0,0 +1,52 @@
"""Stop worker, accept queued, restart API/broker, then complete the same attachment."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,Failure
def docker(*args):return subprocess.check_output(['docker',*args],text=True).strip()
def main():
c=Client();alice,bob,eve,chat=c.bootstrap();record={}
before=json.loads(subprocess.check_output([sys.executable,'scripts/snapshot.py'],text=True))
try:
docker('compose','stop','worker','dispatcher')
queued,raw=c.attachment(alice,chat)
assert queued['status']=='queued'
message=c.message(alice,chat,'accepted with worker stopped',attachments=[queued['id']])['json']
c.call('GET','/api/v1/attachments/'+queued['id']+'/content',409,actor=bob)
killed=docker('compose','ps','-q','api').splitlines()
for container in killed:docker('kill','--signal=KILL',container)
record['killed_api_containers']=killed
docker('compose','up','-d','--wait','--no-deps','api')
time.sleep(2)
assert c.call('GET','/api/v1/attachments/'+queued['id'],actor=bob,schema='Attachment')['json']['status']=='queued'
docker('compose','up','-d','--no-deps','dispatcher')
deadline=time.monotonic()+10
while int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))<1:
assert time.monotonic()<deadline;time.sleep(.1)
docker('compose','stop','dispatcher')
length_before=int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))
docker('compose','restart','broker')
docker('compose','up','-d','--wait','--no-deps','broker')
length_after=int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))
assert length_after>=length_before>=1
record['stream_entries_before_after_broker_restart']=[length_before,length_after]
docker('compose','up','-d','--no-deps','worker','dispatcher')
ready=c.wait_ready(bob,queued)
assert c.call('GET','/api/v1/attachments/'+queued['id']+'/content',actor=bob)['bytes']==raw
record.update(attachment_id=queued['id'],original_sha256=hashlib.sha256(raw).hexdigest(),status=ready['status'],variants=[v['name'] for v in ready['variants']],old_bearer_survived=True,message_attachment_retained=message['attachment_ids']==[queued['id']])
finally:docker('compose','up','-d','--no-deps','worker','dispatcher')
after=json.loads(subprocess.check_output([sys.executable,'scripts/snapshot.py'],text=True))
record['before']=before;record['after']=after
print(json.dumps(record,indent=2))
if __name__=='__main__':main()
+24
View File
@@ -0,0 +1,24 @@
"""Small deterministic PNG helpers; generation happens outside measurement."""
import random
import struct
import zlib
def chunk(name, data):
return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data) & 0xffffffff)
def png(width, height, noise=False, rgb=True):
channels = 3 if rgb else 1
rand = random.Random(2301)
encoded = zlib.compressobj(1)
parts = []
for _ in range(height):
line = bytes(rand.getrandbits(8) for _ in range(width * channels)) if noise else b'\x7f' * (width * channels)
parts.append(encoded.compress(b'\0' + line))
parts.append(encoded.flush())
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 2 if rgb else 0, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
def bomb():
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'x')) + chunk(b'IEND', b'')
+257
View File
@@ -0,0 +1,257 @@
"""Real OTLP evidence, controlled incidents and bounded telemetry-backend outage."""
import argparse
import base64
import concurrent.futures
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from urllib.parse import urlencode
import urllib.request
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, Failure
BASE=os.environ.get('BASE_URL','http://127.0.0.1:18093')
PROM=os.environ.get('PROMETHEUS_URL','http://127.0.0.1:19096')
LOKI=os.environ.get('LOKI_URL','http://127.0.0.1:13106')
TEMPO=os.environ.get('TEMPO_URL','http://127.0.0.1:13206')
COLLECTOR=os.environ.get('COLLECTOR_URL','http://127.0.0.1:18896')
OPENER=urllib.request.build_opener(urllib.request.ProxyHandler({}))
def get(url):
req=urllib.request.Request(url,headers={'Accept':'application/json'})
with OPENER.open(req,timeout=10) as response:
return json.load(response)
def prom(query):
return get(PROM+'/api/v1/query?'+urlencode({'query':query}))['data']['result']
def scalar(query):
rows=prom(query)
return float(rows[0]['value'][1]) if rows else 0
def logs(query, start=None, limit=2000):
params={'query':query,'start':str(int((start or time.time()-600)*1e9)),
'end':str(time.time_ns()),'limit':str(limit),'direction':'forward'}
result=get(LOKI+'/loki/api/v1/query_range?'+urlencode(params))['data']['result']
return [json.loads(value) for stream in result for stamp,value in stream['values']]
def trace(identifier):
return get(TEMPO+'/api/traces/'+identifier)
def spans(data):
result=[]
for batch in data.get('batches',data.get('resourceSpans',[])):
service=next(a['value']['stringValue'] for a in batch['resource']['attributes'] if a['key']=='service.name')
for scope in batch.get('scopeSpans',[]):
for span in scope['spans']:
result.append(dict(span,service=service))
return result
def wait(function,timeout=60):
end=time.monotonic()+timeout
while time.monotonic()<end:
try:
result=function()
if result:return result
except (OSError,ValueError,Failure):
pass
time.sleep(.5)
raise AssertionError('Timed out: '+function.__name__)
def compose(*args):
return subprocess.check_output(['docker','compose',*args],text=True).strip()
def save(name,data):
(ROOT/'evidence'/name).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
def upload(c,actor,chat,tid):
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
return c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=private-canary.png',202,
actor=actor,raw=raw,headers={'Content-Type':'image/png',
'traceparent':'00-'+tid+'-0123456789abcdef-01'},schema='Attachment')
def proof():
wait(lambda:get(LOKI+'/loki/api/v1/labels'))
wait(lambda:get(TEMPO+'/api/search'))
proof_start=time.time()
c=Client(BASE);a,b,e,chat=c.bootstrap()
tid=uuid.uuid4().hex
marker='SECRET_MESSAGE_CANARY_'+uuid.uuid4().hex
c.message(a,chat,marker)
response=upload(c,a,chat,tid)
ready=c.wait_ready(b,response['json'])
def completed_trace():
data=trace(tid)
return data if any(s['name']=='attachment process' for s in spans(data)) else None
data=wait(completed_trace)
rows=spans(data)
upload_span=next(s for s in rows if s['kind']=='SPAN_KIND_SERVER')
publish=next(s for s in rows if s['kind']=='SPAN_KIND_PRODUCER')
consumer=next(s for s in rows if s['kind']=='SPAN_KIND_CONSUMER')
assert consumer['parentSpanId']==publish['spanId']
index={s['spanId']:s for s in rows}
parent=publish
while parent['spanId']!=upload_span['spanId']:
parent=index[parent['parentSpanId']]
assert any(s['service']=='messenger-worker' and s['name'].startswith('s3.') for s in rows)
assert any(s['service']=='messenger-worker' and s['name']=='db.transaction' for s in rows)
query='{service_name=~"messenger-.*"} | json | trace_id="'+tid+'"'
records=wait(lambda: logs(query) if len(logs(query))>=4 else None)
assert {r['event'] for r in records}>={'http_request','attachment_accepted','job_published','job_processed'}
assert any(r.get('request_id')==response['headers'].get('X-Request-Id') for r in records)
assert all(len(r['trace_id'])==32 and len(r['span_id'])==16 for r in records)
all_logs=logs('{service_name=~"messenger-.*"}',start=proof_start,limit=5000)
payload=json.dumps(all_logs)+json.dumps(data)
for value in [marker,a['token'],a['registration']['password'],a['registration']['username'],'private-canary.png']:
assert value not in payload, 'business/credential canary leaked'
metric_rows=prom('{service_name=~"messenger-.*"}')
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','filename','url','job_id','trace_id','span_id'}
assert all(not forbidden.intersection(row['metric']) for row in metric_rows)
names={r['metric']['__name__'] for r in metric_rows}
assert {'http_server_duration_seconds_bucket','jobs_processed_total','queue_depth','queue_oldest_age_seconds','db_pool_used','worker_capacity'}<=names
save('trace-proof.json',{'trace_id':tid,'request_id':response['headers'].get('X-Request-Id'),
'status':ready['status'],'consumer_parent_matches_producer':True,'producer_descends_from_upload':True,
'api_worker_logs_correlated':True,'secret_canaries_absent':True,'metric_labels_allowlisted':True,
'trace':data,'logs':records})
# Retry is a real S3 outage after durable acceptance, not fabricated spans.
compose('stop','worker')
retry_tid=uuid.uuid4().hex
queued=upload(c,a,chat,retry_tid)['json']
paused=False
try:
compose('pause','s3');paused=True
compose('up','-d','--no-deps','worker')
def attempted():
raw=compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',
"SELECT attempt FROM attachment_jobs WHERE 1=1 AND attachment_id = '"+queued['id']+"';")
return int(raw)>=1
wait(attempted)
time.sleep(5)
finally:
if paused:compose('unpause','s3')
compose('up','-d','--no-deps','worker')
wait(lambda:c.call('GET','/health/ready',schema='Health'))
c.wait_ready(a,queued)
def retried():
data=trace(retry_tid)
return data if len([s for s in spans(data) if s['kind']=='SPAN_KIND_CONSUMER'])>=2 else None
retry_data=wait(retried)
retry_records=wait(lambda:logs('{service_name="messenger-worker"} | json | trace_id="'+retry_tid+'" | event="job_retry"'))
save('retry-trace.json',{'trace_id':retry_tid,'retry_observed':True,'trace':retry_data,'logs':retry_records})
print('PASS: actual API/producer/consumer/S3/DB chain, correlated safe logs, real retry and low cardinality.')
def alerts():
return get(PROM+'/api/v1/alerts')['data']['alerts']
def firing(name):
return [a for a in alerts() if a['labels']['alertname']==name and a['state']=='firing']
def incidents():
c=Client(BASE);a,b,e,chat=c.bootstrap();result={}
start=time.time()
compose('stop','worker')
try:
queued=[c.attachment(a,chat)[0] for _ in range(3)]
observed=wait(lambda:scalar('max(queue_depth{service_name="messenger-dispatcher"})')>=3)
fired=wait(lambda:firing('QueueLag'))
detected=time.time()
metrics={q:prom(q) for q in ['queue_depth','queue_oldest_age_seconds','worker_busy','worker_capacity']}
result['worker_stop']={'injected_at':start,'detected_at':detected,
'detection_seconds':detected-start,'firing':fired,'metrics':metrics,
'diagnosis':'Backlog and oldest age grow; worker completion stops while API acceptance still succeeds. Gauges expire after 30s.'}
finally:
compose('up','-d','--no-deps','worker')
for att in queued:c.wait_ready(a,att)
wait(lambda:scalar('max(queue_depth{service_name="messenger-dispatcher"})')==0)
wait(lambda:not firing('QueueLag'))
result['worker_stop']['resolved_at']=time.time()
# Keep readiness SELECT 1 available while real session SQL is blocked.
lock=subprocess.Popen(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1',
'-c',"BEGIN; LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(35); COMMIT;"],
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
time.sleep(1)
db_start=time.time();stop=False;errors=[];error_trace=uuid.uuid4().hex
def traffic():
while not stop:
r=c.call('GET','/api/v1/users/me',[200,503],actor=a,
headers={'traceparent':'00-'+error_trace+'-0123456789abcdef-01'})
if r['status']==503:errors.append(r['elapsed'])
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
futures=[pool.submit(traffic) for _ in range(4)]
try:
fired=wait(lambda:firing('APIHighErrorRate'),timeout=50)
detected=time.time()
result['db_lock']={'injected_at':db_start,'detected_at':detected,'detection_seconds':detected-db_start,
'firing':fired,'error_latencies_seconds':errors.copy(),'trace_id':error_trace}
lock.wait(timeout=45)
finally:
stop=True
for future in futures:future.result()
finally:
stop=True
if lock.poll() is None:
lock.terminate();lock.wait(timeout=5)
wait(lambda:c.call('GET','/api/v1/users/me',actor=a,schema='User'))
wait(lambda:not firing('APIHighErrorRate'),timeout=70)
data=wait(lambda:trace(error_trace))
assert any(s['name']=='db.transaction' and s.get('status',{}).get('code')=='STATUS_CODE_ERROR' for s in spans(data))
result['db_lock'].update(resolved_at=time.time(),trace=data,
diagnosis='Server 5xx spans contain slow/error PostgreSQL transaction; health remains available; sessions lock is the bottleneck.')
save('incidents.json',result)
print('PASS: worker-stop and real DB-lock incidents, local firing/resolved and causal DB traces.')
def collector_metrics():
with OPENER.open(COLLECTOR+'/metrics',timeout=5) as r:raw=r.read().decode()
result={}
for line in raw.splitlines():
if line.startswith('otelcol_') and not line.startswith('#'):
name=line.split('{')[0].split(' ')[0]
try:result[name]=result.get(name,0)+float(line.rsplit(' ',1)[-1])
except ValueError:pass
return result
def backend_outage():
c=Client(BASE);a,b,e,chat=c.bootstrap();before=collector_metrics()
cid=compose('ps','-q','otel-collector')
samples=[];messages=[];attachments=[];start=time.time()
compose('stop','tempo')
try:
for i in range(45):
for _ in range(3):
messages.append(c.message(a,chat,'synthetic-backend-outage')['json']['id'])
if i%10==0:
att,_=c.attachment(a,chat);attachments.append(c.wait_ready(a,att)['id'])
stat=json.loads(subprocess.check_output(['docker','stats','--no-stream','--format','{{json .}}',cid],text=True))
samples.append({'elapsed':time.time()-start,'memory':stat['MemUsage'],'cpu':stat['CPUPerc']})
time.sleep(1)
during=collector_metrics()
assert during.get('otelcol_exporter_send_failed_spans_total',0)>before.get('otelcol_exporter_send_failed_spans_total',0)
assert during.get('otelcol_exporter_queue_size',0)<=128*2
history=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=b,schema='MessagePage')['json']
got={m['id'] for m in history['items']}
if history['next_cursor']:
history2=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+history['next_cursor'],actor=b,schema='MessagePage')['json']
got.update(m['id'] for m in history2['items'])
assert set(messages)<=got
finally:compose('up','-d','--no-deps','tempo')
wait(lambda:get(TEMPO+'/api/search'))
tid=uuid.uuid4().hex
upload(c,a,chat,tid)
wait(lambda:trace(tid))
save('backend-outage.json',{'duration_seconds':time.time()-start,'confirmed_messages':len(messages),
'confirmed_attachments_ready':len(attachments),'all_confirmed_messages_retained':True,
'collector_samples':samples,'before':before,'during':during,'recovered_trace_id':tid})
print('PASS: Tempo unavailable, finite Collector buffers/drops, API writes/jobs retained, fresh trace after recovery.')
if __name__=='__main__':
parser=argparse.ArgumentParser()
parser.add_argument('phase',choices=['proof','incidents','backend'])
args=parser.parse_args()
{'proof':proof,'incidents':incidents,'backend':backend_outage}[args.phase]()
+193
View File
@@ -0,0 +1,193 @@
"""Fixed-arrival mixed workload: SDK off, full traces, 10% and 25% head sampling."""
import concurrent.futures
import http.client
import json
import os
from pathlib import Path
import socket
import statistics
import subprocess
import sys
import threading
import time
from urllib.parse import urlsplit
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parent))
from observability import Client, BASE, compose, collector_metrics, scalar, prom, logs, wait, save
class DockerHTTP(http.client.HTTPConnection):
def connect(self):
self.sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
self.sock.settimeout(8)
self.sock.connect(DOCKER_SOCKET)
context=json.loads(subprocess.check_output(['docker','context','inspect'],text=True))[0]
DOCKER_SOCKET=urlsplit(context['Endpoints']['docker']['Host']).path
def stats(container):
connection=DockerHTTP('localhost')
try:
connection.request('GET','/containers/'+container+'/stats?stream=false&one-shot=true')
response=connection.getresponse()
assert response.status==200
data=json.load(response)
finally:connection.close()
memory=data.get('memory_stats',{})
details=memory.get('stats',{})
usage=memory.get('usage',0)
return {'cpu_seconds':data['cpu_stats']['cpu_usage']['total_usage']/1e9,
'anonymous_bytes':details.get('anon',details.get('rss',0)),
'working_set_bytes':max(0,usage-details.get('inactive_file',details.get('total_inactive_file',0))),
'rx_bytes':sum(n.get('rx_bytes',0) for n in data.get('networks',{}).values())}
def span_counts():
return {r['metric']['service_instance_id']:float(r['value'][1])
for r in prom('spans_finished{service_name=~"messenger-.*"}')}
def delta(previous,current):
return sum(max(0,value-previous.get(key,0)) for key,value in current.items())
def quantile(values,q):
return sorted(values)[min(len(values)-1,int((len(values)-1)*q))]
def set_mode(enabled,ratio):
env=os.environ.copy()
env.update(TELEMETRY_ENABLED=str(enabled),TRACE_SAMPLE_RATIO=str(ratio))
subprocess.run(['docker','compose','up','-d','--wait','--no-deps','api','worker','dispatcher'],env=env,
check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
c=Client(BASE)
wait(lambda:c.call('GET','/health/ready',schema='Health'))
return c
def probes(c,actor,mode):
results=[]
for duration in [3.5,3.5,3.5,1.2]:
query="BEGIN; LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep("+str(duration)+"); COMMIT;"
lock=subprocess.Popen(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-c',query],
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
try:
def locked():
value=compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',
"SELECT count(*) FROM pg_locks WHERE 1=1 AND relation = 'sessions'::regclass AND mode = 'AccessExclusiveLock' AND granted;")
return int(value)>0
wait(locked,timeout=5)
result=c.call('GET','/api/v1/users/me',[200,503],actor=actor)
assert result['status']==(503 if duration>3 else 200)
assert result['elapsed']>.1
results.append({'request_id':result['headers'].get('X-Request-Id'),
'status':result['status'],'latency_seconds':result['elapsed']})
finally:lock.wait(timeout=5)
if mode!='off':
time.sleep(3)
for row in results:
records=logs('{service_name="messenger-api"} | json | request_id="'+row['request_id']+'"',limit=10)
assert records
row['trace_sampled']=records[0]['sampled']
row['trace_id']=records[0]['trace_id']
else:
for row in results:row['trace_sampled']=False
return results
def run(mode,enabled,ratio,repeat,seconds,rps):
c=set_mode(enabled,ratio);a,b,e,chat=c.bootstrap()
for _ in range(10):c.call('GET','/api/v1/users/me',actor=a)
time.sleep(5)
names=compose('ps','-q','api','worker','dispatcher','otel-collector','postgres','loki','tempo','prometheus','grafana','s3','s3-store','broker','lb','redis').splitlines()
labels={}
for cid in names:
label=json.loads(subprocess.check_output(['docker','inspect',cid,'--format','{{json .Config.Labels}}'],text=True))
labels[cid]=label['com.docker.compose.service']
before={cid:stats(cid) for cid in names}
ingest_before=collector_metrics();spans_before=span_counts()
memory={cid:[] for cid in names};sampling_stop=threading.Event()
def sample():
while not sampling_stop.is_set():
for cid in names:
try:memory[cid].append(stats(cid))
except OSError:pass
sampling_stop.wait(1)
sampler=threading.Thread(target=sample,daemon=True);sampler.start()
latencies=[];failures=[];attachments=[];start=time.monotonic()
def request(i):
try:
if i%20==0:
result=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=cost.png',202,
actor=a,raw=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes(),
headers={'Content-Type':'image/png'},schema='Attachment')
return result['elapsed'],result['json']
if i%5==0:
result=c.message(a,chat,'fixed-synthetic-cost-payload')
else:result=c.call('GET','/api/v1/users/me',actor=a,schema='User')
return result['elapsed'],None
except Exception as error:return None,type(error).__name__
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
futures=[]
for i in range(seconds*rps):
delay=start+i/rps-time.monotonic()
if delay>0:time.sleep(delay)
futures.append(pool.submit(request,i))
for future in futures:
elapsed,att=future.result()
if elapsed is None:failures.append(att)
else:
latencies.append(elapsed)
if att:attachments.append(att)
load_wall=time.monotonic()-start
for att in attachments:c.wait_ready(a,att)
# Drain exporter batches and metric-reader intervals, then compare counters by instance.
time.sleep(5)
sampling_stop.set();sampler.join(timeout=15)
after={cid:stats(cid) for cid in names}
ingest_after=collector_metrics();spans_after=span_counts()
assert not failures, failures
resource={}
for cid in names:
service=labels[cid]
target=resource.setdefault(service,{'cpu_seconds':0,'peak_sampled_anonymous_bytes':0,'peak_sampled_working_set_bytes':0,'rx_bytes':0})
target['cpu_seconds']+=max(0,after[cid]['cpu_seconds']-before[cid]['cpu_seconds'])
target['rx_bytes']+=max(0,after[cid]['rx_bytes']-before[cid]['rx_bytes'])
target['peak_sampled_anonymous_bytes']+=max((s['anonymous_bytes'] for s in memory[cid]),default=0)
target['peak_sampled_working_set_bytes']+=max((s['working_set_bytes'] for s in memory[cid]),default=0)
counts={k:max(0,ingest_after.get(k,0)-ingest_before.get(k,0)) for k in [
'otelcol_receiver_accepted_spans_total','otelcol_receiver_accepted_log_records_total',
'otelcol_receiver_accepted_metric_points_total','otelcol_exporter_sent_spans_total',
'otelcol_exporter_send_failed_spans_total']}
finished=delta(spans_before,spans_after)
accepted=counts['otelcol_receiver_accepted_spans_total']
result={'mode':mode,'enabled':enabled,'sample_ratio':ratio,'repeat':repeat,
'arrival_rps':rps,'scheduled_requests':seconds*rps,'confirmed_requests':len(latencies),
'load_wall_seconds':load_wall,'successful_rps':len(latencies)/load_wall,
'p50_seconds':quantile(latencies,.5),'p95_seconds':quantile(latencies,.95),'p99_seconds':quantile(latencies,.99),
'errors':failures,'image_jobs_ready':len(attachments),'resource':resource,'collector_ingest':counts,
'sampled_spans_finished':finished,'sampled_spans_not_accepted_after_drain':max(0,finished-accepted)}
result['rare_probes']=probes(c,a,mode)
print(mode,repeat,'p95',round(result['p95_seconds'],5),'ingested spans',accepted,flush=True)
return result
def main():
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--seconds',type=int,default=20)
parser.add_argument('--rps',type=int,default=30)
parser.add_argument('--repeats',type=int,default=3)
args=parser.parse_args()
result={'method':'Fixed arrival mixed requests, 5% image uploads, 15% messages, 80% profile reads; same fixture/resources. No transparent retries.',
'notes':['CPU cgroup total across load plus exporter drain; includes renderer.',
'Anonymous/working-set memory sampled at 1Hz through read-only Docker stats API, not exact per-PID peak RSS.',
'Collector rx bytes include OTLP HTTP, Prometheus scrapes and backend replies; accepted signal counts are exact Collector counter deltas.',
'Fresh API/worker/dispatcher containers per setting; data/backends retained. Per-instance counter deltas ignore expired old series.',
'Rare SQL-lock probes run after resource/ingest measurement; three SQL-lock probes and one slow success per run; future runs synchronize on pg_locks.'],
'runs':[]}
modes=[('off',0,0),('full',1,1),('sample10',1,.1),('sample25',1,.25)]
try:
for repeat in range(args.repeats):
# Rotate order to reduce a fixed warm-cache/time-order advantage.
order=modes[repeat%len(modes):]+modes[:repeat%len(modes)]
for mode,enabled,ratio in order:
result['runs'].append(run(mode,enabled,ratio,repeat,args.seconds,args.rps))
save('observability-cost.json',result)
finally:set_mode(1,.25)
print('PASS: telemetry cost experiment completed; balanced 25% tracing restored.')
if __name__=='__main__':main()
+37
View File
@@ -0,0 +1,37 @@
"""Restart all stores and verify historical telemetry alongside public business persistence."""
import json
import os
from pathlib import Path
import subprocess
import time
from urllib.parse import urlencode
from observability import BASE,PROM,trace,spans,logs,get,wait,save
root=Path(__file__).resolve().parents[1]
identifier=json.loads((root/'evidence/trace-proof.json').read_text())['trace_id']
before_trace=trace(identifier)
before_ids={s['spanId'] for s in spans(before_trace)}
query='{service_name=~"messenger-.*"} | json | trace_id="'+identifier+'"'
before_logs=logs(query,start=time.time()-3600)
assert before_logs
at=time.time()-5
url=PROM+'/api/v1/query?'+urlencode({'query':'sum(http_server_requests_total)','time':str(at)})
before_metric=get(url)['data']['result']
assert before_metric
command=['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+BASE]
result=subprocess.run(command,capture_output=True,text=True)
(root/'evidence/persistence.txt').write_text(result.stdout+result.stderr)
assert result.returncode==0,result.stdout[-300:]
after_trace=wait(lambda:trace(identifier),timeout=90)
after_ids={s['spanId'] for s in spans(after_trace)}
assert before_ids<=after_ids
after_logs=wait(lambda:logs(query,start=time.time()-3600),timeout=90)
assert {json.dumps(r,sort_keys=True) for r in before_logs}<={json.dumps(r,sort_keys=True) for r in after_logs}
after_metric=wait(lambda:get(url)['data']['result'])
assert before_metric==after_metric
save('telemetry-persistence.json',{'trace_id':identifier,'historical_span_count':len(before_ids),
'historical_logs':len(before_logs),'fixed_metric_query_time':at,
'metric_before':before_metric,'metric_after':after_metric,
'business_data_and_existing_session_survived':True,'all_telemetry_volumes_restarted':True,
'trace_log_metric_history_survived':True})
print('PASS: full business restart, original Bearer, historical Tempo trace, Loki logs and fixed-time Prometheus sample.')
+188
View File
@@ -0,0 +1,188 @@
"""Real DB/S3/Redis fault injection. Stop production worker/dispatcher first."""
import concurrent.futures
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path[:0]=['/app/src',str(Path.cwd()/'tests')]
from PIL import Image
from client import Client
from pipeline import STREAM,GROUP,broker,connect,event,dispatch_once,process,ack
from objects import Objects
from postgres import setting
from admin import replay,version,cleanup
def main():
c=Client();alice,bob,eve,chat=c.bootstrap()
bus=broker(); objects=Objects(setting)
report={'invariants':{},'faults':[]}
def fetch(aid):
with connect() as conn:
a=conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s',(aid,)).fetchone()
j=conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s',(a['current_job_id'],)).fetchone()
return a,j
def upload(raw=None,mime='image/png'):
if raw is None: a,_=c.attachment(alice,chat)
else:a=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=research.png',202,actor=alice,raw=raw,headers={'Content-Type':mime},schema='Attachment')['json']
return a,fetch(a['id'])[1]
def run_once(fault=None):
args=[sys.executable,'/app/src/pipeline.py','work','--once']
if fault:args+=['--fault-point',fault]
return subprocess.run(args,capture_output=True,timeout=30).returncode
def drain():
for _ in range(200):
batch=bus.xreadgroup(GROUP,'research-drain',{STREAM:'>'},count=1)
if not batch:break
for mid,data in batch[0][1]:process(json.loads(data['event']));ack(bus,mid)
def expire(job):
with connect() as conn:
conn.execute("UPDATE attachment_jobs SET lease_until = clock_timestamp() - INTERVAL '1 second' WHERE 1=1 AND id = %s",(job['id'],))
def recover(aid):
until=time.monotonic()+20
while time.monotonic()<until:
dispatch_once(bus);drain()
a,j=fetch(aid)
if a['state']=='ready':return a,j
time.sleep(.1)
raise AssertionError('not recovered')
for mid,data in bus.xautoclaim(STREAM,GROUP,'initial-recovery',min_idle_time=0,start_id='0-0',count=100)[1]:
process(json.loads(data['event']));ack(bus,mid)
# COMMIT -> no publisher yet: one queued row, no Redis message, then automatic outbox pass.
a,j=upload()
assert fetch(a['id'])[0]['state']=='queued'
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',409,actor=bob)
c.message(bob,chat,'queued is linkable',attachments=[a['id']])
dispatch_once(bus);drain();assert fetch(a['id'])[0]['state']=='ready'
report['invariants']['commit_before_publish_recovered']=True
# Broker accepted XADD but publisher died before marking outbox: true exit(77).
a,j=upload()
code=subprocess.run([sys.executable,'/app/src/pipeline.py','dispatch','--once','--fault-point','after_publish'],capture_output=True,timeout=10).returncode
assert code==77
dispatch_once(bus);drain()
assert fetch(a['id'])[0]['state']=='ready'
report['invariants']['publish_before_marker_duplicate_safe']=True
for point in ['before_side_effect','after_original','after_objects','after_commit']:
a,j=upload();dispatch_once(bus)
code=run_once(point);assert code==77,(point,code)
before,job=fetch(a['id'])
if point not in ('after_commit','before_side_effect'):expire(job)
result,job=recover(a['id'])
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',actor=bob)['bytes']==(Path.cwd()/'tests/fixtures/sample.png').read_bytes()
reclaimed=bus.xautoclaim(STREAM,GROUP,'post-crash-redelivery',min_idle_time=0,start_id='0-0',count=100)[1]
for mid,data in reclaimed:
process(json.loads(data['event']));ack(bus,mid)
assert bus.xpending(STREAM,GROUP)['pending']==0
keys=objects.client.list_objects_v2(Bucket=objects.bucket,Prefix='results/'+a['id']+'/v1/').get('Contents',[])
assert len(keys)==4,(point,len(keys))
report['faults'].append({'point':point,'exit_code':code,'state_at_crash':before['state'],'recovered':result['state'],'attempts':job['attempt'],'result_objects':len(keys)})
report['invariants']['crashes_before_after_side_effect_and_commit']=True
bus.xadd(STREAM,{'event':json.dumps({'not':'a job'})})
assert run_once()==0
assert bus.xlen('rejected-jobs')>=1
report['invariants']['invalid_envelope_observable_dlq']=True
# Duplicate/reorder through broker on a completed job: no extra attempt/effect.
a,j=upload();dispatch_once(bus);drain();before,done=fetch(a['id'])
old=event(j)
for attempt in [2,1,3,1,1]:bus.xadd(STREAM,{'event':json.dumps(dict(old,attempt=attempt))})
drain();after,done2=fetch(a['id'])
assert before['variants']==after['variants'] and done2['attempt']==done['attempt']
report['invariants']['duplicate_and_reorder_no_second_effect']=True
# Race two consumers with the SAME logical job, not just one serial duplicate.
a,j=upload();e=event(j)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: results=list(pool.map(lambda _:process(e),range(2)))
assert fetch(a['id'])[0]['state']=='ready' and sorted(results)==['noop','ready']
report['invariants']['concurrent_duplicate_single_claim']=True
# Pause actual old process after all immutable side effects, advance version and finish v2.
a,j=upload();e=event(j)
directory=Path('/tmp')/('fence-'+uuid.uuid4().hex);directory.mkdir();marker=directory/'paused';release=directory/'release'
code="import sys,json,time;from pathlib import Path;sys.path.insert(0,'/app/src');from pipeline import process\ndef hook(point,job):\n if point=='after_objects':\n Path(sys.argv[2]).write_text('paused')\n while not Path(sys.argv[3]).exists():time.sleep(.05)\nprint(process(json.loads(sys.argv[1]),hook))"
child=subprocess.Popen([sys.executable,'-c',code,json.dumps(e),str(marker),str(release)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
try:
deadline=time.monotonic()+20
while not marker.exists():
assert child.poll() is None
assert time.monotonic()<deadline;time.sleep(.05)
new=version(uuid.UUID(a['id']),2);newrow,newjob=fetch(a['id'])
assert process(event(newjob))=='ready'
current,finished=fetch(a['id']);signature=current['variants']
release.write_text('go');stdout,stderr=child.communicate(timeout=10)
assert child.returncode==0 and stdout.strip()=='fenced',(stdout,stderr)
bus.xadd(STREAM,{'event':json.dumps(e)});drain()
final,finished=fetch(a['id'])
assert final['pipeline_version']==2 and final['variants']==signature and final['state']=='ready'
assert all('/v2/' in v['object_key'] for v in final['variants'])
report['invariants']['stale_running_version_fenced']=True
report['invariants']['old_delivery_after_new_ready_no_overwrite']=True
finally:
release.write_text('go')
if child.poll() is None:child.kill();child.wait()
# Transient failures consume a finite budget; failed registry and explicit replay.
a,j=upload()
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
# Exact staging copy saved externally; missing source is permanent and observable.
raw=(Path.cwd()/'tests/fixtures/sample.png').read_bytes();objects.delete(j['source_key'])
process(event(j));failed,fj=fetch(a['id']);assert failed['state']=='failed' and failed['error_code']=='source_missing'
objects.put(j['source_key'],io.BytesIO(raw),len(raw),'image/png',hashlib.sha256(raw).hexdigest())
replay(j['id']);fresh,fj=fetch(a['id']);assert process(event(fj))=='ready'
try:replay(j['id']);raise AssertionError('replayed ready')
except ValueError:pass
report['invariants']['failed_registry_explicit_replay_and_ready_refusal']=True
# Real S3 signature failures are transient, with two attempts and measured backoff.
a,j=upload()
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
wrong=Path('/tmp/wrong-secret');wrong.write_text('synthetic-invalid-key-not-a-real-secret')
env=dict(os.environ,S3_SECRET_ACCESS_KEY_FILE=str(wrong))
transitions=[];started=time.monotonic()
for _ in range(2):
row,j=fetch(a['id'])
delay=max(0,(j['next_attempt_at']-__import__('datetime').datetime.now(__import__('datetime').timezone.utc)).total_seconds())
time.sleep(delay+.01)
code="import sys,json;sys.path.insert(0,'/app/src');from pipeline import process;print(process(json.loads(sys.argv[1])))"
run=subprocess.run([sys.executable,'-c',code,json.dumps(event(j))],env=env,capture_output=True,timeout=10)
assert run.returncode==0
row,j=fetch(a['id']);transitions.append({'state':j['state'],'attempt':j['attempt'],'error_code':j['error_code']})
assert row['state']=='failed' and row['error_code']=='retry_exhausted' and j['attempt']==2
replay(j['id']);row,j=fetch(a['id']);assert process(event(j))=='ready'
report['retry']={'transitions':transitions,'seconds':round(time.monotonic()-started,3),'replayed_attempt':fetch(a['id'])[1]['attempt']}
report['invariants']['transient_backoff_exhaustion_then_replay']=True
# Real corrupted JPEG whose header is valid: heavy decoder fails safely in worker.
jpg=io.BytesIO();Image.new('RGB',(320,200),'blue').save(jpg,format='JPEG');truncated=jpg.getvalue()[:-100]
a,j=upload(truncated,'image/jpeg');process(event(j));bad,_=fetch(a['id'])
assert bad['state']=='failed' and bad['error_code']=='invalid_image'
report['invariants']['invalid_decode_permanent_failed']=True
# EXIF, alpha, small image and all on-disk variants checked by the real decoder.
transforms=[]
for kind in ['alpha','exif','small']:
out=io.BytesIO()
if kind=='alpha':
Image.new('RGBA',(20,10),(255,0,0,0)).save(out,format='PNG');mime='image/png'
elif kind=='exif':
image=Image.new('RGB',(200,320),'green');exif=Image.Exif();exif[274]=6;image.save(out,format='JPEG',exif=exif);mime='image/jpeg'
else:Image.new('RGB',(5,3),'yellow').save(out,format='PNG');mime='image/png'
a,j=upload(out.getvalue(),mime);assert process(event(j))=='ready'
r=c.call('GET','/api/v1/attachments/'+a['id']+'/content?variant=thumbnail',actor=bob)
with Image.open(io.BytesIO(r['bytes'])) as thumb:
expected=(20,10) if kind=='alpha' else (256,160) if kind=='exif' else (5,3)
assert thumb.size==expected
assert not thumb.getexif()
if kind=='alpha':assert min(thumb.getpixel((0,0)))>=250
transforms.append({'kind':kind,'size':thumb.size,'exif_removed':not bool(thumb.getexif())})
report['transforms']=transforms
pending,pending_job=upload()
dry=cleanup(False);fixed=cleanup(True);repeat=cleanup(True)
assert fetch(pending['id'])[0]['state']=='queued' and objects.head(pending_job['source_key']) is not None
report['invariants']['cleanup_preserves_current_and_fresh_failed']=True
assert repeat['counts']['ready_staging']==0
report['invariants']['ready_staging_cleanup_idempotent']=True
report['cleanup']=[dry,fixed,repeat]
print(json.dumps(report,indent=2))
if __name__=='__main__': main()
+28
View File
@@ -0,0 +1,28 @@
"""Figures from real accepted/ready and cgroup samples, no synthetic results."""
import json
from pathlib import Path
import statistics
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
r=Path(__file__).resolve().parents[1]/'evidence'
x=json.loads((r/'resources.json').read_text())['experiments']
fig,axes=plt.subplots(1,2,figsize=(11,4.3),layout='constrained')
labels=['320×200\n1,3 KiB','1800×1400\n7,21 MiB','10000×4000\n0,51 MiB']
a=[max(v['accepted_seconds'] for v in e['replies']) for e in x]
b=[max(v['ready_seconds'] for v in e['replies']) for e in x]
axes[0].bar([i-.18 for i in range(3)],a,.36,label='p95 до 202')
axes[0].bar([i+.18 for i in range(3)],b,.36,label='p95 до ready')
axes[0].set(xticks=range(3),xticklabels=labels,ylabel='Секунды',title='10 одновременных загрузок · worker=1')
axes[0].legend()
peak=[int(e['after']['memory.peak'])/1048576 for e in x]
anon=[max(int(dict(line.split() for line in s['worker']['memory.stat'].splitlines())['anon']) for s in e['samples'])/1048576 for e in x]
axes[1].bar([i-.18 for i in range(3)],peak,.36,label='cgroup memory.peak')
axes[1].bar([i+.18 for i in range(3)],anon,.36,label='Пик resident anon')
axes[1].axhline(768,color='#d62728',linestyle='--',label='Лимит worker')
axes[1].set(xticks=range(3),xticklabels=labels,ylabel='MiB',title='Worker + дочерний декодер')
axes[1].legend(fontsize=8)
for ax in axes:ax.grid(axis='y',alpha=.2);ax.set_axisbelow(True)
fig.suptitle('ЛР 5 · реальные измерения · concurrency=1, prefetch=1')
fig.savefig(r/'pipeline.png',dpi=150)
fig.savefig(r/'pipeline.svg')
+36
View File
@@ -0,0 +1,36 @@
"""Publication plot from measured cost/retention JSON; matplotlib is research-only."""
import json
from pathlib import Path
import statistics
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parents[1]
data=json.loads((ROOT/'evidence/observability-cost.json').read_text())
modes=['off','full','sample10','sample25']
labels=['Off','Full 100%','Sample 10%','Sample 25%']
colors=['#64748b','#2563eb','#0d9488','#d97706']
fig,axs=plt.subplots(2,3,figsize=(16,9),layout='constrained')
def draw(ax,values,title,ylabel):
med=[statistics.median(v) for v in values]
low=[m-min(v) for m,v in zip(med,values)]
high=[max(v)-m for m,v in zip(med,values)]
ax.bar(range(4),med,color=colors,yerr=[low,high],capsize=4,alpha=.85)
for i,v in enumerate(values):ax.scatter([i]*len(v),v,color='#0f172a',s=14,zorder=3)
ax.set_xticks(range(4),labels,rotation=12)
ax.set_title(title,loc='left',fontweight='bold')
ax.set_ylabel(ylabel)
ax.grid(axis='y',alpha=.2)
ax.set_axisbelow(True)
rows=[[r for r in data['runs'] if r['mode']==mode] for mode in modes]
draw(axs[0,0],[[r['p95_seconds']*1000 for r in group] for group in rows],'HTTP p95','milliseconds')
draw(axs[0,1],[[r['resource']['api']['cpu_seconds'] for r in group] for group in rows],'API CPU (both replicas)','CPU seconds / run + drain')
draw(axs[0,2],[[r['collector_ingest']['otelcol_receiver_accepted_spans_total'] for r in group] for group in rows],'Accepted traces','spans / run + drain')
draw(axs[1,0],[[r['resource']['otel-collector']['rx_bytes']/1024 for r in group] for group in rows],'Collector network received','KiB (includes scrape / protocol traffic)')
draw(axs[1,1],[[r['resource']['api']['peak_sampled_anonymous_bytes']/1048576 for r in group] for group in rows],'API anonymous memory','MiB (sum of 1 Hz sampled replica peaks)')
draw(axs[1,2],[[r['resource']['worker']['cpu_seconds'] for r in group] for group in rows],'Worker CPU incl renderer','CPU seconds / run + drain')
fig.suptitle('Lab 6: cost of observability | 600 mixed requests per run (30 uploads) | 30 req/s | 3 repeats',fontsize=15,fontweight='bold')
fig.savefig(ROOT/'evidence/observability-cost.png',dpi=150)
fig.savefig(ROOT/'evidence/observability-cost.svg')
print('Plot written from actual per-run JSON; dots = repeats, bars = median, whiskers = min/max.')
+52
View File
@@ -0,0 +1,52 @@
"""Finite simultaneous jobs including 40 MP; record actual worker cgroup peak/RSS."""
import concurrent.futures
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import threading
import time
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client
from images import png
def docker(*args):return subprocess.check_output(['docker',*args],text=True).strip()
def memory(container):
code="import json;from pathlib import Path;p=Path('/sys/fs/cgroup');print(json.dumps({k:(p/k).read_text().strip() for k in ['memory.current','memory.peak','memory.events','memory.stat','cpu.stat']}))"
return json.loads(docker('exec',container,'python','-c',code))
def main():
c=Client(timeout=30);a,b,e,chat=c.bootstrap()
profiles=[(320,200,False),(1800,1400,True),(10000,4000,False)]
result=[]
for w,h,noise in profiles:
content=png(w,h,noise=noise)
docker('compose','restart','worker');container=docker('compose','ps','-q','worker')
before=memory(container);samples=[];done=threading.Event();start=time.monotonic()
def sample():
while not done.is_set():
samples.append({'seconds':round(time.monotonic()-start,4),'worker':memory(container)})
done.wait(.05)
sampler=threading.Thread(target=sample);sampler.start()
barrier=threading.Barrier(10)
def upload(i):
barrier.wait();t=time.monotonic()
r=Client(timeout=30).call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=load.png',202,actor=a,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
accepted=time.monotonic()-t
ready=Client(timeout=30).wait_ready(b,r['json'])
assert ready['sha256']==hashlib.sha256(content).hexdigest()
return {'index':i,'accepted_seconds':accepted,'ready_seconds':time.monotonic()-t,'status':ready['status']}
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: replies=list(pool.map(upload,range(10)))
finally:done.set();sampler.join()
after=memory(container);assert 'oom_kill 0' in after['memory.events']
result.append({'width':w,'height':h,'bytes':len(content),'clients':10,'before':before,'after':after,'samples':samples,'replies':replies,'seconds':time.monotonic()-start})
print(json.dumps({'method':'10 simultaneous uploads, worker concurrency=1; cgroup v2 samples include child renderer; anon is resident anonymous memory, memory.peak includes tmpfs/kernel/cache','experiments':result},indent=2))
if __name__=='__main__':main()
+38
View File
@@ -0,0 +1,38 @@
"""Separate synchronized rare-error/slow-success retention experiment."""
import json
from pathlib import Path
from observability_cost import set_mode, probes
from observability import save, trace, wait
import urllib.error
def verify_presence(rows):
for row in rows:
if row["trace_sampled"]:
data=wait(lambda:trace(row["trace_id"]),timeout=90)
assert data.get("batches",data.get("resourceSpans"))
row["tempo_trace_found"]=True
else:
try:
trace(row["trace_id"])
except urllib.error.HTTPError as error:
assert error.code==404
row["tempo_trace_found"]=False
else:
raise AssertionError("Unsampled trace unexpectedly stored")
return rows
def main():
result={'method':'Three repeats per full/10%/25% setting; each holds sessions lock until pg_locks confirms it. 3x503 plus one slow200 per repeat. Sampling is ordinary SDK head sampling without forced traceparent.','runs':[]}
try:
for mode,ratio in [('full',1),('sample10',.1),('sample25',.25)]:
c=set_mode(1,ratio)
actor=c.user('retention')
for repeat in range(3):
result['runs'].append({'mode':mode,'repeat':repeat,'probes':verify_presence(probes(c,actor,mode))})
save('sampling-retention.json',result)
print(mode,repeat,'retention recorded',flush=True)
finally:set_mode(1,.25)
print('PASS: synchronized rare 503/slow200 retention study; balanced sampling restored.')
if __name__=='__main__':main()
+29
View File
@@ -0,0 +1,29 @@
"""Private S3 and job envelopes do not expose source bytes or credentials."""
import json
from pathlib import Path
import sys
import urllib.error
import urllib.request
sys.path[:0]=['/app/src',str(Path.cwd()/'tests')]
from client import Client
from pipeline import connect,validate,event
from objects import Objects
from postgres import setting
c=Client();a,b,e,chat=c.bootstrap();att,raw=c.attachment(a,chat);ready=c.wait_ready(b,att)
with connect() as conn:
row=conn.execute('SELECT object_key, current_job_id FROM attachments WHERE 1=1 AND id = %s',(att['id'],)).fetchone()
job=conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s',(row['current_job_id'],)).fetchone()
message=event(job);message['attempt']=max(1,job['attempt'])
assert validate(message)
required={'schema_version','job_id','type','attachment_id','pipeline_version','attempt','created_at'}
assert required <= set(message) <= required | {'traceparent','tracestate'}
assert validate(message)
assert len(json.dumps(message))<1024
for path in ('/'+Objects(setting).bucket+'/'+row['object_key'],'/'+Objects(setting).bucket+'?list-type=2'):
try:urllib.request.urlopen('http://s3:8333'+path,timeout=2);raise AssertionError('anonymous access')
except urllib.error.HTTPError as error:assert error.code==403
for key in ['schema_version','pipeline_version','attempt']:
bad=dict(message);bad[key]=True;assert not validate(bad)
for body in [dict(message,extra='x'),dict(message,created_at='bad'),dict(message,traceparent='bad')]:assert not validate(body)
print(json.dumps({'anonymous_object_and_list_403':True,'job_fields':sorted(message),'job_bytes':len(json.dumps(message)),'no_source_bytes_or_credentials_in_envelope':True,'strict_invalid_envelope_checks':True},indent=2))
+32
View File
@@ -0,0 +1,32 @@
"""A continuously trickling client still reaches the absolute upload deadline."""
import json
from pathlib import Path
import select
import socket
import sys
import time
import uuid
from urllib.parse import urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client
c = Client()
alice, bob, eve, chat = c.bootstrap()
target = urlsplit(c.base)
connection = socket.create_connection((target.hostname, target.port), timeout=3)
header = 'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=slow_' + uuid.uuid4().hex + '.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer ' + alice['token'] + '\r\nContent-Type: image/png\r\nContent-Length: 10485760\r\nConnection: close\r\n\r\n'
started = time.monotonic()
connection.sendall(header.encode())
response = b''
while time.monotonic() - started < 20:
if select.select([connection], [], [], .15)[0]:
response += connection.recv(4096)
if b'\r\n\r\n' in response:
break
connection.sendall(b'x')
connection.close()
elapsed = time.monotonic() - started
assert response.startswith(b'HTTP/1.1 400') or response.startswith(b'HTTP/1.0 400'), response[:100]
assert 14 <= elapsed < 19
assert b'x-instance-id:' in response.lower() and b'x-request-id:' in response.lower()
print(json.dumps({'trickle_seconds': round(elapsed, 3), 'http_status': 400, 'absolute_deadline_enforced': True}))
+177
View File
@@ -0,0 +1,177 @@
"""Extra black-box tests, without changing the course's public tests."""
import concurrent.futures
from pathlib import Path
import sys
import unittest
from urllib.parse import quote
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client as PublicClient, LAB
class Client(PublicClient):
def call(self, method, path, *args, headers=None, **kwargs):
headers = dict(headers or {})
if method == 'POST' and path.endswith('/messages'):
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
return super().call(method, path, *args, headers=headers, **kwargs)
class APIContract(unittest.TestCase):
def setUp(self):
self.client = Client()
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = '/api/v1/chats/' + self.chat['id']
def test_malformed_json_and_extra_fields(self):
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
def test_unicode_limits(self):
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
self.assertEqual(result['text'], '👩' * 4000)
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
def test_unicode_nul_round_trip(self):
import base64
value = 'A\x00B\\u0000👩'
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
self.assertEqual(user['display_name'], value)
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
self.assertEqual(session['user'], user)
actor = {'id': user['id'], 'token': session['token']}
# Exercise the database path and then the Redis profile cache.
for _ in range(2):
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
self.assertEqual(chat['title'], value)
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
for content in contents:
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
self.assertEqual([message['text'] for message in history['items']], contents)
def test_foreign_chat(self):
for suffix in ('', '/messages'):
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
def test_registration_race(self):
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
statuses = list(executor.map(register, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
def test_invalid_chat_creation(self):
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
for member_ids in members:
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
def test_cursor_scope_and_validation(self):
for i in range(3):
self.client.message(self.alice, self.chat, str(i))
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
def test_concurrent_messages_and_pagination(self):
def send(i):
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
sent = list(executor.map(send, range(100)))
found = []
cursor = None
while True:
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
found.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
break
self.assertEqual(len(found), 100)
self.assertEqual(len({v['id'] for v in found}), 100)
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
def test_idempotency_concurrent_replicas(self):
key = uuid.uuid4().hex
def send(_):
return Client().message(self.alice, self.chat, 'Один раз\x00👩', key=key)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
replies = list(executor.map(send, range(32)))
self.assertGreaterEqual(len({v['headers']['X-Instance-Id'] for v in replies}), 2)
self.assertTrue(all(v['json'] == replies[0]['json'] for v in replies))
page = self.client.call('GET', self.path + '/messages', actor=self.bob, schema='MessagePage')['json']
self.assertEqual(page['items'], [replies[0]['json']])
self.client.call('POST', self.path + '/messages', 409, actor=self.alice, body={'text': 'different'}, headers={'Idempotency-Key': key})
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=self.alice)
self.client.call('POST', self.path + '/messages', 401, actor=self.alice, body={'text': 'Один раз\x00👩'}, headers={'Idempotency-Key': key})
def test_protocol_error_headers(self):
self.client.call('TRACE', '/api/v1/users/me', 400, actor=self.alice)
def test_idempotency_scope(self):
key = uuid.uuid4().hex
one = self.client.message(self.alice, self.chat, 'same', key=key)['json']
two = self.client.message(self.bob, self.chat, 'same', key=key)['json']
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'scope', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
three = self.client.message(self.alice, other, 'same', key=key)['json']
self.assertEqual(len({one['id'], two['id'], three['id']}), 3)
def test_idempotency_semantic_body(self):
key = uuid.uuid4().hex
one = self.client.message(self.alice, self.chat, 'semantic', key=key)['json']
two = self.client.call('POST', self.path + '/messages', 201, actor=self.alice, body={'attachment_ids': [], 'text': 'semantic'}, headers={'Idempotency-Key': key}, schema='Message')['json']
self.assertEqual(one, two)
def test_idempotency_invalid_keys(self):
for key in (None, '', 'x' * 129, 'space key', 'bad,key', 'slash/key'):
headers = {} if key is None else {'Idempotency-Key': key}
PublicClient().call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': 'valid'}, headers=headers)
for raw in (b'{"text":true}', b'{"text":"ok","extra":1}', b'{"text":"ok","attachment_ids":false}'):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
def test_idempotency_conflicting_race(self):
key = uuid.uuid4().hex
def send(i):
return Client().call('POST', self.path + '/messages', [201, 409], actor=self.alice, body={'text': str(i % 2)}, headers={'Idempotency-Key': key}, schema=None)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
replies = list(executor.map(send, range(32)))
self.assertEqual(sum(v['status'] == 201 for v in replies), 16)
self.assertEqual(sum(v['status'] == 409 for v in replies), 16)
page = self.client.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
self.assertEqual(len(page['items']), 1)
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
def test_unicode_password_basic_and_logout(self):
import base64
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
self.client.call('POST', '/api/v1/users', 201, body=registration)
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
headers = {'Authorization': 'Basic ' + encoded}
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
actor = {'id': session['user']['id'], 'token': session['token']}
self.client.call('GET', '/api/v1/users/me', actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
if __name__ == '__main__':
unittest.main(verbosity=2)
+52
View File
@@ -0,0 +1,52 @@
"""Independent tests for async image metadata, transformations and access."""
import io
from pathlib import Path
import sys
import unittest
import uuid
from urllib.parse import quote
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'tests')]
from client import Client
from images import bomb
class Images(unittest.TestCase):
def setUp(self):
self.c=Client(); self.alice,self.bob,self.eve,self.chat=self.c.bootstrap()
self.path='/api/v1/chats/'+self.chat['id']
self.raw=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
def test_async_variants_and_replay(self):
queued,_=self.c.attachment(self.alice,self.chat)
self.assertEqual(queued['status'],'queued')
key=uuid.uuid4().hex
one=self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json']
self.assertEqual(self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json'],one)
ready=self.c.wait_ready(self.alice,queued)
self.assertEqual({v['name'] for v in ready['variants']},{'thumbnail','crop','optimized'})
dimensions={v['name']:(v['width'],v['height']) for v in ready['variants']}
self.assertEqual(dimensions,{'thumbnail':(256,160),'crop':(128,128),'optimized':(320,200)})
for v in ready['variants']:
import hashlib
r=self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant='+v['name'],actor=self.bob)
self.assertEqual(hashlib.sha256(r['bytes']).hexdigest(),v['sha256'])
self.assertEqual(len(r['bytes']),v['size_bytes'])
self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant=absent',404,actor=self.bob)
def test_mime_bytes_pixels_and_filename(self):
path=self.path+'/attachments?filename=test.png'
for raw,mime,status in [(b'not image','image/png',415),(self.raw[:20],'image/png',415),(self.raw,'image/jpeg',415),(bomb(),'image/png',413),(b'x'*(10485760+1),'image/png',413)]:
self.c.call('POST',path,status,actor=self.alice,raw=raw,headers={'Content-Type':mime})
for name in ('../x.png','a\\x.png','a\0.png','a\n.png','a'*256,''):
self.c.call('POST',self.path+'/attachments?filename='+quote(name,safe=''),400,actor=self.alice,raw=self.raw,headers={'Content-Type':'image/png'})
def test_private_and_cross_chat(self):
att,_=self.c.attachment(self.alice,self.chat)
for suffix in ('','/content'):
self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=self.eve)
self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,401)
other=self.c.call('POST','/api/v1/chats',201,actor=self.alice,body={'title':'other','member_ids':[self.alice['id']]},schema='Chat')['json']
self.c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=self.alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
if __name__=='__main__': unittest.main(verbosity=2)