Files
rag-technical-docs-assistant/tests/phase4_operations.py
11linear11 42f5b9e854 fix(ops): harden backend startup and worker recovery
Install modular API, voice and embedding extras and use the supported single-process server entrypoint. Drain worker SIGTERM shutdown within the Compose grace period.

Add isolated HTTPS embedding fixtures, bounded intake execution and reproducible account, publication, restart, lease-recovery and shutdown acceptance. Eight operational scenarios passed with zero real-provider calls.
2026-10-09 17:44:04 -04:00

282 lines
18 KiB
Python

"""Explicit opt-in Docker deployment acceptance with zero real-provider calls.
Run --prepare, build/start the accompanying Compose project, then run --verify.
Never consumes .env, approved corpus, real credentials or operational databases.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import secrets
import subprocess
import time
from uuid import uuid4
import httpx
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = ROOT / 'tests/support/phase4-compose.yml'
URL = 'http://localhost:18080'
def fixture_environment():
return dict(
INGEST_DATABASE_URL='postgresql+psycopg://postgres:fixture@db:5432/rag_ops_test',
INGEST_EMBEDDING_PROVIDER='acceptance-fixture',
INGEST_EMBEDDING_ENDPOINT='https://embedding:8090/v1',
INGEST_EMBEDDING_MODEL='deterministic-fixture', INGEST_EMBEDDING_DIMENSIONS='3',
INGEST_EMBEDDING_API_KEY='fixture-only',
INGEST_EMBEDDING_LIMITS=json.dumps(dict(unit='utf8_bytes', max_input_units=10000,
max_batch_units=320000, max_batch_inputs=32), separators=(',', ':')),
INGEST_POLL_SECONDS='0.2', INGEST_HEARTBEAT_SECONDS='0.25', INGEST_LEASE_SECONDS='2',
INGEST_EMBEDDING_TIMEOUT_SECONDS='40', INGEST_OCR_REVIEW_REQUIRED='true',
SSL_CERT_FILE='/fixtures/ca.pem',
VOICE_PROVIDER='gemini', COOKIE_SECURE='false',
TRUSTED_HOSTS='["localhost:18080","127.0.0.1:18080"]',
TRUSTED_ORIGINS='["http://localhost:18080"]')
def compose(env_path, *args, input=None):
result = subprocess.run(['docker', 'compose', '-p', 'rag-phase4-ops', '-f', str(COMPOSE), *args],
env={**os.environ, 'ACCEPTANCE_ENV_FILE': str(env_path),
'ACCEPTANCE_TLS_DIRECTORY':str(env_path.with_name(env_path.stem+'-tls'))}, input=input,
capture_output=True, text=True, timeout=90, cwd=ROOT)
if result.returncode:
raise RuntimeError('Isolated Compose operation failed: ' + args[0])
return result.stdout
def container_python(env_path, service, source):
return compose(env_path, 'exec', '-T', service, 'python', '-c', source).strip()
def wait_for(fn, seconds=45):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
result = fn()
if result:
return result
time.sleep(.2)
raise TimeoutError('Operational scenario deadline exceeded')
def verify(env_path, output):
report = dict(run_id=str(uuid4()), category='isolated_deployment_fixture',
real_provider_calls=0, scenarios=[])
def record(name, started, **data):
report['scenarios'].append(dict(scenario=name, status='passed',
elapsed_seconds=time.monotonic()-started, **data))
output.write_text(json.dumps(report, indent=2) + '\n')
def request(client, method, path, expected=200, **kwargs):
rid = str(uuid4())
headers = dict(kwargs.pop('headers', {}), **{'X-Request-ID': rid})
response = client.request(method, path, headers=headers, **kwargs)
assert response.status_code == expected, (path, response.status_code)
assert response.headers['x-request-id'] == rid
return response
def fixture(path='/'):
return json.loads(container_python(env_path, 'embedding',
"import urllib.request,ssl; print(urllib.request.urlopen('https://127.0.0.1:8090" + path +
"',context=ssl.create_default_context(cafile='/fixtures/tls/cert.pem')).read().decode())"))
try:
started = time.monotonic()
with httpx.Client(base_url=URL, timeout=10) as client:
def ready():
try:
return client.get('/health/ready').status_code == 200
except httpx.HTTPError:
return False
wait_for(ready)
assert fixture()['fixture_calls'] == 0
ids=[]
for route in ('/health/live', '/health/ready'):
ids.append(request(client, 'GET', route).headers['x-request-id'])
counts={service:int(container_python(env_path,service,
"from pathlib import Path; print(sum("+repr('app.server' if service=='api' else 'app.worker')+
" in p.read_text().split(chr(0)) for p in Path('/proc').glob('[0-9]*/cmdline')))"))
for service in ('api','worker')}
assert counts=={'api':1,'worker':1}
record('real_lifespan_readiness_and_provider_free_health', started, request_ids=ids,
fixture_calls=0,application_process_counts=counts)
started = time.monotonic(); password = secrets.token_hex(24)
account = json.loads(compose(env_path, 'run', '--rm', '-T', '--no-deps', 'api',
'python', '-m', 'app.bootstrap', '--organization-name', 'Phase4 Fixture',
'--username', 'acceptance-admin', '--assistant-name', 'Fixture',
'--instruction', 'Use authorized fixture documents.', '--password-stdin', input=password+'\n'))
compose(env_path, 'run', '--rm', '-T', '--no-deps', 'api', 'python', '-m', 'app.provision',
'--username', 'acceptance-user', '--role', 'user', '--password-stdin', input=password+'\n')
login = request(client, 'POST', '/api/v1/auth/login',
json=dict(username='acceptance-admin', password=password), headers={'Origin':URL})
headers={'Origin':URL, 'X-CSRF-Token':login.json()['csrf_token']}
assert request(client,'GET','/api/v1/me').json()['user']['id']==account['administrator_id']
record('supported_account_provisioning_and_login', started, actor_id=account['administrator_id'],
organization_id=account['organization_id'], request_id=login.headers['x-request-id'])
started=time.monotonic(); body=b'Operational fixture: fee is 5 percent.'; key=str(uuid4())
upload_headers=dict(headers, **{'Idempotency-Key':key})
uploaded=request(client,'POST','/api/v1/documents',202,files={'file':('fixture.md',body)},headers=upload_headers)
document=uploaded.json()['document_id']; job=uploaded.json()['job_id']
replay=request(client,'POST','/api/v1/documents',202,files={'file':('fixture.md',body)},headers=upload_headers)
assert replay.json()['document_id']==document and replay.headers['idempotency-replayed']=='true'
def published():
d=request(client,'GET','/api/v1/documents/'+document).json()
return d if d['status']=='ready' else False
state=wait_for(published)
assert not state['is_active'] and not state['searchable'] and state['ocr_review_required']
selection=request(client,'GET','/api/v1/knowledge-selection').json()
selected=request(client,'PATCH','/api/v1/knowledge-selection',json=dict(expected_revision=selection['revision'],document_ids=[document]),headers=headers)
assert request(client,'GET','/api/v1/documents/'+document).json()['searchable']
assert request(client,'GET','/api/v1/configuration').json()['capabilities']['voice'] is False
record('upload_replay_worker_atomic_publication_and_explicit_selection',started,
document_id=document,job_id=job,original_sha256=hashlib.sha256(body).hexdigest(),
request_ids=[uploaded.headers['x-request-id'],selected.headers['x-request-id']],
fixture_calls=fixture()['fixture_calls'])
started=time.monotonic(); calls=fixture()['fixture_calls']
for _ in range(3):
request(client,'GET','/health/live'); request(client,'GET','/health/ready')
assert fixture()['fixture_calls']==calls
record('repeated_health_does_not_embed',started,fixture_calls_before=calls,fixture_calls_after=calls)
# Supported lifecycle service creates an unconnected fixture reservation;
# no provider adapter or invented calibration report is involved.
started=time.monotonic()
live=json.loads(container_python(env_path,'api',
"from uuid import UUID,uuid4; import json; from app.api.v1.dependencies import get_engine,get_lifecycle_service; "
"from app.modules.auth.service import AuthService; from app.modules.voice.configuration import VoiceSettings; "
"e=get_engine(); a=AuthService(e); _,token,_,_=a.login('acceptance-admin',"+repr(password)+"); "
"u=a.get_current_user(token); l=get_lifecycle_service(e); c=l.create_conversation(u,uuid4()); "
"s=l.create_live_session(u,UUID(c['id']),uuid4(),execution_profile=VoiceSettings().profile()); "
"print(json.dumps({'conversation_id':c['id'],'session_id':s['session_id']})); e.dispose()"))
compose(env_path,'stop','-t','10','api','worker')
compose(env_path,'up','-d','--wait','--no-deps','--force-recreate','db')
compose(env_path,'run','--rm','-T','--no-deps','migrations')
compose(env_path,'up','-d','--no-deps','--force-recreate','api','worker')
wait_for(ready)
session=request(client,'GET','/api/v1/voice/sessions/'+live['session_id'])
assert session.json()['status']=='failed'
assert request(client,'GET','/api/v1/documents/'+document).json()['searchable']
persisted=container_python(env_path,'api',
"import hashlib; from pathlib import Path; from sqlalchemy import text; from app.api.v1.dependencies import get_engine; "
"e=get_engine(); c=e.connect(); k=c.execute(text(\"SELECT storage_key FROM documents WHERE id=:id\"),{'id':"+repr(document)+"}).scalar_one(); "
"print(hashlib.sha256((Path('data/originals')/k).read_bytes()).hexdigest()); c.close(); e.dispose()")
assert persisted==hashlib.sha256(body).hexdigest()
retained=int(container_python(env_path,'api',
"from sqlalchemy import text; from app.api.v1.dependencies import get_engine; "
"from app.api.v1.documents import get_document_services; from app.modules.documents.settings import IngestionSettings; "
"e=get_engine(); c=e.connect(); d=dict(c.execute(text(\"SELECT * FROM documents WHERE id=:id\"),{'id':"+repr(document)+"}).mappings().one()); "
"s=get_document_services(e,IngestionSettings()); a=s.candidates.inspect_pointer(d['extraction_state']['complete_artifact'],document=d); "
"print(len(a.blocks)); c.close(); e.dispose()"))
assert retained==1
record('service_recreation_persists_originals_accounts_selection_and_reconciles_live',started,
**live,terminal_status=session.json()['status'],document_id=document,retained_extraction_blocks=retained,
database_container_recreated=True)
# Kill the fixture worker while an HTTP embedding request is blocked.
started=time.monotonic(); calls_before=fixture()['fixture_calls']; fixture('/block')
second=request(client,'POST','/api/v1/documents',202,files={'file':('recover.md',b'Worker recovery fixture.')},
headers=dict(headers, **{'Idempotency-Key':str(uuid4())})).json()
def processing():
d=request(client,'GET','/api/v1/documents/'+second['document_id']).json()
return d if d['job']['stage']=='embed' else False
wait_for(processing)
wait_for(lambda: fixture()['fixture_calls']>calls_before)
old=container_python(env_path,'api',
"from sqlalchemy import text; from app.api.v1.dependencies import get_engine; e=get_engine(); c=e.connect(); "
"print(c.execute(text(\"SELECT claim_token FROM ingestion_jobs WHERE id=:id\"),{'id':"+repr(second['job_id'])+"}).scalar_one()); c.close(); e.dispose()")
compose(env_path,'kill','-s','SIGKILL','worker'); fixture('/release'); time.sleep(2.5)
compose(env_path,'start','worker')
def recovered():
d=request(client,'GET','/api/v1/documents/'+second['document_id']).json()
return d if d['status']=='ready' else False
recovered_state=wait_for(recovered)
assert not recovered_state['is_active']
summary=json.loads(container_python(env_path,'api',
"import json; from sqlalchemy import text; from app.api.v1.dependencies import get_engine; e=get_engine(); c=e.connect(); "
"r=c.execute(text(\"SELECT attempt_count,claim_token FROM ingestion_jobs WHERE id=:id\"),{'id':"+repr(second['job_id'])+"}).one(); "
"n=c.execute(text(\"SELECT count(*) FROM document_chunks WHERE document_id=:id\"),{'id':"+repr(second['document_id'])+"}).scalar_one(); "
"print(json.dumps({'attempts':r[0],'claim_changed':str(r[1])!="+repr(old)+",'chunks':n})); c.close(); e.dispose()"))
assert summary['attempts']==2 and summary['chunks']==1 and summary['claim_changed']
record('killed_worker_lease_reclaim_and_duplicate_free_publication',started,
document_id=second['document_id'],job_id=second['job_id'],**summary)
# Synthetic fixture approval exercises transport only; it is never
# presented as a human decision on the approved real originals.
from tests.support.formats import docx_bytes
started=time.monotonic()
source=docx_bytes(document=b'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Question: fixture fee?</w:t></w:r></w:p><w:p><w:r><w:t>Answer: 5 percent.</w:t></w:r></w:p></w:body></w:document>')
faq=request(client,'POST','/api/v1/documents',202,files={'file':('fixture-faq.docx',source)},
headers=dict(headers,**{'Idempotency-Key':str(uuid4())})).json()
def pending():
value=request(client,'GET','/api/v1/documents/'+faq['document_id']).json()
return value if value['review_required'] else False
wait_for(pending)
evidence=request(client,'GET','/api/v1/documents/'+faq['document_id']+'/extraction-review').json()['items'][0]
assert evidence['review_kind']=='factual_corpus'
decision=dict(evidence_sha256=evidence['evidence_sha256'],decision='approve',checked=evidence['required_checks'],
note='Synthetic fixture test decision; never a human approval of real originals.',excluded_group_ids=[])
decided=request(client,'POST','/api/v1/documents/'+faq['document_id']+'/extraction-review/decisions',
json=decision,headers=dict(headers,**{'Idempotency-Key':str(uuid4())}))
retry=request(client,'POST','/api/v1/documents/'+faq['document_id']+'/retry',202,
headers=dict(headers,**{'Idempotency-Key':str(uuid4())}))
assert retry.json()['job_id']==faq['job_id']
def faq_ready():
value=request(client,'GET','/api/v1/documents/'+faq['document_id']).json()
return value if value['status']=='ready' else False
assert not wait_for(faq_ready)['is_active']
record('synthetic_factual_review_and_same_job_retry',started,document_id=faq['document_id'],job_id=faq['job_id'],
evidence_sha256=evidence['evidence_sha256'],request_ids=[decided.headers['x-request-id'],retry.headers['x-request-id']],
approval_category='synthetic_fixture_only')
started=time.monotonic()
logout=request(client,'POST','/api/v1/auth/logout',204,headers=headers)
request(client,'GET','/api/v1/me',401)
compose(env_path,'stop','-t','10','api','worker')
exits=[json.loads(line) for line in compose(env_path,'ps','--all','--format','json').splitlines()]
codes={row['Service']:row['ExitCode'] for row in exits if row['Service'] in ('api','worker')}
report['shutdown_exit_codes']=codes
# Uvicorn re-raises SIGTERM after completing lifespan cleanup.
assert codes.get('worker')==0 and codes.get('api') in (0,143), codes
api_logs=compose(env_path,'logs','--no-color','api')
assert 'Application shutdown complete.' in api_logs
record('logout_and_graceful_service_shutdown',started,request_id=logout.headers['x-request-id'],exit_codes=codes)
report['status']='passed'
except Exception as exc:
report['status']='failed'
report['failure_type']=type(exc).__name__
output.write_text(json.dumps(report,indent=2)+'\n')
raise
output.write_text(json.dumps(report,indent=2)+'\n')
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--env-file',type=Path,required=True)
parser.add_argument('--output',type=Path)
mode=parser.add_mutually_exclusive_group(required=True)
mode.add_argument('--prepare',action='store_true')
mode.add_argument('--verify',action='store_true')
args=parser.parse_args()
if args.prepare:
tls=args.env_file.with_name(args.env_file.stem+'-tls')
tls.mkdir(mode=0o700)
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','2',
'-subj','/CN=embedding','-addext','subjectAltName=DNS:embedding,IP:127.0.0.1',
'-keyout',str(tls/'key.pem'),'-out',str(tls/'cert.pem')],
check=True,capture_output=True)
(tls/'key.pem').chmod(0o600)
with args.env_file.open('x') as f:
for key,value in fixture_environment().items():
f.write(key+'='+value+'\n')
args.env_file.chmod(0o600)
else:
if args.output is None or args.output.exists():
parser.error('A new output path is required')
verify(args.env_file.resolve(),args.output)
if __name__=='__main__':
main()