This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
"""Direct SQL evidence: rollback, idempotent migrations, real EXPLAIN on 12000 rows.
|
||||
Run inside API container: docker compose exec -T api python student-tests/database.py
|
||||
Synthetic SQL data is rolled back after the experiment.
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
import psycopg
|
||||
from db import make_pool,migrate
|
||||
|
||||
async def main():
|
||||
pool=make_pool()
|
||||
await pool.open()
|
||||
try:
|
||||
await pool.wait()
|
||||
await migrate(pool)
|
||||
await migrate(pool)
|
||||
print('PASS: migrations applied twice')
|
||||
async with pool.connection() as conn:
|
||||
before=(await (await conn.execute('SELECT count(*) n FROM chats')).fetchone())['n']
|
||||
try:
|
||||
async with conn.transaction():
|
||||
chat=uuid.uuid4()
|
||||
await conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)',(chat,'rollback-check'))
|
||||
await conn.execute('INSERT INTO members VALUES (%s,%s)',(chat,uuid.uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('expected foreign key failure')
|
||||
after=(await (await conn.execute('SELECT count(*) n FROM chats')).fetchone())['n']
|
||||
assert before==after
|
||||
print('PASS: rollback removes partial chat')
|
||||
# Roll back synthetic rows while retaining actual planner output.
|
||||
async with conn.transaction(force_rollback=True):
|
||||
user,chat=uuid.uuid4(),uuid.uuid4()
|
||||
await conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',(user,'plan_'+uuid.uuid4().hex[:16],'plan','not-a-login-hash'))
|
||||
await conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)',(chat,'plan'))
|
||||
await conn.execute('INSERT INTO members VALUES (%s,%s)',(chat,user))
|
||||
await conn.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) SELECT gen_random_uuid(),%s,%s,'message '||n, '2026-01-01'::timestamptz+n*interval '1 microsecond' FROM generate_series(1,12000) n",(chat,user))
|
||||
await conn.execute('ANALYZE messages')
|
||||
row=await (await conn.execute('SELECT created_at,id FROM messages WHERE chat_id=%s ORDER BY created_at,id OFFSET 9000 LIMIT 1',(chat,))).fetchone()
|
||||
plan=await (await conn.execute('EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51',(chat,row['created_at'],row['id']))).fetchall()
|
||||
rendered='\n'.join(r['QUERY PLAN'] for r in plan)
|
||||
print('EXPLAIN: 12000 messages; cursor after row 9001; page 51')
|
||||
print(rendered)
|
||||
assert 'messages_history' in rendered and 'Index' in rendered
|
||||
print('PASS: history uses messages_history index')
|
||||
finally:
|
||||
await pool.close()
|
||||
|
||||
if __name__=='__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Run on a dedicated API with SESSION_TTL_SECONDS=2."""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,run
|
||||
|
||||
def main():
|
||||
c=Client()
|
||||
user=c.user('expiry')
|
||||
c.call('GET','/api/v1/users/me',actor=user,schema='User')
|
||||
time.sleep(2.5)
|
||||
c.call('GET','/api/v1/users/me',401,actor=user)
|
||||
print('PASS: short session expires (expected configured TTL=2)')
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Extra black-box cases. Uses public Client without modifying public tests."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,check,run
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
body = {'username':'race_'+uuid.uuid4().hex[:16],'display_name':'Гонка','password':'Пароль:🙂'*3}
|
||||
def register(_):
|
||||
return Client().call('POST','/api/v1/users',[201,409],body=body)['status']
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
statuses = list(pool.map(register,range(4)))
|
||||
check(statuses.count(201)==1 and statuses.count(409)==3,'registration race failed')
|
||||
print('PASS: concurrent registration: 1 x 201, 3 x 409')
|
||||
credential = base64.b64encode((body['username']+':'+body['password']).encode()).decode()
|
||||
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
|
||||
print('PASS: Unicode password with colon')
|
||||
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'rollback-'+uuid.uuid4().hex,'member_ids':[alice['id'],str(uuid.uuid4())]})
|
||||
c.call('GET','/api/v1/chats/not-a-uuid',401)
|
||||
c.call('GET','/api/v1/chats/not-a-uuid',400,actor=alice)
|
||||
c.call('POST','/api/v1/users',400,body={**body,'extra':True})
|
||||
for text in ('', ' ', 'x'*4001):
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=alice,body={'text':text})
|
||||
for i in range(6):
|
||||
c.message(alice,chat,'page '+str(i))
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
page=c.call('GET',path+'?limit=2',actor=alice,schema='MessagePage')['json']
|
||||
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id']]},schema='Chat')['json']
|
||||
from urllib.parse import quote
|
||||
cursor=quote(page['next_cursor'],safe='')
|
||||
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+cursor,400,actor=alice)
|
||||
c.call('GET',path+'?cursor=bad',400,actor=alice)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice)
|
||||
print('PASS: validation, cursor isolation, logout')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Optional Linux-only native verification, requires installed PostgreSQL/Redis binaries.
|
||||
NATIVE_DATA must be a separate test directory. Ports: 8080, 55432, 56379.
|
||||
Uses local trust authentication on synthetic data; never deploy this test cluster.
|
||||
Primary supported user workflow is scripts/verify.py with Docker Compose.
|
||||
"""
|
||||
import os,subprocess,sys,time,json,signal
|
||||
from pathlib import Path
|
||||
LAB=Path(__file__).resolve().parents[1]
|
||||
ROOT=Path(os.environ['NATIVE_DATA']).resolve()
|
||||
ROOT.mkdir(parents=True,exist_ok=True)
|
||||
PY=sys.executable
|
||||
PG=Path(os.environ['PG_BIN']).resolve()
|
||||
REDIS=Path(os.environ['REDIS_SERVER']).absolute()
|
||||
os.environ.update(DATABASE_URL='postgresql://agent@127.0.0.1:55432/postgres',CACHE_URL='redis://127.0.0.1:56379/0',CURSOR_SECRET='native-test-only-cursor-secret-01234567890123456789',APP_HOST='127.0.0.1',APP_PORT='8080',SESSION_TTL_SECONDS='3600')
|
||||
sys.path.insert(0,str(LAB/'tests'))
|
||||
from client import Client,check,Failure
|
||||
from resilience import history
|
||||
processes={}
|
||||
logs=[]
|
||||
def start(name):
|
||||
commands={'db':[str(PG/'postgres'),'-D',str(ROOT/'postgres'),'-p','55432','-h','127.0.0.1','-c',"unix_socket_directories="],
|
||||
'cache':[str(REDIS),'--port','56379','--bind','127.0.0.1','--dir',str(ROOT/'redis'),'--appendonly','yes'],
|
||||
'api':[PY,'run.py']}
|
||||
log=open(ROOT/(name+'-native.log'),'a'); logs.append(log)
|
||||
processes[name]=subprocess.Popen(commands[name],cwd=LAB,stdout=log,stderr=log)
|
||||
def stop(name):
|
||||
p=processes.pop(name)
|
||||
p.send_signal(signal.SIGINT if name=='db' else signal.SIGTERM); p.wait(timeout=15)
|
||||
def wait(c):
|
||||
for _ in range(60):
|
||||
try:
|
||||
c.call('GET','/health/ready',schema='Health');return
|
||||
except Failure:time.sleep(.3)
|
||||
raise RuntimeError('not ready; see logs')
|
||||
def test(script,out=None,env=None):
|
||||
p=subprocess.run([PY,script],cwd=LAB,text=True,capture_output=True,env=env)
|
||||
print(p.stdout,flush=True)
|
||||
if out:(LAB/'evidence'/out).write_text(p.stdout)
|
||||
if p.returncode:print(p.stderr);raise RuntimeError(script+' failed')
|
||||
try:
|
||||
(ROOT/'redis').mkdir(exist_ok=True)
|
||||
if not (ROOT/'postgres/PG_VERSION').exists():
|
||||
subprocess.run([str(PG/'initdb'),'-D',str(ROOT/'postgres'),'-U','agent','-A','trust','--no-locale','-E','UTF8'],check=True,stdout=subprocess.DEVNULL)
|
||||
start('db');start('cache');time.sleep(1);start('api')
|
||||
c=Client();wait(c)
|
||||
test('tests/smoke.py');test('student-tests/extra.py')
|
||||
test('student-tests/database.py','local-explain-and-rollback.txt')
|
||||
a,b,e,chat=c.bootstrap();m=c.message(a,chat,'persistence')['json']
|
||||
for name in ('api','db','cache'):stop(name)
|
||||
for name in ('db','cache'):start(name)
|
||||
time.sleep(1);start('api');wait(c)
|
||||
check(m in history(c,b,chat),'message lost')
|
||||
c.call('GET','/api/v1/users/me',actor=a,schema='User')
|
||||
print('PASS: actual API/PostgreSQL/Redis process restart preserves data and existing tokens',flush=True)
|
||||
import redis
|
||||
r=redis.Redis.from_url(os.environ['CACHE_URL']);check(r.exists('profile:v1:'+a['id']),'no cache key')
|
||||
print('PASS: actual Redis cache key exists',flush=True)
|
||||
stop('cache')
|
||||
t=time.monotonic();c.call('GET','/api/v1/users/me',actor=a,schema='User');elapsed=time.monotonic()-t
|
||||
check(elapsed<5,'cache timeout');c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Bearer '+'a'*43})
|
||||
print('PASS: Redis outage fallback %.3fs; invalid token rejected'%elapsed,flush=True)
|
||||
start('cache');stop('db')
|
||||
t=time.monotonic();c.call('GET','/api/v1/users/me',503,actor=a);elapsed=time.monotonic()-t
|
||||
check(elapsed<8,'DB timeout');c.call('GET','/health/ready',503);c.call('GET','/health/live',schema='Health')
|
||||
print('PASS: PostgreSQL outage 503 %.3fs; live 200, ready 503'%elapsed,flush=True)
|
||||
start('db');wait(c)
|
||||
stop('api');os.environ['SESSION_TTL_SECONDS']='2';start('api');wait(c)
|
||||
test('student-tests/expiry.py')
|
||||
print('PASS: native integration suite (Docker not available)',flush=True)
|
||||
finally:
|
||||
for name in list(processes):stop(name)
|
||||
for log in logs:log.close()
|
||||
Reference in New Issue
Block a user