Prepare verified laboratory 2 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:31:17 +03:00
parent 65003b6119
commit 62d7c2023c
85 changed files with 9426 additions and 38 deletions
+126
View File
@@ -0,0 +1,126 @@
import { resolve } from 'node:path';
const root = resolve(import.meta.dir, '..');
const lab = (await Bun.file(resolve(root, 'lab.json')).json()).number;
const base = process.env.BASE_URL ?? 'http://127.0.0.1:28202';
const prefix = `st_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
let assertions = 0;
function check(value: unknown, message: string): asserts value { if (!value) throw new Error(message); assertions++; }
async function call(method: string, path: string, status: number, token?: string, body?: unknown, headers: Record<string, string> = {}) {
const response = await fetch(base + path, {method, headers: {...(token ? {Authorization: `Bearer ${token}`} : {}), ...(body !== undefined ? {'Content-Type': 'application/json'} : {}), ...headers}, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(8000)});
const bytes = await response.arrayBuffer();
let json: any; try {json = JSON.parse(new TextDecoder().decode(bytes));} catch {}
check(response.status === status, `${method} ${path}: expected ${status}, got ${response.status}`);
check(Boolean(response.headers.get('X-Request-Id')), 'Missing request ID');
if (status >= 400) check(json?.error?.request_id === response.headers.get('X-Request-Id'), 'Error request ID mismatch');
return {json, response, bytes};
}
const password = 'synthetic:пароль🙂123';
async function user(suffix: string) {
const registration = {username: prefix + suffix, display_name: 'Синтетический тест', password};
const {json} = await call('POST', '/api/v1/users', 201, undefined, registration);
const login = await call('POST', '/api/v1/auth/sessions', 201, undefined, undefined, {Authorization: 'Basic ' + Buffer.from(registration.username + ':' + password).toString('base64')});
check(!JSON.stringify(json).includes('password'), 'Password leaked in User');
check(typeof login.json.token === 'string' && login.json.token.length >= 43, 'Token entropy/shape');
return {id: json.id, token: login.json.token, registration};
}
async function cleanup() {
// No API delete exists. Scope every statement to this run's random username prefix.
const sql = `BEGIN;
CREATE TEMP TABLE own_users AS SELECT id FROM users WHERE left(username,${prefix.length})='${prefix}';
DO $fixture$ BEGIN IF EXISTS(SELECT 1 FROM chat_members mine JOIN chat_members other ON other.chat_id=mine.chat_id WHERE mine.user_id IN(SELECT id FROM own_users) AND other.user_id NOT IN(SELECT id FROM own_users)) THEN RAISE EXCEPTION 'fixture has foreign memberships';END IF;END $fixture$;
CREATE TEMP TABLE own_chats AS SELECT DISTINCT mine.chat_id AS id FROM chat_members mine WHERE mine.user_id IN (SELECT id FROM own_users) AND NOT EXISTS(SELECT 1 FROM chat_members other WHERE other.chat_id=mine.chat_id AND other.user_id NOT IN(SELECT id FROM own_users));
DELETE FROM messages WHERE sender_id IN (SELECT id FROM own_users);
DELETE FROM sessions WHERE user_id IN (SELECT id FROM own_users);
DELETE FROM chat_members WHERE chat_id IN (SELECT id FROM own_chats);
DELETE FROM chats WHERE id IN (SELECT id FROM own_chats);
DELETE FROM users WHERE id IN (SELECT id FROM own_users);
COMMIT;`;
const p = Bun.spawn([resolve(root,'scripts/compose.sh'), 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1'], {cwd: root, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'});
p.stdin.write(sql); p.stdin.end();
await new Response(p.stdout).text();
const err = await new Response(p.stderr).text();
if (await p.exited !== 0) throw new Error('Fixture cleanup failed: ' + err.replace(/password|token/gi, '[redacted]'));
}
let primary: unknown;
try {
const alice = await user('a'), bob = await user('b'), eve = await user('e');
await call('POST','/api/v1/users',400,undefined,{username:prefix+'x',display_name:'x'});
await call('POST','/api/v1/users',400,undefined,{...alice.registration,password:'short'});
await call('POST','/api/v1/users',400,undefined,{...alice.registration,extra:1});
const race = await Promise.all([0,1].map(async () => {
const r = await fetch(base+'/api/v1/users',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...alice.registration,username:prefix+'race'})});
await r.arrayBuffer(); return r.status;
}));
check(race.sort().join(',') === '201,409','Registration race must create exactly one user');
const denied = await call('GET','/api/v1/users/me',401,undefined,undefined,{'X-User-Id':alice.id});
check(denied.response.headers.get('WWW-Authenticate') === 'Bearer realm="messenger"','Bearer challenge');
const wrong = await call('POST','/api/v1/auth/sessions',401,undefined,undefined,{Authorization:'Basic '+Buffer.from(alice.registration.username+':wrong-password').toString('base64')});
check(wrong.response.headers.get('WWW-Authenticate') === 'Basic realm="messenger", charset="UTF-8"','Basic challenge');
const invalidChat={title:'rollback',member_ids:[alice.id,crypto.randomUUID()]};
await call('POST','/api/v1/chats',400,alice.token,invalidChat);
let page = (await call('GET','/api/v1/chats',200,alice.token)).json;
check(page.items.length === 0 && page.next_cursor === null,'Failed composite create left a chat');
const chat = (await call('POST','/api/v1/chats',201,alice.token,{title:'Пагинация',member_ids:[bob.id,alice.id]})).json;
const path='/api/v1/chats/'+chat.id+'/messages';
check((await call('GET',path,200,alice.token)).json.items.length===0,'Empty page');
for (const limit of ['0','-1','101','1.2','abc']) await call('GET',path+'?limit='+limit,400,alice.token);
await call('GET',path+'?cursor=%%%',400,alice.token);
await call('GET',path,404,eve.token);
const sent=[];
for(let i=0;i<102;i++) {
const h=lab>=3?{'Idempotency-Key':crypto.randomUUID()}:{};
sent.push((await call('POST',path,201,alice.token,{text:`Сообщение ${i}`},h)).json);
}
check((await call('GET',path,200,bob.token)).json.items.length===50,'Default bound');
check((await call('GET',path+'?limit=100',200,bob.token)).json.items.length===100,'Maximum bound');
const seen=[];let cursor: string|null=null;
do {
page=(await call('GET',path+'?limit=7'+(cursor?'&cursor='+encodeURIComponent(cursor):''),200,bob.token)).json;
check(page.items.length<=7,'Page bound');seen.push(...page.items);cursor=page.next_cursor;
}while(cursor);
check(JSON.stringify(seen)===JSON.stringify(sent),'Traversal must preserve every item exactly once');
const other=(await call('POST','/api/v1/chats',201,alice.token,{title:'Другой',member_ids:[alice.id]})).json;
const first=(await call('GET',path+'?limit=1',200,alice.token)).json;
await call('GET','/api/v1/chats/'+other.id+'/messages?cursor='+encodeURIComponent(first.next_cursor),400,alice.token);
if(lab>=3){
const key=crypto.randomUUID(),headers={'Idempotency-Key':key},body={text:'один конкурентный результат'};
const results=await Promise.all(Array.from({length:12},()=>call('POST',path,201,alice.token,body,headers)));
check(new Set(results.map(r=>r.json.id)).size===1,'Concurrent retries duplicated a message');
await call('POST',path,409,alice.token,{text:'другой'},headers);
await call('POST',path,400,alice.token,{text:'без ключа'});
const ids=new Set<string>();for(let i=0;i<20;i++)ids.add((await call('GET','/api/v1/users/me',200,alice.token)).response.headers.get('X-Instance-Id')!);
check(ids.size>=2&&!ids.has(null as any),'One session must reach multiple actual replicas');
}
await call('DELETE','/api/v1/auth/sessions/current',204,alice.token);
await call('GET','/api/v1/users/me',401,alice.token);
if(process.env.FAILURES==='1') {
async function compose(args:string[], ttl?:string) {
const p=Bun.spawn([resolve(root,'scripts/compose.sh'),...args],{cwd:root,env:{...process.env,...(ttl?{SESSION_TTL_SECONDS:ttl}:{})},stdout:'pipe',stderr:'pipe'});
await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);
check(await p.exited===0,'Compose failure action failed');
}
async function ready() {for(let i=0;i<150;i++){try{const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1500)});await r.arrayBuffer();if(r.status===200)return;}catch{}await Bun.sleep(100);}throw new Error('Readiness did not recover');}
try {
await compose(['stop','valkey']);
await call('GET','/api/v1/users/me',200,bob.token);
await call('GET','/api/v1/users/me',401,undefined,undefined,{'X-User-Id':bob.id});
}finally{await compose(['start','valkey']);}
try {
await compose(['stop','postgres']);
await call('GET','/api/v1/users/me',503,bob.token);
await call('GET','/health/ready',503);
await call('GET','/health/live',200);
}finally{await compose(['start','postgres']);await ready();}
await call('GET','/api/v1/users/me',200,bob.token);
if(lab===2){try {
await compose(['up','-d','--no-deps','--force-recreate','api'],'2');await ready();
const short=await user('ttl');
await call('GET','/api/v1/users/me',200,short.token);
await Bun.sleep(2200);
await call('GET','/api/v1/users/me',401,short.token);
}finally{await compose(['up','-d','--no-deps','--force-recreate','api'],'3600');await ready();}}
}
} catch(error) { primary=error; }
try {await cleanup();} catch(error) {console.error(String(error));if(!primary)primary=error;}
if(primary)throw primary;
console.log(`PASS lab${lab}: ${assertions} HTTP assertions, registration race, rollback, pagination, authentication${lab>=3?', concurrent idempotency and replica sharing':''}; fixture cleanup completed`);
+74
View File
@@ -0,0 +1,74 @@
"""Plot measured coursework results; this is data analysis, not application code."""
import argparse
import json
from pathlib import Path
from statistics import mean
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument('summary', type=Path)
parser.add_argument('--pool-summary', type=Path)
args = parser.parse_args()
data = json.loads(args.summary.read_text())
if data.get('complete') is not True:
raise SystemExit('Only a completed, cleaned-up run can be plotted')
plt.rcParams.update({'svg.fonttype': 'none', 'font.size': 10})
if 'dataset' in data:
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), constrained_layout=True)
modes = ['chat_only', 'history']
for axis, key, title in zip(axes, ['read', 'write'], ['Deep history page (51 rows)', 'Insert 1,000 messages']):
values = [data['plans'][mode][key]['Execution Time'] for mode in modes]
axis.bar(['chat_id', 'chat_id + time + id'], values, color=['#6b7280', '#2563eb'])
axis.set_ylabel('Execution time, ms')
axis.set_title(title)
if key == 'read':
axis.set_yscale('log')
for index, value in enumerate(values):
axis.annotate(f'{value:.3f}', (index, value), xytext=(0, 4), textcoords='offset points', ha='center')
fig.suptitle('100,000 skewed messages; one EXPLAIN ANALYZE per index')
fig.savefig(args.summary.parent / 'comparison.svg')
plt.close(fig)
else:
if data.get('valid') is not True:
raise SystemExit('Invalid measurements')
rows = data['samples']
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), constrained_layout=True)
for phase, label, color in [('fixed', 'Fixed total API CPU/RAM', '#2563eb'), ('growing', 'Resources grow with replicas', '#c2410c')]:
groups = [[r for r in rows if r['phase'] == phase and r['replicas'] == count] for count in [1, 2, 4]]
if not all(groups):
continue
for axis, metric in zip(axes, ['rps', 'p95']):
values = [[r['metrics']['successful_rps'] if metric == 'rps' else r['metrics']['successful_latency_ms']['p95'] for r in group] for group in groups]
centers = [mean(value) for value in values]
errors = [[center - min(value) for center, value in zip(centers, values)], [max(value) - center for center, value in zip(centers, values)]]
axis.errorbar([1, 2, 4], centers, yerr=errors, marker='o', capsize=4, label=label, color=color)
for axis, title in zip(axes, ['Successful requests / second', 'p95 of successful requests, ms']):
axis.set_title(title)
axis.set_xlabel('API replicas')
axis.set_xticks([1, 2, 4])
axis.grid(alpha=.2)
axis.legend(fontsize=8)
fig.suptitle('Closed loop, concurrency 16, 5 seconds; mean and range of two runs')
fig.savefig(args.summary.parent / 'scaling.svg')
plt.close(fig)
pool_data = json.loads(args.pool_summary.read_text()) if args.pool_summary else data
if pool_data.get('complete') is not True:
raise SystemExit('Incomplete pool experiment')
pools = [[r for r in pool_data['samples'] if r['phase'] == 'pool' and r['pool'] == size] for size in [8, 1]]
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), constrained_layout=True)
for axis, metric in zip(axes, ['rps', 'p95']):
values = [[r['metrics']['successful_rps'] if metric == 'rps' else r['metrics']['successful_latency_ms']['p95'] for r in group] for group in pools]
centers = [mean(value) for value in values]
axis.bar(['pool = 8', 'pool = 1'], centers, color=['#6b7280', '#2563eb'])
axis.set_ylabel('Successful req/s' if metric == 'rps' else 'p95, ms')
axis.set_ylim(bottom=0)
for index, center in enumerate(centers):
axis.annotate(f'{center:.2f}', (index, center), xytext=(0, 4), textcoords='offset points', ha='center')
fig.suptitle('One hot sender; same single-replica CPU/RAM budget')
fig.savefig(args.summary.parent / 'pool.svg')
plt.close(fig)
print('Saved standalone SVG research figures')
+1
View File
@@ -0,0 +1 @@
matplotlib==3.11.2
+77
View File
@@ -0,0 +1,77 @@
import {resolve} from 'node:path';
import {mkdir,mkdtemp,writeFile,chmod} from 'node:fs/promises';
const root=resolve(import.meta.dir,'..');
if(process.argv.includes('--check')){console.log('Research script parsed without accessing the stand');process.exit(0);}
let stage='preflight';
async function command(args:string[],input?:string|Uint8Array){
const p=Bun.spawn(args,{cwd:root,stdin:input===undefined?'ignore':'pipe',stdout:'pipe',stderr:'pipe',signal:AbortSignal.timeout(120000)});
if(input!==undefined){p.stdin.write(input);p.stdin.end();}
const [out,err]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);
if(await p.exited!==0)throw new Error(`${stage}: command rejected (${args[0]})`);
return out;
}
async function guard(){const p=Bun.spawn(['game-running'],{stdout:'ignore',stderr:'pipe'});await new Response(p.stderr).text();if(await p.exited!==1)throw new Error('Research requires a verified inactive game');}
async function sql(query:string,service='postgres',database='messenger'){return await command([resolve(root,'scripts/compose.sh'),'exec','-T',service,'psql','-X','-qAt','-U','messenger','-d',database,'-v','ON_ERROR_STOP=1'],query);}
const nonce=crypto.randomUUID().replaceAll('-','').slice(0,12),user=crypto.randomUUID(),chats=[crypto.randomUUID(),crypto.randomUUID(),crypto.randomUUID()];
const parent=resolve(root,'evidence/research');await mkdir(parent,{recursive:true});
const evidence=await mkdtemp(resolve(parent,'run-'));
await writeFile(resolve(evidence,'run.json'),JSON.stringify({run_id:nonce,started_at:new Date().toISOString(),state:'started'})+'\n',{flag:'wx'});
const local=resolve(root,'.local');
const results:any={dataset:{messages:100000,distribution:[90000,9000,1000]},plans:{},backup:{}};
let apiStopped=false,restoreTouched=false,primary:unknown;const cleanupErrors:string[]=[];
try{
await guard();
if(!(await command([resolve(root,'scripts/compose.sh'),'ps','--status','running','-q','api'])).trim())throw new Error('Expected coursework API is not running');
stage='stop_api';apiStopped=true;await command([resolve(root,'scripts/compose.sh'),'stop','api']);
if((await command([resolve(root,'scripts/compose.sh'),'ps','--status','running','-q','api'])).trim())throw new Error('API did not stop');
stage='seed';
await sql(`BEGIN;
INSERT INTO users(id,username,display_name,password_hash) VALUES('${user}','research_${nonce}','Synthetic research','disabled-no-login');
INSERT INTO chats(id,title) VALUES ${chats.map((id,i)=>`('${id}','Synthetic ${i}')`).join(',')};
INSERT INTO chat_members(chat_id,user_id) VALUES ${chats.map(id=>`('${id}','${user}')`).join(',')};
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT gen_random_uuid(),CASE WHEN i<=90000 THEN '${chats[0]}'::uuid WHEN i<=99000 THEN '${chats[1]}'::uuid ELSE '${chats[2]}'::uuid END,'${user}','synthetic-'||i,
'2026-01-01T00:00:00Z'::timestamptz+i*interval '1 microsecond' FROM generate_series(1,100000) AS i;
UPDATE users SET message_count=100000 WHERE id='${user}'; COMMIT; ANALYZE messages;`);
const read=`SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id='${chats[0]}' AND (created_at,id)>('2026-01-01T00:00:00.070000Z'::timestamptz,'00000000-0000-0000-0000-000000000000'::uuid) ORDER BY created_at,id LIMIT 51`;
for(const mode of ['chat_only','history']){
await guard();stage='index_'+mode;
if(mode==='chat_only')await sql('DROP INDEX messages_history;CREATE INDEX research_chat_only ON messages(chat_id);ANALYZE messages;');
else await sql('DROP INDEX research_chat_only;CREATE INDEX messages_history ON messages(chat_id,created_at,id);ANALYZE messages;');
stage='read_plan_'+mode;
const raw=await sql('EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) '+read+';');
await writeFile(resolve(evidence,mode+'-read.json'),raw);results.plans[mode]={read:JSON.parse(raw)[0]};
stage='write_plan_'+mode;
const rawWrite=await sql(`EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) INSERT INTO messages(id,chat_id,sender_id,text) SELECT gen_random_uuid(),'${chats[0]}','${user}','write-cost-'||i FROM generate_series(1,1000) i;`);
await writeFile(resolve(evidence,mode+'-write.json'),rawWrite);results.plans[mode].write=JSON.parse(rawWrite)[0];
}
stage='fingerprint';
const fingerprint=`SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'members',(SELECT count(*) FROM chat_members),'messages',(SELECT count(*) FROM messages),'research_messages',(SELECT count(*) FROM messages WHERE sender_id='${user}'),'samples',(SELECT json_agg(t) FROM (SELECT id,text,created_at FROM messages WHERE sender_id='${user}' ORDER BY created_at,id LIMIT 3) t))::text;`;
const before=JSON.parse(await sql(fingerprint));
stage='backup';await guard();const dumpStart=performance.now();
const dump=Bun.spawn([resolve(root,'scripts/compose.sh'),'exec','-T','postgres','pg_dump','-U','messenger','-d','messenger','-Fc','--no-owner','--no-acl'],{cwd:root,stdout:'pipe',stderr:'pipe'});
const dumpFile=resolve(local,'research-backup-'+nonce+'.dump');await Bun.write(dumpFile,new Response(dump.stdout));await new Response(dump.stderr).text();if(await dump.exited!==0)throw new Error('Backup rejected');await chmod(dumpFile,0o600);
results.backup.dump_seconds=(performance.now()-dumpStart)/1000;results.backup.bytes=Bun.file(dumpFile).size;
stage='restore_start';restoreTouched=true;await command([resolve(root,'scripts/compose.sh'),'up','-d','--wait','restore']);
const database='recovery_'+nonce;await sql('CREATE DATABASE '+database,'restore','restore');
stage='restore';const restoreStart=performance.now();
const restore=Bun.spawn([resolve(root,'scripts/compose.sh'),'exec','-T','restore','pg_restore','-U','messenger','-d',database,'--no-owner','--no-acl','--exit-on-error'],{cwd:root,stdin:Bun.file(dumpFile),stdout:'pipe',stderr:'pipe'});
await Promise.all([new Response(restore.stdout).text(),new Response(restore.stderr).text()]);if(await restore.exited!==0)throw new Error('Restore rejected');
results.backup.restore_seconds=(performance.now()-restoreStart)/1000;
const after=JSON.parse(await sql(fingerprint,'restore',database));
if(JSON.stringify(before)!==JSON.stringify(after))throw new Error('Restored row counts or sampled messages differ');
results.backup.verified=before;results.backup.target='separate PostgreSQL container and persistent volume';
await sql('DROP DATABASE '+database,'restore','restore');
await guard();stage='measured';
}catch(error){primary=error;}
finally{
if(apiStopped)try{
await sql('DROP INDEX IF EXISTS research_chat_only;CREATE INDEX IF NOT EXISTS messages_history ON messages(chat_id,created_at,id);');
await sql(`BEGIN;DELETE FROM messages WHERE sender_id='${user}';DELETE FROM chat_members WHERE user_id='${user}';DELETE FROM chats WHERE id=ANY(ARRAY[${chats.map(id=>`'${id}'::uuid`).join(',')}]);DELETE FROM users WHERE id='${user}';COMMIT;`);
}catch{cleanupErrors.push('source_data_or_index');}
if(restoreTouched)try{await sql('DROP DATABASE IF EXISTS recovery_'+nonce,'restore','restore');await command([resolve(root,'scripts/compose.sh'),'stop','restore']);}catch{cleanupErrors.push('restore_database');}
if(apiStopped)try{await command([resolve(root,'scripts/compose.sh'),'start','api']);await command([process.execPath,'--no-env-file','student-tests/wait.ts']);}catch{cleanupErrors.push('api_recovery');}
}
if(primary||cleanupErrors.length){await writeFile(resolve(evidence,'failure.json'),JSON.stringify({run_id:nonce,stage,primary:primary instanceof Error?primary.name:primary?'unknown':null,cleanup_errors:cleanupErrors})+'\n');throw new Error('Research failed; inspect this run failure summary');}
await writeFile(resolve(evidence,'summary.json'),JSON.stringify({run_id:nonce,complete:true,...results},null,2)+'\n',{flag:'wx'});
console.log('PASS lab2 research: '+evidence);
+14
View File
@@ -0,0 +1,14 @@
import {resolve} from 'node:path';
const root=resolve(import.meta.dir,'..');
const lab=(await Bun.file(resolve(root,'lab.json')).json()).number;
const base=process.env.BASE_URL??`http://127.0.0.1:${28200+lab}`;
const needed=lab>=3?Number(process.env.API_REPLICAS??2):1;
const instances=new Set<string>();
for(let attempt=0;attempt<600;attempt++){
try{
const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1000)});await r.arrayBuffer();
if(r.status===200){instances.add(r.headers.get('X-Instance-Id')??'single');if(instances.size>=needed){console.log(`Ready: ${instances.size} API process(es)`);process.exit(0);}}
}catch{}
await Bun.sleep(150);
}
throw new Error('Stand readiness deadline expired');