Files
mtusi2026lab2/student-tests/research.py
T
2026-11-05 01:43:30 +03:00

76 lines
5.6 KiB
Python

"""Track 2: isolated 120k-row study, actual pg_dump/restore and content verification."""
import datetime,json,subprocess,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def worker(mode,database,host=None):
r=subprocess.run(['docker','compose','exec','-T','api','python','-',mode,database]+([host] if host else []),cwd=ROOT,input=(ROOT/'student-tests/research_worker.py').read_text(),stdout=subprocess.PIPE,text=True,check=True)
return json.loads(r.stdout)
def main():
suffix=uuid.uuid4().hex[:10]; source='lab2_study_'+suffix; restored=source+'_restored'
print('Fresh isolated databases:',source,restored,flush=True)
prepared=worker('prepare',source)
print('Seeded',prepared['messages'],'synthetic messages:',prepared['distribution'],flush=True)
result=worker('benchmark',source)
dump='/tmp/'+source+'.dump'
recovery='lab2-recovery-'+suffix; volume=recovery+'-data'
container=subprocess.check_output(['docker','compose','ps','-q','api'],cwd=ROOT,text=True).strip()
network=next(iter(json.loads(subprocess.check_output(['docker','inspect','--format','{{json .NetworkSettings.Networks}}',container],text=True))))
subprocess.run(['docker','volume','create',volume],check=True,stdout=subprocess.DEVNULL)
started=False
def db(*args):
subprocess.run(['docker','compose','exec','-T','db',*args],cwd=ROOT,check=True)
try:
start=time.perf_counter();db('pg_dump','-U','messenger','-d',source,'-Fc','-f',dump); backup_s=time.perf_counter()-start
start=time.perf_counter()
subprocess.run(['docker','run','-d','--name',recovery,'--network',network,
'-e','POSTGRES_DB='+restored,'-e','POSTGRES_USER=messenger',
'-e','POSTGRES_PASSWORD_FILE=/run/secrets/db_password',
'--mount','type=bind,src='+str(ROOT/'secrets/db_password')+',dst=/run/secrets/db_password,readonly',
'--mount','type=volume,src='+volume+',dst=/var/lib/postgresql/data',
'postgres:17.6-bookworm'],check=True,stdout=subprocess.DEVNULL)
started=True
for _ in range(60):
probe=subprocess.run(['docker','exec',recovery,'pg_isready','-U','messenger','-d',restored],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
if probe.returncode==0:
break
time.sleep(1)
# Wait until final server accepts TCP inside the default network.
for _ in range(60):
probe=subprocess.run(['docker','exec',recovery,'pg_isready','-h','127.0.0.1','-U','messenger','-d',restored],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
if probe.returncode==0: break
time.sleep(1)
else: raise RuntimeError('Restoration server did not become ready')
producer=subprocess.Popen(['docker','compose','exec','-T','db','cat',dump],cwd=ROOT,stdout=subprocess.PIPE)
try:
consumer=subprocess.run(['docker','exec','-i',recovery,'pg_restore','-U','messenger','-d',restored,'--exit-on-error','--no-owner'],stdin=producer.stdout)
producer.stdout.close()
code=producer.wait()
if code or consumer.returncode: raise RuntimeError('Backup stream or restore failed')
finally:
if producer.poll() is None: producer.kill();producer.wait()
restore_s=time.perf_counter()-start
start=time.perf_counter();actual=worker('verify',restored,recovery);verify_s=time.perf_counter()-start
expected=result.pop('fingerprint')
if actual!=expected: raise AssertionError('Restored counts, full message digest or samples differ')
size=int(subprocess.check_output(['docker','compose','exec','-T','db','stat','-c','%s',dump],cwd=ROOT,text=True))
result['backup_restore']={'backup_s':backup_s,'fresh_container_bootstrap_and_restore_s':restore_s,'verification_s':verify_s,'dump_bytes':size,'expected':expected,'restored':actual,'identical':True,'source_database':source,'restored_database':restored,'new_volume':volume,'recovery_container':recovery,'limitation':'logical snapshot; no PITR or concurrent writes; separate PostgreSQL instance and fresh named volume on the same physical Docker host'}
result['utc']=datetime.datetime.now(datetime.timezone.utc).isoformat()
(ROOT/'evidence/query-study.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')
print('PASS: 2 indexes, 3 rounds, 3 query profiles, 20 measured reads/profile, real 5000-row writes with rollback',flush=True)
print('PASS: pg_dump -> NEW PostgreSQL container + NEW volume -> table counts + ALL 120000 messages SHA256 + selected messages match',flush=True)
print('Backup %.3fs; restore %.3fs; verification %.3fs; dump %d bytes'%(backup_s,restore_s,verify_s,size),flush=True)
for variant in ['global','chat_first']:
rows=[r for r in result['results'] if r['variant']==variant]
print(variant,'5000-row insert ms:',[round(r['insert_5000_ms'],3) for r in rows],flush=True)
for scenario in ['hot-middle','medium-first','tiny-first']:
print(variant,scenario,'median ms per round:',[round(q['median_ms'],3) for r in rows for q in r['queries'] if q['scenario']==scenario],flush=True)
finally:
# Only objects created by this run; main messenger database and named volume are never removed.
db('rm','-f',dump)
if started: subprocess.run(['docker','rm','-f',recovery],check=True,stdout=subprocess.DEVNULL)
print('Research source database and recovered volume retained for inspection; recovery process stopped; no dump/credentials included in evidence.',flush=True)
if __name__=='__main__': main()