"""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()