Persist messenger in PostgreSQL with sessions, cache and recovery evidence

This commit is contained in:
2026-10-16 15:16:17 +03:00
parent 65003b6119
commit be6f10f195
34 changed files with 8920 additions and 55 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')
+109
View File
@@ -0,0 +1,109 @@
"""120k skewed messages: query plans/write cost + real fresh-volume restore.
Host orchestrates Docker; --inside runs synthetic SQL in an isolated database.
No production table is changed and no credentials are printed.
"""
import hashlib
from datetime import datetime
import json
import os
from pathlib import Path
import statistics
import subprocess
import sys
import time
import uuid
def inside(dbname):
import psycopg
with psycopg.connect(os.environ['DATABASE_URL'],autocommit=True) as admin:
admin.execute(psycopg.sql.SQL('CREATE DATABASE {}').format(psycopg.sql.Identifier(dbname)))
with psycopg.connect(os.environ['DATABASE_URL'],dbname=dbname,autocommit=True) as c:
c.execute(Path('/app/migrations/001_initial.sql').read_text())
c.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES ('00000000-0000-0000-0000-000000000001','benchmark','Synthetic','not-a-login-hash')")
c.execute("INSERT INTO chats(id,title) SELECT md5('chat'||n)::uuid,'chat'||n FROM generate_series(1,3) n")
c.execute("INSERT INTO members SELECT id,'00000000-0000-0000-0000-000000000001'::uuid FROM chats")
c.execute("INSERT INTO messages SELECT md5('message'||n)::uuid,md5('chat'||CASE WHEN n<=100000 THEN 1 WHEN n<=115000 THEN 2 ELSE 3 END)::uuid,'00000000-0000-0000-0000-000000000001'::uuid,repeat('payload-',20)||n,'2026-01-01'::timestamptz+n*interval '1 millisecond' FROM generate_series(1,120000) n")
c.execute('DROP INDEX messages_history')
c.execute('VACUUM ANALYZE messages')
cursor=c.execute("SELECT created_at,id FROM messages WHERE chat_id=md5('chat1')::uuid ORDER BY created_at,id OFFSET 69999 LIMIT 1").fetchone()
keyset="SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=md5('chat1')::uuid AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 50"
offset="SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=md5('chat1')::uuid ORDER BY created_at,id OFFSET 70000 LIMIT 50"
result={'version':c.execute('SELECT version()').fetchone()[0],'rows':120000,'chat_sizes':[100000,15000,5000],'repeats':5,'plans':[],'writes':[]}
for variant,ddl in [('primary_only',None),('chat_index','CREATE INDEX experiment_idx ON messages(chat_id)'),('compound','CREATE INDEX experiment_idx ON messages(chat_id,created_at,id)')]:
if ddl: c.execute(ddl)
c.execute('ANALYZE messages')
for query_name,query,args in [('keyset',keyset,cursor),('offset',offset,())]:
for _ in range(2): c.execute(query,args).fetchall()
plans=[c.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '+query,args).fetchone()[0][0] for _ in range(5)]
result['plans'].append({'index':variant,'query':query_name,'execution_ms':[p['Execution Time'] for p in plans],'median_ms':statistics.median(p['Execution Time'] for p in plans),'plans':plans})
# Five real committed batches, then remove only those synthetic rows.
measurements=[]
for rep in range(5):
start=time.perf_counter()
c.execute("INSERT INTO messages SELECT md5('write'||n)::uuid,md5('chat1')::uuid,'00000000-0000-0000-0000-000000000001'::uuid,repeat('payload-',20)||n,'2027-01-01'::timestamptz+n*interval '1 millisecond' FROM generate_series(1,5000) n")
measurements.append(round((time.perf_counter()-start)*1000,3))
c.execute("DELETE FROM messages WHERE created_at>='2027-01-01'")
c.execute('VACUUM ANALYZE messages')
result['writes'].append({'index':variant,'batch_rows':5000,'committed_ms':measurements,'median_ms':statistics.median(measurements)})
if ddl: c.execute('DROP INDEX experiment_idx')
c.execute('CREATE INDEX messages_history ON messages(chat_id,created_at,id)')
result['snapshot']=snapshot(c)
print(json.dumps(result,default=str))
def snapshot(c):
counts={table:c.execute('SELECT count(*) FROM '+table).fetchone()[0] for table in ('users','chats','members','messages','sessions')}
selected=c.execute('SELECT id,chat_id,sender_id,text,created_at FROM messages ORDER BY id LIMIT 20').fetchall()
digest=c.execute("SELECT md5(string_agg(id::text||chat_id::text||sender_id::text||text||created_at::text,'' ORDER BY id)) FROM messages").fetchone()[0]
return {'counts':counts,'selected':[[str(v) for v in row] for row in selected],'all_messages_digest':digest}
def host():
root=Path(__file__).resolve().parents[1]
def run(*args,input=None):
return subprocess.run(['docker',*args],cwd=root,input=input,stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True).stdout
unique=uuid.uuid4().hex[:10]; dbname='experiment_'+unique
cid=run('compose','ps','-q','db').decode().strip()
source=Path(__file__).read_bytes()
result=json.loads(run('compose','exec','-T','api','python','-','--inside',dbname,input=source))
start=time.perf_counter()
dump=run('exec',cid,'pg_dump','-U','messenger','-Fc',dbname)
result['backup']={'seconds':round(time.perf_counter()-start,3),'bytes':len(dump),'sha256':hashlib.sha256(dump).hexdigest()}
backup=root/'backups'/f'{dbname}.dump'; backup.parent.mkdir(exist_ok=True); backup.write_bytes(dump)
# Distinct container and brand-new named volume: no restore onto source storage.
image=run('inspect','--format','{{.Config.Image}}',cid).decode().strip()
volume='lab2-restore-'+unique; target='lab2-restore-'+unique
run('volume','create',volume)
try:
run('run','-d','--name',target,'--cpus','1','--memory','256m','-e','POSTGRES_USER=messenger','-e','POSTGRES_DB=messenger','-e','POSTGRES_HOST_AUTH_METHOD=trust','-v',volume+':/var/lib/postgresql/data',image)
start=time.perf_counter()
for _ in range(100):
try: run('exec',target,'pg_isready','-U','messenger'); break
except subprocess.CalledProcessError: time.sleep(.2)
else: raise AssertionError('restore PostgreSQL did not become ready')
run('exec','-i',target,'pg_restore','-U','messenger','-d','messenger','--exit-on-error',input=dump)
result['restore']={'seconds_including_startup':round(time.perf_counter()-start,3),'fresh_volume':volume,'published_ports':False}
# pg_restore schema/data includes all constraints and indexes.
query="SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'members',(SELECT count(*) FROM members),'messages',(SELECT count(*) FROM messages),'sessions',(SELECT count(*) FROM sessions))"
counts=json.loads(run('exec',target,'psql','-U','messenger','-Atc',query))
digest=run('exec',target,'psql','-U','messenger','-Atc',"SELECT md5(string_agg(id::text||chat_id::text||sender_id::text||text||created_at::text,'' ORDER BY id)) FROM messages").decode().strip()
selected=json.loads(run('exec',target,'psql','-U','messenger','-Atc',"SELECT json_agg(row_to_json(t)) FROM (SELECT id,chat_id,sender_id,text,created_at::text FROM messages ORDER BY id LIMIT 20) t"))
selected=[[str(row[k]) for k in ('id','chat_id','sender_id','text','created_at')] for row in selected]
# Normalize equivalent precision/offset rendering, preserving actual instants.
for rows in (selected,result['snapshot']['selected']):
for row in rows: row[-1]=datetime.fromisoformat(row[-1]).isoformat(timespec='microseconds')
assert counts==result['snapshot']['counts']
assert digest==result['snapshot']['all_messages_digest']
assert selected==result['snapshot']['selected']
result['restore'].update(counts=counts,all_messages_digest=digest,selected_20_match=True,verified=True)
finally:
run('rm','-f',target)
run('volume','rm',volume)
result['limitations']='Warm-cache serial variants on one local host; logical backup snapshot, no WAL/PITR; synthetic DB retained for inspection.'
result['database']=dbname
(root/'evidence').mkdir(exist_ok=True)
(root/'evidence/index-restore.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps({k:v for k,v in result.items() if k not in ('plans','snapshot')},indent=2))
if __name__=='__main__':
if '--inside' in sys.argv: inside(sys.argv[-1])
else: host()
+59
View File
@@ -0,0 +1,59 @@
"""Bounded closed-loop HTTP load, raw latency and Docker resource samples."""
from concurrent.futures import ThreadPoolExecutor
import csv
import json
import math
from pathlib import Path
import subprocess
import threading
import time
import uuid
import httpx
ROOT=Path(__file__).resolve().parents[1]
def docker(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8').strip()
rows=[]; samples=[]; done=threading.Event()
def sample():
while not done.is_set():
data=docker('stats','--no-stream','--format','{{json .}}',*docker('compose','ps','-q').splitlines())
samples.extend({'elapsed_s':round(time.perf_counter()-start,3),**json.loads(line)} for line in data.splitlines())
done.wait(1)
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=10) as c:
body={'username':'load_'+uuid.uuid4().hex[:18],'display_name':'Load','password':'synthetic-password-123'}
user=c.post('/api/v1/users',json=body).json()
auth=c.post('/api/v1/auth/sessions',auth=(body['username'],body['password'])).json()
headers={'Authorization':'Bearer '+auth['token']}
chat=c.post('/api/v1/chats',headers=headers,json={'title':'load','member_ids':[user['id']]}).json()
path='/api/v1/chats/'+chat['id']+'/messages'
# Warm up the pool/cache for 2 seconds, outside measurement.
deadline=time.perf_counter()+2
while time.perf_counter()<deadline: c.get(path,headers=headers)
start=time.perf_counter(); deadline=start+10
sampler=threading.Thread(target=sample,daemon=True); sampler.start()
def work(worker):
i=0
while time.perf_counter()<deadline:
now=time.perf_counter(); method='POST' if i%5==0 else 'GET'; status=0
try:
r=c.request(method,path,headers=headers,**({'json':{'text':'synthetic '*100}} if method=='POST' else {'params':{'limit':50}}))
status=r.status_code
except httpx.HTTPError: pass
rows.append({'worker':worker,'method':method,'elapsed_s':round(now-start,6),'latency_ms':round((time.perf_counter()-now)*1000,3),'status':status})
i+=1
with ThreadPoolExecutor(max_workers=10) as pool: list(pool.map(work,range(10)))
duration=time.perf_counter()-start
done.set(); sampler.join(10)
success=sum(r['status'] in (200,201) for r in rows)
latencies=sorted(r['latency_ms'] for r in rows)
summary={'warmup_s':2,'duration_s':round(duration,3),'concurrency':10,'profile':'closed-loop: 1 write then 4 history reads per worker; 1000-character messages',
'requests':len(rows),'success_rps':round(success/duration,2),'error_fraction':1-success/len(rows),
**{f'p{p}_ms':latencies[math.ceil(len(latencies)*p/100)-1] for p in (50,95,99)},
'statuses':{str(s):sum(r['status']==s for r in rows) for s in {r['status'] for r in rows}},'resource_source':'Docker stats samples; CPU percent is host-core percentage, memory is cgroup working set'}
out=ROOT/'evidence'; out.mkdir(exist_ok=True)
with (out/'http-load.csv').open('w',newline='',encoding='utf-8') as f:
writer=csv.DictWriter(f,fieldnames=list(rows[0])); writer.writeheader(); writer.writerows(rows)
(out/'http-resources.json').write_text(json.dumps(samples,indent=2)+'\n',encoding='utf-8')
(out/'http-summary.json').write_text(json.dumps(summary,indent=2)+'\n',encoding='utf-8')
print(json.dumps(summary,indent=2))
assert success==len(rows),'Unexpected failed requests'
+28
View File
@@ -0,0 +1,28 @@
"""Plot recorded medians; all five plans/samples remain in JSON."""
import json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
root=Path(__file__).resolve().parents[1]/'evidence'
data=json.loads((root/'index-restore.json').read_text(encoding='utf-8'))
labels=['Primary only','Chat index','Compound index']
fig,axes=plt.subplots(1,2,figsize=(11,4.5),layout='constrained')
for name,offset,color in [('keyset',-.18,'#087f5b'),('offset',.18,'#d9480f')]:
values=[p['median_ms'] for p in data['plans'] if p['query']==name]
bars=axes[0].bar([i+offset for i in range(3)],values,width=.35,label=name,color=color)
axes[0].bar_label(bars,fmt='%.3f',padding=3,fontsize=8)
axes[0].set_yscale('log'); axes[0].set_ylim(.01,1000)
axes[0].set_ylabel('Median execution, ms (log scale)'); axes[0].legend()
axes[0].set_title('Page 70,001–70,050 of the 100k chat')
bars=axes[1].bar(range(3),[v['median_ms'] for v in data['writes']],color='#4263eb')
axes[1].bar_label(bars,fmt='%.1f',padding=3)
axes[1].set_ylim(0,max(v['median_ms'] for v in data['writes'])*1.25)
axes[1].set_ylabel('Median commit time, ms'); axes[1].set_title('Insert 5,000 messages (5 repetitions)')
for ax in axes:
ax.set_xticks(range(3),labels); ax.grid(axis='y',alpha=.2); ax.set_axisbelow(True)
fig.suptitle('Lab 2 · PostgreSQL 17.11 · 120,000 skewed messages · 1 CPU / 256 MiB')
fig.savefig(root/'indexes.png',dpi=160)
fig.savefig(root/'indexes.svg')
p=root/'indexes.svg'; p.write_text('\n'.join(line.rstrip() for line in p.read_text(encoding='utf-8').splitlines())+'\n',encoding='utf-8')
+20
View File
@@ -0,0 +1,20 @@
"""Restart all three services without deleting volumes; record actual start times."""
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
def command(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8').strip()
def snapshot():
result={}
for service in ('api','db','cache'):
cid=command('compose','ps','-q',service)
result[service]=json.loads(command('inspect','--format','{{json .State}}',cid))['StartedAt']
return result
before=snapshot()
command('compose','restart','api','db','cache')
after=snapshot()
assert all(before[k]!=after[k] for k 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
+123
View File
@@ -0,0 +1,123 @@
"""Integration checks against real Compose services; no mocked dependencies."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import uuid
import httpx
ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'evidence'
OUT.mkdir(exist_ok=True)
evidence={}
def docker(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
def sql(query):
return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',query)
def wait_ready(client):
deadline=time.monotonic()+60
while time.monotonic()<deadline:
try:
if client.get('/health/ready').status_code==200: return
except httpx.HTTPError: pass
time.sleep(.3)
raise AssertionError('readiness timeout')
def register(client):
name='v_'+uuid.uuid4().hex[:20]
body={'username':name,'display_name':'Проверка','password':'correct-horse-test-123'}
r=client.post('/api/v1/users',json=body); assert r.status_code==201,r.text
return body,r.json()
def login(client,body):
r=client.post('/api/v1/auth/sessions',auth=(body['username'],body['password']))
assert r.status_code==201,r.text
return {'Authorization':'Bearer '+r.json()['token']}
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=12) as c:
wait_ready(c)
smoke=subprocess.check_output([sys.executable,'-X','utf8','tests/smoke.py'],cwd=ROOT,text=True,encoding='utf-8')
evidence['public_smoke']=smoke.strip()
body,user=register(c); headers=login(c,body)
bad=c.post('/api/v1/auth/sessions',auth=(body['username'],'definitely-wrong-password'))
assert bad.status_code==401
assert c.get('/api/v1/users/me',headers={'X-User-Id':user['id']}).status_code==401
assert c.get('/api/v1/users/me',auth=(body['username'],body['password'])).status_code==401
evidence['authentication_negative']='wrong password, Basic on protected route, X-User-Id: 401'
race={'username':'race_'+uuid.uuid4().hex[:18],'display_name':'Race','password':body['password']}
with ThreadPoolExecutor(max_workers=8) as pool:
statuses=list(pool.map(lambda _:c.post('/api/v1/users',json=race).status_code,range(8)))
assert statuses.count(201)==1 and statuses.count(409)==7,statuses
evidence['registration_race']=statuses
before=sql('SELECT count(*) FROM chats')
bad=c.post('/api/v1/chats',headers=headers,json={'title':'rollback','member_ids':[user['id'],str(uuid.uuid4())]})
assert bad.status_code==400,bad.text
assert before==sql('SELECT count(*) FROM chats')
evidence['rollback']='missing member: 400; chats count unchanged'
chat=c.post('/api/v1/chats',headers=headers,json={'title':'parallel','member_ids':[user['id']]}).json()
path='/api/v1/chats/'+chat['id']+'/messages'
with ThreadPoolExecutor(max_workers=10) as pool:
replies=list(pool.map(lambda n:c.post(path,headers=headers,json={'text':f'parallel {n}'}),range(100)))
assert all(r.status_code==201 for r in replies),[r.status_code for r in replies]
records=[]; cursor=None
while True:
page=c.get(path,headers=headers,params={'limit':17,**({'cursor':cursor} if cursor else {})}).json()
records+=page['items']; cursor=page['next_cursor']
if cursor is None: break
assert len(records)==100 and len({r['id'] for r in records})==100
assert {r['id'] for r in records}=={r.json()['id'] for r in replies}
evidence['concurrent_messages']={'sent':100,'read':len(records),'page_size':17}
def hits():
stats=docker('compose','exec','-T','cache','valkey-cli','INFO','stats')
return int(next(line.split(':')[1] for line in stats.splitlines() if line.startswith('keyspace_hits:')))
hits_before=hits()
for _ in range(5): assert c.get('/api/v1/users/me',headers=headers).status_code==200
evidence['cache_hit_delta']=hits()-hits_before
assert evidence['cache_hit_delta']>=5
docker('compose','stop','cache')
try:
start=time.perf_counter()
r=c.get('/api/v1/users/me',headers=headers)
evidence['cache_down']={'status':r.status_code,'seconds':round(time.perf_counter()-start,3)}
assert r.status_code==200
assert c.get('/api/v1/users/me',headers={'Authorization':'Bearer '+'x'*43}).status_code==401
finally: docker('compose','start','cache')
docker('compose','stop','db')
try:
start=time.perf_counter(); r=c.get('/api/v1/users/me',headers=headers)
evidence['database_down']={'status':r.status_code,'seconds':round(time.perf_counter()-start,3)}
assert r.status_code==503 and time.perf_counter()-start<10
assert c.get('/api/v1/users/me').status_code==401
finally: docker('compose','start','db')
wait_ready(c)
assert c.get('/api/v1/users/me',headers=headers).status_code==200
assert c.delete('/api/v1/auth/sessions/current',headers=headers).status_code==204
assert c.get('/api/v1/users/me',headers=headers).status_code==401
evidence['logout']='204 then 401'
# A separate API process with short TTL uses the same persistent dependencies.
name='lab2-expiry-'+uuid.uuid4().hex[:8]
docker('compose','run','-d','--no-deps','--name',name,'-p','127.0.0.1::8080','-e','SESSION_TTL_SECONDS=2','api')
try:
binding=docker('port',name,'8080/tcp').split(':')[-1]
with httpx.Client(base_url='http://127.0.0.1:'+binding,timeout=10) as c:
wait_ready(c); body,user=register(c); headers=login(c,body)
assert c.get('/api/v1/users/me',headers=headers).status_code==200
time.sleep(2.2)
assert c.get('/api/v1/users/me',headers=headers).status_code==401
evidence['short_ttl']='SESSION_TTL_SECONDS=2: 200 then 401 after 2.2s'
finally: docker('rm','-f',name)
evidence['migration_repeat']=docker('compose','run','--rm','--no-deps','migrate')
if os.name=='nt':
with tempfile.TemporaryDirectory(prefix='lab2-hook-') as tmp:
hook=Path(tmp)/'restart.cmd'
hook.write_text('@echo off\n"'+sys.executable+'" "'+str(ROOT/'scripts/restart.py')+'"\n',encoding='utf-8')
evidence['public_persistence']=subprocess.check_output([sys.executable,'-X','utf8','tests/resilience.py','--mode','persistence','--action-script',str(hook)],cwd=ROOT,text=True,encoding='utf-8').strip()
else:
evidence['public_persistence']=subprocess.check_output([sys.executable,'tests/resilience.py','--mode','persistence','--action-script','scripts/restart.sh'],cwd=ROOT,text=True).strip()
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))