Проверить сквозной контекст, отказы, SLO и требования уровня 4

This commit is contained in:
2026-11-27 16:57:58 +03:00
parent 71254d3389
commit 0355ba13d2
23 changed files with 9136 additions and 16812 deletions
+22 -1
View File
@@ -10,13 +10,17 @@ import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, check
from client import Client, check, shape
BASE = os.getenv('BASE_URL','http://127.0.0.1:8086')
GRAFANA = os.getenv('GRAFANA_URL','http://127.0.0.1:3006')
PROJECT = os.getenv('COMPOSE_PROJECT_NAME','lyakhonov-lab6')
def dc(*args):
if args and args[0]=='start':
# Compose v2.40 also starts dependencies, which would undo an injected S3 outage.
ids=subprocess.check_output(['docker','compose','-p',PROJECT,'ps','-aq',*args[1:]],cwd=ROOT,text=True).split()
return subprocess.check_output(['docker','start',*ids],text=True)
return subprocess.check_output(['docker','compose','-p',PROJECT,*args],cwd=ROOT,text=True,stderr=subprocess.STDOUT)
@@ -32,12 +36,29 @@ def prom(expr):
return query('prometheus','/api/v1/query',query=expr)['data']['result']
class DBLock:
"""Bounded SQL lock in this project's DB; health reads remain usable."""
def start(self):
self.process=subprocess.Popen(['docker','compose','-p',PROJECT,'exec','-T','db',
'env','PGAPPNAME=lab6-fault-lock','psql','-U','messenger','-d','messenger','-c',
'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(180); COMMIT;'],
cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
time.sleep(.5)
check(self.process.poll() is None,'SQL fault process failed')
def stop(self):
dc('exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='lab6-fault-lock' AND pid<>pg_backend_pid()")
self.process.wait(timeout=10)
def snapshot():
ids=dc('ps','-aq').split()
result=[]
for row in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
result.append({'id':row['Id'],'service':row['Config']['Labels']['com.docker.compose.service'],
'started_at':row['State']['StartedAt'],'status':row['State']['Status'],
'oom_killed':row['State']['OOMKilled'],
'memory_limit':row['HostConfig']['Memory'],'nano_cpus':row['HostConfig']['NanoCpus']})
return result
+126
View File
@@ -0,0 +1,126 @@
"""Bounded grade-4 failures, recovery and stored telemetry observations."""
from concurrent.futures import ThreadPoolExecutor
import time
from common import *
def alerts():
return query('prometheus','/api/v1/alerts')['data']['alerts']
def main():
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
result={'before':snapshot(),'incidents':[]}
def wait_result(att):
transitional=[]
deadline=time.monotonic()+90
while time.monotonic()<deadline:
request=urllib.request.Request(BASE+'/api/v1/attachments/'+att['id'],headers={'Authorization':'Bearer '+alice['token']})
try:response=urllib.request.urlopen(request,timeout=10)
except urllib.error.HTTPError as error:response=error
with response:
status=response.code
payload=response.read()
source='API' if response.headers.get('X-Instance-Id') else 'LB'
check(status in (200,503),'unexpected attachment response')
if status==503:
transitional.append({'time':time.time(),'status':503,'source':source})
time.sleep(.5)
continue
metadata=shape(json.loads(payload),'Attachment')
if metadata['status']=='ready':
result.setdefault('transition_errors',[]).extend(transitional)
return metadata
elif metadata['status']=='failed':
raise AssertionError('accepted attachment failed')
time.sleep(.5)
raise AssertionError('accepted attachment did not reach ready')
dc('stop','-t','2','worker')
try:
att,_=c.attachment(alice,chat)
observations=[]
for _ in range(8):
observations.append({'time':time.time(),'depth':prom('messenger_queue_depth'),
'age':prom('messenger_queue_oldest_seconds'),'alerts':alerts()})
time.sleep(5)
check(any(a['labels']['alertname']=='QueueLag' and a['state']=='firing'
for row in observations for a in row['alerts']),'queue alert did not fire')
finally:dc('start','worker')
wait_result(att)
result['incidents'].append({'name':'worker stopped','observations':observations,'ready':True})
save('incidents.json',result)
# Force at least one managed retry, keeping the original HTTP trace context.
dc('stop','-t','2','worker')
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=retry.png',202,
actor=alice,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'},schema='Attachment')
tid=response['headers']['X-Trace-Id']
dc('stop','-t','2','s3')
dc('start','worker')
try:
deadline=time.monotonic()+35
retried=False
while time.monotonic()<deadline:
records=query('loki','/loki/api/v1/query_range',query='{service_name="messenger-worker"} |= "'+tid+'" |= "retry"',limit=10)
if records['data']['result']:
retried=True
break
time.sleep(1)
check(retried,'no managed retry observed while S3 stopped')
finally:dc('start','s3')
wait_result(response['json'])
time.sleep(4)
doc,spans=trace_wait(tid)
check(sum(s['kind']=='SPAN_KIND_CONSUMER' for s in spans)>=2,'retry trace missing')
result['retry']={'trace_id':tid,'spans':spans,'ready':True}
save('incidents.json',result)
# DB unavailable to active business traffic, not just /health.
fault=DBLock();fault.start()
observations=[];responses=[]
try:
with ThreadPoolExecutor(max_workers=6) as pool:
deadline=time.monotonic()+45
while time.monotonic()<deadline:
futures=[pool.submit(c.call,'POST','/api/v1/chats/'+chat['id']+'/messages',[201,503],actor=alice,
body={'text':'DB lock experiment'},headers={'Idempotency-Key':str(time.time_ns())+str(i)},schema='Message') for i in range(6)]
for future in futures:
response=future.result()
responses.append({'status':response['status'],'elapsed':response['elapsed'],
'trace_id':response['headers']['X-Trace-Id']})
observations.append({'time':time.time(),'alerts':alerts(),'pool':prom('messenger_db_pool_waiting')})
check(any(a['labels']['alertname']=='HighAPIErrorRate' and a['state']=='firing' for row in observations for a in row['alerts']), 'API error alert did not fire')
finally:fault.stop()
subprocess.check_call([sys.executable,'scripts/wait_ready.py','--project',PROJECT,'--base-url',BASE],cwd=ROOT)
c.message(alice,chat,'after DB recovery')
_,dbspans=trace_wait(next(x['trace_id'] for x in responses if x['status']==503),services=('messenger-api',))
result['incidents'].append({'name':'DB messages table locked','responses':responses,'observations':observations,'trace_spans':dbspans,'recovered':True})
save('incidents.json',result)
# Backend outage: drive signals until Collector retry expires, then prove business durability.
before=prom('otelcol_exporter_send_failed_spans_total')
dc('stop','-t','2','tempo')
snapshots=[]
try:
for i in range(10):
c.message(alice,chat,'telemetry outage '+str(i))
att,_=c.attachment(alice,chat);c.wait_ready(alice,att)
snapshots.append({'time':time.time(),'stats':dc('stats','--no-stream','--format','json'),
'queue':prom('otelcol_exporter_queue_size'),'failed':prom('otelcol_exporter_send_failed_spans_total')})
time.sleep(2)
finally:dc('start','tempo')
result['backend_outage']={'before_failed':before,'samples':snapshots,'business_messages':10,'completed_uploads':10,'after':snapshot()}
save('incidents.json',result)
check(any(float(r['value'][1])>0 for sample in snapshots for r in sample['failed']), 'export failure counter did not increase')
check(all(float(r['value'][1])<=128 for sample in snapshots for r in sample['queue']), 'Collector queue exceeded configured bound')
# Observe recovery, allowing the independent error-rate lookback to age out.
deadline=time.monotonic()+160
while time.monotonic()<deadline:
c.message(alice,chat,'recovery control')
active=alerts()
if not any(a['labels']['alertname'] in ('HighAPIErrorRate','QueueLag') for a in active):break
time.sleep(5)
result['resolved_alerts']=active
save('incidents.json',result)
check(not any(a['labels']['alertname'] in ('HighAPIErrorRate','QueueLag') for a in active),'base alerts not resolved')
print('PASS: worker lag, S3 retry context, DB outage, telemetry backend outage and recovery')
if __name__=='__main__':main()
+38
View File
@@ -0,0 +1,38 @@
"""Public persistence and separately stop each real API replica; preserve volumes."""
import os
import subprocess
import time
from common import *
def main():
result={'before':snapshot()}
env=dict(os.environ,PYTHONUTF8='1')
for mode in ['persistence','failover','failover']:
script=ROOT/'scripts'/('restart.cmd' if mode=='persistence' else 'stop-one.cmd')
before=snapshot()
run=subprocess.run([sys.executable,'-X','utf8','tests/resilience.py','--base-url',BASE,
'--mode',mode,'--action-script',str(script)],cwd=ROOT,env=env,capture_output=True,text=True)
after=snapshot()
result.setdefault('runs',[]).append({'mode':mode,'before':before,'after':after,
'exit_code':run.returncode,'output':run.stdout+run.stderr})
# Bring back only our replicas after the public hook; next run targets the other alias below.
dc('start','api')
subprocess.check_call([sys.executable,'scripts/wait_ready.py','--project',PROJECT,'--base-url',BASE],cwd=ROOT)
save('resilience.json',result)
check(run.returncode==0,'public '+mode+' failed')
# Deterministic separate stops, independent of LB choice in the public hook.
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
for container in dc('ps','-q','api').split():
before=snapshot()
subprocess.check_call(['docker','stop','-t','2',container],stdout=subprocess.DEVNULL)
try:
for i in range(20):c.message(alice,chat,'targeted '+str(i))
finally:subprocess.check_call(['docker','start',container],stdout=subprocess.DEVNULL)
result.setdefault('each_api',[]).append({'stopped_id':container,'before':before,'after':snapshot(),'confirmed':20})
time.sleep(5)
save('resilience.json',result)
print('PASS: persistence, public failover twice, each API stopped separately')
if __name__=='__main__':main()
+2 -1
View File
@@ -46,7 +46,8 @@ def main():
telemetry=json.dumps([doc,logs,signals])
for secret in [alice['token'],bob['token'],alice['registration']['password'],'synthetic concurrent']:
check(secret not in telemetry,'sensitive data in telemetry')
save('signals.json',{'trace_id':tid,'spans':spans,'logs':logs,'metrics':signals,
compact={name:{'series_count':len(rows),'label_names':sorted(set().union(*(set(row['metric']) for row in rows))),'sample':rows[:2]} for name,rows in signals.items()}
save('signals.json',{'trace_id':tid,'spans':spans,'logs':logs,'metrics':compact,
'concurrent_requests':24,'unique_messages':1,'checks':'PASS'})
print('PASS: real OTLP signals, connected producer/consumer/S3/DB graph, logs, metric labels, 24 concurrent replays and negative checks')
+53
View File
@@ -0,0 +1,53 @@
import hashlib
import tempfile
import unittest
from pathlib import Path
from PIL import Image
from src.image_pipeline import render
ROOT = Path(__file__).resolve().parents[1]
class Images(unittest.TestCase):
def test_public_fixture_and_repeat(self):
fixture = ROOT / 'tests' / 'fixtures' / 'sample.png'
original = hashlib.sha256(fixture.read_bytes()).hexdigest()
with tempfile.TemporaryDirectory() as directory:
target = Path(directory)
expected = {
'thumbnail': ('JPEG', (256, 160)),
'crop': ('JPEG', (128, 128)),
'optimized': ('WEBP', (320, 200)),
}
first = render(fixture, target)
self.assertEqual(len(first), len(expected))
digests = {name: hashlib.sha256((target / name).read_bytes()).hexdigest() for name in expected}
self.assertEqual(first, render(fixture, target))
for name, properties in expected.items():
with Image.open(target / name) as image:
self.assertEqual((image.format, image.size), properties)
self.assertEqual(hashlib.sha256((target / name).read_bytes()).hexdigest(), digests[name])
self.assertEqual(hashlib.sha256(fixture.read_bytes()).hexdigest(), original)
def test_orientation_alpha_and_small_image(self):
with tempfile.TemporaryDirectory() as directory:
target = Path(directory)
source = target / 'source.png'
image = Image.new('RGBA', (35, 15), (255, 0, 0, 0))
image.save(source, exif=self.orientation())
render(source, target)
with Image.open(target / 'thumbnail') as thumbnail:
self.assertEqual(thumbnail.size, (15, 35))
self.assertEqual(thumbnail.getpixel((4, 4)), (255, 255, 255))
self.assertFalse(thumbnail.getexif())
with Image.open(target / 'optimized') as optimized:
self.assertEqual(optimized.size, (15, 35))
self.assertFalse(optimized.getexif())
@staticmethod
def orientation():
exif = Image.Exif()
exif[274] = 6
return exif