Balance stateless replicas with shared idempotency and measured failover scaling

This commit is contained in:
2026-10-16 16:02:33 +03:00
parent 0ab3a341aa
commit 4cb20cc68f
155 changed files with 77900 additions and 38 deletions
+15
View File
@@ -0,0 +1,15 @@
"""Generate local synthetic credentials once. Never prints their values."""
from pathlib import Path
import secrets
root=Path(__file__).resolve().parents[1]
target=root/'.env'
if target.exists():
print('Existing .env preserved')
else:
password=secrets.token_hex(24)
content=f'POSTGRES_PASSWORD={password}\nDATABASE_URL=postgresql://messenger:{password}@db:5432/messenger\nREDIS_URL=redis://cache:6379/0\nCURSOR_SECRET={secrets.token_hex(32)}\nSESSION_TTL_SECONDS=3600\n'
with target.open('x',encoding='utf-8') as f: f.write(content)
try: target.chmod(0o600)
except OSError: pass
print('Created local .env; values not displayed')
+43
View File
@@ -0,0 +1,43 @@
"""Causal DB budget intervention, then alternate limited/restored budget at fixed API resources."""
import json
import argparse
from scaling import OUT, run, setup
from stack import ROOT, docker
results=[]
configs=[]
def database(cpu):
cid=docker('compose','ps','-q','db')
# Change only the CPU quota, not container identity, connections or storage.
# Recreating a throttled DB here adds recovery/startup as an unwanted variable.
docker('update','--cpus',str(cpu),cid)
actual=int(docker('inspect','--format','{{.HostConfig.NanoCpus}}',cid))
assert actual==int(cpu*1e9)
return {'container':cid,'nano_cpus':actual}
def record(label,n,cpu,repeat):
db=database(cpu)
api=setup(n,.5,192,5)
configs.append({'label':label,'repeat':repeat,'db':db,'api':api})
results.append(run(label,24,repeat,12))
(OUT/'db-intervention.json').write_text(json.dumps({'configurations':configs,'results':results},indent=2)+'\n',encoding='utf-8')
parser=argparse.ArgumentParser()
parser.add_argument('--paired-only',action='store_true',help='Keep completed 1/2/4 DB-limited series; repeat only alternating budgets')
args=parser.parse_args()
if args.paired_only:
previous=json.loads((OUT/'db-intervention.json').read_text(encoding='utf-8'))
results=[r for r in previous['results'] if r['label'].startswith('db010-api')]
configs=[r for r in previous['configurations'] if r['label'].startswith('db010-api')]
try:
# With the same deliberately constrained DB, more API resources cannot remove its CPU ceiling.
if not args.paired_only:
for n in (1,2,4):
for repeat in (1,2): record(f'db010-api{n}',n,.1,repeat)
# Alternating budgets controls time/order drift better than a single before/after sample.
for repeat in (1,2,3):
record('paired-db010',2,.1,repeat)
record('paired-db100',2,1,repeat)
finally:
database(1)
docker('compose','up','-d','--no-deps','--wait','--scale','api=2','api')
+48
View File
@@ -0,0 +1,48 @@
from collections import defaultdict
import json
from pathlib import Path
import statistics
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
root=Path(__file__).resolve().parents[1]
folder=root/'evidence/scaling'
data=json.loads((folder/'db-intervention.json').read_text(encoding='utf-8'))
groups=defaultdict(list)
for row in data['results']: groups[row['label']].append(row)
fig,axes=plt.subplots(1,2,figsize=(11,4.5),layout='constrained')
labels=['db010-api1','db010-api2','db010-api4']
values=[[r['successful_rps'] for r in groups[label]] for label in labels]
means=[statistics.median(v) for v in values]
axes[0].bar(['1 API','2 API','4 API'],means,color='#2563eb',width=.55)
axes[0].errorbar(range(3),means,yerr=[[m-min(v) for m,v in zip(means,values)],[max(v)-m for m,v in zip(means,values)]],fmt='none',color='#15233a',capsize=5)
axes[0].set_title('DB limited to 0.1 CPU: more API does not help')
for repeat in (1,2,3):
low=next(r['successful_rps'] for r in groups['paired-db010'] if r['repeat']==repeat)
high=next(r['successful_rps'] for r in groups['paired-db100'] if r['repeat']==repeat)
axes[1].plot([.1,1],[low,high],marker='o',label=f'Pair {repeat}')
axes[1].set_xticks([.1,1],['DB 0.1 CPU','DB 1 CPU'])
axes[1].set_title('Same two API replicas, alternating DB quotas')
axes[1].legend()
for ax in axes:
ax.set_ylim(bottom=0); ax.set_ylabel('Successful HTTP requests / second'); ax.grid(axis='y',alpha=.2)
for suffix in ('png','svg'):
path=root/('evidence/database-intervention.'+suffix)
fig.savefig(path,dpi=160)
if suffix=='svg': path.write_text('\n'.join(line.rstrip() for line in path.read_text(encoding='utf-8').splitlines())+'\n',encoding='utf-8')
summary={}
for label,rows in groups.items():
cpu=defaultdict(list)
for row in rows:
samples=json.loads((folder/f'{label}-c24-r{row["repeat"]}-resources.json').read_text(encoding='utf-8'))
for sample in samples:
for container in sample['containers']:
role=container['Name'].rsplit('-',2)[1]
cpu[role].append(float(container['CPUPerc'].rstrip('%')))
summary[label]={'rps_median':statistics.median(r['successful_rps'] for r in rows),
'p95_ms_median':statistics.median(r['p95_ms'] for r in rows),
'errors':sum(r['errors'] for r in rows),'attempts':sum(r['attempts'] for r in rows),
'cpu_percent_of_one_core':{role:{'median':statistics.median(values),'max':max(values)} for role,values in cpu.items()}}
(folder/'db-summary.json').write_text(json.dumps(summary,indent=2)+'\n',encoding='utf-8')
print(json.dumps(summary,indent=2))
+42
View File
@@ -0,0 +1,42 @@
"""Render measured medians/ranges; never substitute estimates for failed samples."""
from collections import defaultdict
import json
from pathlib import Path
import statistics
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
root=Path(__file__).resolve().parents[1]
rows=json.loads((root/'evidence/scaling/summary.json').read_text(encoding='utf-8'))['results']
groups=defaultdict(list)
for row in rows: groups[(row['label'],row['concurrency'])].append(row)
fig,axes=plt.subplots(2,2,figsize=(12,8),layout='constrained')
colors=['#2563eb','#e87924','#16a085']
for col,mode in enumerate(('fixed','growing')):
for n,color in zip((1,2,4),colors):
med,low,high,lat=[],[],[],[]
for c in (8,24,64):
values=[r['successful_rps'] for r in groups[(f'{mode}-{n}',c)]]
center=statistics.median(values)
med.append(center); low.append(center-min(values)); high.append(max(values)-center)
lat.append(statistics.median(r['p95_ms'] for r in groups[(f'{mode}-{n}',c)]))
axes[0,col].errorbar([8,24,64],med,yerr=[low,high],marker='o',capsize=4,color=color,label=f'{n} replicas')
axes[1,col].plot([8,24,64],lat,marker='o',color=color)
axes[0,col].set_title('Fixed total: 1 CPU / 768 MiB' if mode=='fixed' else 'Growing: 0.5 CPU / 192 MiB each')
for ax in axes[:,col]:
ax.set_xlabel('Concurrent clients'); ax.set_xticks([8,24,64]); ax.grid(alpha=.2)
axes[0,col].set_ylabel('Successful HTTP requests / second'); axes[0,col].legend()
axes[1,col].set_ylabel('p95 of all attempts (ms)')
fig.suptitle('Lab 3: observed scaling; bars show min/max across repeats',fontsize=15)
for suffix in ('png','svg'):
path=root/('evidence/scaling.'+suffix)
fig.savefig(path,dpi=160)
if suffix=='svg': path.write_text('\n'.join(line.rstrip() for line in path.read_text(encoding='utf-8').splitlines())+'\n',encoding='utf-8')
lines=['| Configuration | Clients | RPS median [min, max] | p95 median ms | Errors / attempts |',
'|---|---:|---:|---:|---:|']
for (label,c),items in groups.items():
rps=[i['successful_rps'] for i in items]
lines.append(f'| {label} | {c} | {statistics.median(rps):.2f} [{min(rps):.2f}, {max(rps):.2f}] | {statistics.median(i["p95_ms"] for i in items):.1f} | {sum(i["errors"] for i in items)} / {sum(i["attempts"] for i in items)} |')
(root/'evidence/scaling/table.md').write_text('\n'.join(lines)+'\n',encoding='utf-8')
print('\n'.join(lines))
+13
View File
@@ -0,0 +1,13 @@
"""Restart every running replica and dependency, preserving durable volumes."""
import json
from stack import ROOT, docker, state
before = state()
docker('compose', 'restart', 'api', 'db', 'cache', 'lb')
after = state()
assert set(before) == set(after)
assert all(before[c]['state']['StartedAt'] != after[c]['state']['StartedAt'] for c in before)
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence/restart-processes.json').write_text(
json.dumps({'before': before, 'after': after, 'volumes_removed': False}, indent=2) + '\n',
encoding='utf-8')
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/restart.py
+150
View File
@@ -0,0 +1,150 @@
"""Controlled 1/2/4 replica study, resource samples, raw requests, pool intervention.
Synthetic data only. Same 20% POST / 80% first history page workload in every run.
Short closed-loop runs measure local HTTP confirmations, not a production capacity SLA.
"""
import argparse
import asyncio
from collections import Counter
import csv
import json
import statistics
import threading
import time
import uuid
import httpx
from stack import ROOT, docker, ready, replicas
OUT = ROOT / 'evidence/scaling'
OUT.mkdir(parents=True, exist_ok=True)
def setup(n, cpu, memory, pool):
# Temporary ignored override contains no credentials; base configuration is restored in finally.
override = ROOT / '.env.scaling.json'
override.write_text(json.dumps({'services': {'api': {'cpus': cpu, 'mem_limit': str(memory) + 'm',
'environment': {'DB_POOL_SIZE': str(pool)}}}}), encoding='utf-8')
docker('compose', '-f', 'compose.yaml', '-f', str(override), 'up', '-d', '--no-deps', '--wait', '--scale', f'api={n}', 'api')
with httpx.Client(base_url='http://127.0.0.1:8080', timeout=10) as c:
ready(c)
deadline = time.monotonic() + 25
while time.monotonic() < deadline:
seen = {c.get('/health/ready').headers.get('X-Instance-Id') for _ in range(40)} - {None}
if len(seen) == n:
break
time.sleep(.5)
else:
raise AssertionError(f'LB sees {len(seen)}, expected {n}')
return [{'id': cid, 'limits': json.loads(docker('inspect', '--format',
'{"nano_cpus":{{.HostConfig.NanoCpus}},"memory_bytes":{{.HostConfig.Memory}}}', cid))}
for cid in replicas()]
def sample(stop, samples):
while not stop.is_set():
tick = time.time()
stats = docker('compose', 'ps', '-q', 'api', 'db', 'cache', 'lb').splitlines()
resources = docker('stats', '--no-stream', '--format', '{{json .}}', *stats)
waits = docker('compose', 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc',
"SELECT json_build_object('active',count(*) FILTER (WHERE state='active'),"
"'idle_transaction',count(*) FILTER (WHERE state='idle in transaction'),"
"'lock_wait',count(*) FILTER (WHERE wait_event_type='Lock')) FROM pg_stat_activity WHERE backend_type='client backend'")
samples.append({'unix_time': tick, 'containers': [json.loads(s) for s in resources.splitlines()],
'database': json.loads(waits)})
stop.wait(.5)
async def traffic(path, headers, concurrency, duration, record=True):
rows = []
start = time.perf_counter()
async with httpx.AsyncClient(base_url='http://127.0.0.1:8080', timeout=10,
limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency)) as c:
async def worker(i):
seq = i
while time.perf_counter() - start < duration:
method = 'POST' if seq % 5 == 0 else 'GET'
tick = time.perf_counter()
try:
if method == 'POST':
r = await c.post(path, headers={**headers, 'Idempotency-Key': uuid.uuid4().hex}, json={'text': 'x' * 1000})
else:
r = await c.get(path, headers=headers, params={'limit': 50})
code, serving = r.status_code, r.headers.get('X-Instance-Id', '')
except httpx.HTTPError:
code, serving = 0, ''
if record:
rows.append((round(tick - start, 6), method, code, round((time.perf_counter() - tick) * 1000, 3), serving))
seq += 1
await asyncio.gather(*(worker(i) for i in range(concurrency)))
return rows, time.perf_counter() - start
def run(label, concurrency, repeat, duration):
with httpx.Client(base_url='http://127.0.0.1:8080', timeout=12) as c:
name = 'load_' + uuid.uuid4().hex[:20]
password = 'load-password-only-123'
r = c.post('/api/v1/users', json={'username': name, 'display_name': 'Load', 'password': password})
assert r.status_code == 201, r.text
uid = r.json()['id']
r = c.post('/api/v1/auth/sessions', auth=(name, password))
assert r.status_code == 201
headers = {'Authorization': 'Bearer ' + r.json()['token']}
r = c.post('/api/v1/chats', headers=headers, json={'title': 'Load', 'member_ids': [uid]})
assert r.status_code == 201
path = '/api/v1/chats/' + r.json()['id'] + '/messages'
for _ in range(60):
r = c.post(path, headers={**headers, 'Idempotency-Key': uuid.uuid4().hex}, json={'text': 'x' * 1000})
assert r.status_code == 201
asyncio.run(traffic(path, headers, concurrency, 2, record=False))
samples, stop = [], threading.Event()
thread = threading.Thread(target=sample, args=(stop, samples))
thread.start()
client_cpu_start = time.process_time()
try:
rows, elapsed = asyncio.run(traffic(path, headers, concurrency, duration))
finally:
stop.set()
thread.join()
slug = f'{label}-c{concurrency}-r{repeat}'
with (OUT / (slug + '.csv')).open('w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['start_seconds', 'method', 'status', 'latency_ms', 'instance'])
writer.writerows(rows)
(OUT / (slug + '-resources.json')).write_text(json.dumps(samples, indent=2) + '\n', encoding='utf-8')
latencies = sorted(r[3] for r in rows)
good = [r for r in rows if r[2] in (200, 201)]
result = {'label': label, 'concurrency': concurrency, 'repeat': repeat, 'elapsed': round(elapsed, 3),
'client_cpu_seconds': round(time.process_time() - client_cpu_start, 3),
'attempts': len(rows), 'successful_rps': round(len(good) / elapsed, 3),
'status_counts': dict(Counter(str(r[2]) for r in rows)), 'errors': len(rows) - len(good),
'p50_ms': statistics.median(latencies), 'p95_ms': latencies[int(.95 * (len(latencies) - 1))],
'p99_ms': latencies[int(.99 * (len(latencies) - 1))], 'instances': sorted({r[4] for r in good})}
print(json.dumps(result), flush=True)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--duration', type=int, default=10)
parser.add_argument('--repeats', type=int, default=2)
args = parser.parse_args()
results, configurations = [], []
cases = [(f'fixed-{n}', n, 1 / n, 768 // n, 5) for n in (1, 2, 4)]
cases += [(f'growing-{n}', n, .5, 192, 5) for n in (1, 2, 4)]
cases += [('pool1-2', 2, .5, 192, 1)]
try:
for label, n, cpu, memory, pool in cases:
actual = setup(n, cpu, memory, pool)
configurations.append({'label': label, 'replicas': n, 'cpu_each': cpu, 'memory_mib_each': memory,
'pool_each': pool, 'actual_containers': actual})
for concurrency in (8, 24, 64):
for repeat in range(1, args.repeats + 1):
results.append(run(label, concurrency, repeat, args.duration))
(OUT / 'summary.json').write_text(json.dumps({'configurations': configurations, 'results': results}, indent=2) + '\n', encoding='utf-8')
finally:
docker('compose', 'up', '-d', '--no-deps', '--wait', '--scale', 'api=2', 'api')
if __name__ == '__main__':
main()
+25
View File
@@ -0,0 +1,25 @@
"""Shared bounded Docker helpers for reproducible, scoped failure experiments."""
import json
from pathlib import Path
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
def docker(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
def replicas(): return docker('compose','ps','-q','api').splitlines()
def instance(cid):
return docker('exec',cid,'python','-c',"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live',timeout=2).headers['X-Instance-Id'])")
def state():
result={}
for service in ('api','db','cache','lb'):
for cid in docker('compose','ps','-q',service).splitlines():
result[cid]={'service':service,'state':json.loads(docker('inspect','--format','{{json .State}}',cid))}
return result
def ready(client,timeout=60):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
try:
if client.get('/health/ready').status_code==200: return
except Exception: pass
time.sleep(.2)
raise AssertionError('Readiness timeout')
+12
View File
@@ -0,0 +1,12 @@
"""Stop the real process selected by X-Instance-Id; do not stop any dependency."""
import json
import os
from stack import ROOT, docker, instance, replicas
target=os.environ['TARGET_INSTANCE_ID']
matches=[cid for cid in replicas() if instance(cid)==target]
assert len(matches)==1,'Target does not uniquely identify a running API'
before=replicas()
docker('stop','--time','5',matches[0])
assert docker('inspect','--format','{{.State.Running}}',matches[0])=='false'
(ROOT/'evidence').mkdir(exist_ok=True)
(ROOT/'evidence/stop-one.json').write_text(json.dumps({'target_instance':target,'stopped_container':matches[0],'before_containers':before,'after_running_containers':replicas()},indent=2)+'\n',encoding='utf-8')
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/stop-one.py
+52
View File
@@ -0,0 +1,52 @@
"""Real DB fault and synthetic 24h expiry boundary; no production clock manipulation."""
import json
import time
import uuid
import httpx
from stack import ROOT,docker,ready
def sql(q):
return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',q)
result={}
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=12) as c:
ready(c)
name='expiry_'+uuid.uuid4().hex[:20]
password='expiry-password-123'
r=c.post('/api/v1/users',json={'username':name,'display_name':'Lifecycle','password':password})
assert r.status_code==201
uid=r.json()['id']
r=c.post('/api/v1/auth/sessions',auth=(name,password)); assert r.status_code==201
h={'Authorization':'Bearer '+r.json()['token']}
r=c.post('/api/v1/chats',headers=h,json={'title':'Lifecycle','member_ids':[uid]}); assert r.status_code==201
path='/api/v1/chats/'+r.json()['id']+'/messages'
key=uuid.uuid4().hex
headers={**h,'Idempotency-Key':key}
first=c.post(path,headers=headers,json={'text':'Original'}); assert first.status_code==201
seconds=float(sql("SELECT extract(epoch from expires_at-clock_timestamp()) FROM idempotency WHERE key='"+key+"'"))
assert 86390<seconds<=86400
# Isolated synthetic key only: fast-forward its DB expiry, never wall clock or other data.
sql("UPDATE idempotency SET expires_at=clock_timestamp()-interval '1 second' WHERE key='"+key+"'")
second=c.post(path,headers=headers,json={'text':'After expiry'})
assert second.status_code==201 and first.json()['id']!=second.json()['id']
result['ttl']={'observed_seconds_after_create':seconds,'expired_key_reusable':True}
newkey=uuid.uuid4().hex
docker('compose','stop','db')
try:
r=c.post(path,headers={**h,'Idempotency-Key':newkey},json={'text':'After transient failure'})
assert r.status_code==503
result['database_down_status']=r.status_code
finally: docker('compose','start','db')
ready(c)
assert sql("SELECT count(*) FROM idempotency WHERE key='"+newkey+"'")=='0'
# LB may still be waiting for its next readiness healthcheck.
deadline=time.monotonic()+10
while True:
r=c.post(path,headers={**h,'Idempotency-Key':newkey},json={'text':'After transient failure'})
if r.status_code==201: break
assert r.status_code==503 and time.monotonic()<deadline
time.sleep(.2)
result['transient_failure_not_recorded']=True
result['passed']=True
(ROOT/'evidence/key-lifecycle.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,indent=2))
+205
View File
@@ -0,0 +1,205 @@
"""Real LB/replica integration, fault injection and rolling replacement evidence."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import httpx
from stack import ROOT, docker, instance, ready, replicas, state
OUT = ROOT / 'evidence'
OUT.mkdir(exist_ok=True)
evidence = {}
def user(c):
name = 'v_' + uuid.uuid4().hex[:20]
password = 'test-password-only-123'
r = c.post('/api/v1/users', json={'username': name, 'display_name': 'Проверка', 'password': password})
assert r.status_code == 201, r.text
uid = r.json()['id']
r = c.post('/api/v1/auth/sessions', auth=(name, password))
assert r.status_code == 201, r.text
return uid, {'Authorization': 'Bearer ' + r.json()['token']}
def chat(c, headers, members):
r = c.post('/api/v1/chats', headers=headers, json={'title': 'Verify', 'member_ids': members})
assert r.status_code == 201, r.text
return '/api/v1/chats/' + r.json()['id'] + '/messages'
def history(c, headers, path):
rows, cursor = [], None
for _ in range(1000):
r = c.get(path, headers=headers, params={'limit': 100, **({'cursor': cursor} if cursor else {})})
assert r.status_code == 200, r.text
page = r.json()
rows.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
return rows
raise AssertionError('Pagination exceeded bound')
def restore(c):
docker('compose', 'up', '-d', '--no-deps', '--wait', '--scale', 'api=2', 'api')
ready(c)
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
ids = {c.get('/health/ready').headers.get('X-Instance-Id') for _ in range(12)} - {None}
if len(ids) == 2:
return
time.sleep(.2)
raise AssertionError('LB did not observe both actual replicas')
def public(mode):
script = 'restart' if mode == 'persistence' else 'stop-one'
with tempfile.TemporaryDirectory(prefix='lab3-hook-') as temp:
if os.name == 'nt':
hook = Path(temp) / (script + '.cmd')
hook.write_text('@echo off\n"' + sys.executable + '" "' + str(ROOT / ('scripts/' + script + '.py')) + '"\n', encoding='utf-8')
else:
hook = ROOT / ('scripts/' + script + '.sh')
return subprocess.check_output([sys.executable, '-X', 'utf8', 'tests/resilience.py', '--mode', mode,
'--action-script', str(hook)], cwd=ROOT, text=True, encoding='utf-8').strip()
def fault_scenario(c, uid, headers, target, rolling=False):
path = chat(c, headers, [uid])
before = state()
alias = instance(target)
rows, confirmed = [], {}
stop = threading.Event()
start = time.monotonic()
def traffic(worker):
with httpx.Client(base_url='http://127.0.0.1:8080', timeout=3) as client:
key = uuid.uuid4().hex
while not stop.is_set():
tick = time.monotonic()
body = {'text': key}
try:
r = client.post(path, headers={**headers, 'Idempotency-Key': key}, json=body)
status, serving = r.status_code, r.headers.get('X-Instance-Id')
if status == 201:
msg = r.json()
assert key not in confirmed or confirmed[key] == msg
confirmed[key] = msg
key = uuid.uuid4().hex
except httpx.HTTPError:
status, serving = 0, None
rows.append({'t': round(tick - start, 6), 'method': 'POST', 'status': status,
'instance': serving, 'ms': round((time.monotonic() - tick) * 1000, 3)})
tick = time.monotonic()
try:
r = client.get(path, headers=headers, params={'limit': 10})
status, serving = r.status_code, r.headers.get('X-Instance-Id')
except httpx.HTTPError:
status, serving = 0, None
rows.append({'t': round(tick - start, 6), 'method': 'GET', 'status': status,
'instance': serving, 'ms': round((time.monotonic() - tick) * 1000, 3)})
time.sleep(.03)
events = []
with ThreadPoolExecutor(max_workers=3) as pool:
futures = [pool.submit(traffic, w) for w in range(3)]
try:
time.sleep(2)
targets = replicas() if rolling else [target]
for cid in targets:
event = {'container': cid, 'alias': instance(cid), 'signal_at': time.monotonic() - start}
docker('stop', '-t', '5', cid)
event['stopped_at'] = time.monotonic() - start
assert json.loads(docker('inspect', '--format', '{{json .State.Running}}', cid)) is False
if rolling:
docker('rm', cid)
docker('compose', 'up', '-d', '--no-deps', '--no-recreate', '--wait', '--scale', 'api=2', 'api')
ready(c)
event['replacement_ready_at'] = time.monotonic() - start
events.append(event)
time.sleep(3)
time.sleep(3)
finally:
stop.set()
for future in futures:
future.result()
elapsed = time.monotonic() - start
actual = history(c, headers, path)
assert len({m['text'] for m in actual}) == len(actual), 'Duplicate retry side effect'
by_id = {m['id']: m for m in actual}
assert all(by_id.get(m['id']) == m for m in confirmed.values()), 'Lost confirmation'
for event in events:
for method, good in [('GET', 200), ('POST', 201)]:
successful = [r for r in rows if r['method'] == method and r['status'] == good and r['t'] >= event['stopped_at']]
assert successful, 'No successful operation after stop'
event[method + '_recovery_seconds'] = round(successful[0]['t'] - event['signal_at'], 3)
assert event[method + '_recovery_seconds'] <= 10
assert all(r['instance'] != event['alias'] for r in successful)
errors = [r for r in rows if r['status'] not in (200, 201)]
result = {'events': events, 'duration_seconds': round(elapsed, 3), 'attempts': len(rows),
'successful_rps': round((len(rows) - len(errors)) / elapsed, 3), 'errors': len(errors),
'confirmed_messages': len(confirmed), 'stored_messages': len(actual), 'all_confirmed_retained': True,
'before': before, 'after': state(), 'requests': sorted(rows, key=lambda r: r['t'])}
name = 'rolling' if rolling else 'stop-' + alias
(OUT / (name + '.json')).write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
return {k: v for k, v in result.items() if k not in ('requests', 'before', 'after')}
with httpx.Client(base_url='http://127.0.0.1:8080', timeout=12) as c:
restore(c)
evidence['public_smoke'] = subprocess.check_output([sys.executable, '-X', 'utf8', 'tests/smoke.py'], cwd=ROOT, text=True).strip()
uid, headers = user(c)
uid2, headers2 = user(c)
path = chat(c, headers, [uid, uid2])
key = uuid.uuid4().hex
same_headers = {**headers, 'Idempotency-Key': key}
with ThreadPoolExecutor(max_workers=16) as pool:
replies = list(pool.map(lambda _: c.post(path, headers=same_headers, json={'text': 'Один результат'}), range(32)))
assert all(r.status_code == 201 for r in replies), [r.status_code for r in replies]
assert len({r.headers['X-Instance-Id'] for r in replies}) == 2
original = replies[0].json()
assert all(r.json() == original for r in replies)
assert len(history(c, headers, path)) == 1
evidence['parallel_idempotency'] = {'attempts': 32, 'replicas': 2, 'messages': 1}
assert c.post(path, headers=same_headers, json={'text': 'Другой результат'}).status_code == 409
r = c.post(path, headers={**headers2, 'Idempotency-Key': key}, json={'text': 'Другой пользователь'})
assert r.status_code == 201 and r.json()['id'] != original['id']
path2 = chat(c, headers, [uid])
assert c.post(path2, headers=same_headers, json={'text': 'Другой чат'}).status_code == 201
assert c.post(path, headers=headers, json={'text': 'Без ключа'}).status_code == 400
assert c.post(path, headers={**headers, 'Idempotency-Key': 'bad key'}, json={'text': 'Ключ'}).status_code == 400
# Invalid request must not reserve a key.
fresh = {**headers, 'Idempotency-Key': uuid.uuid4().hex}
assert c.post(path, headers=fresh, json={'text': ''}).status_code == 400
assert c.post(path, headers=fresh, json={'text': 'После 400'}).status_code == 201
evidence['key_scopes_validation'] = '409 mismatch; independent users/chats; missing/invalid key 400; 400 does not reserve key'
evidence['public_persistence'] = public('persistence')
ready(c)
assert c.post(path, headers=same_headers, json={'text': 'Один результат'}).json() == original
assert c.delete('/api/v1/auth/sessions/current', headers=headers2).status_code == 204
assert c.post(path, headers={**headers2, 'Idempotency-Key': key}, json={'text': 'Другой пользователь'}).status_code == 401
evidence['replay_after_restart_logout'] = 'same response after all-service restart; revoked session cannot replay'
restore(c)
evidence['public_failover'] = public('failover')
restore(c)
targets = replicas()
evidence['each_replica_failure'] = []
for target in targets:
try:
evidence['each_replica_failure'].append(fault_scenario(c, uid, headers, target))
finally:
restore(c)
evidence['rolling'] = fault_scenario(c, uid, headers, replicas()[0], rolling=True)
restore(c)
evidence['migration_repeat'] = docker('compose', 'run', '--rm', '--no-deps', 'migrate')
evidence['passed'] = True
(OUT / 'integration.json').write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps(evidence, ensure_ascii=False, indent=2))