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.
This commit is contained in:
11linear11
2026-10-09 17:44:04 -04:00
parent a73a496c54
commit 42f5b9e854
9 changed files with 760 additions and 5 deletions
+153
View File
@@ -0,0 +1,153 @@
"""Explicitly authorized four-original intake, at most one vision HTTP attempt.
Uses the real API, supported bootstrap/migrations/worker, and isolated storage/DB.
Never approves review, selects documents, calibrates or bypasses voice readiness.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import secrets
import subprocess
import threading
import time
import urllib.request
from uuid import uuid4
import httpx
ROOT=Path(__file__).resolve().parents[1]
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--database-url',required=True)
parser.add_argument('--storage',type=Path,required=True)
parser.add_argument('--output',type=Path,required=True)
parser.add_argument('--allow-provider-calls',action='store_true',required=True)
args=parser.parse_args()
from tests.support.postgres import validated_test_url
validated_test_url(args.database_url)
if args.output.exists() or args.storage.exists():
parser.error('New isolated storage and report paths required')
args.storage.mkdir(parents=True,mode=0o700)
env={**os.environ,'INGEST_DATABASE_URL':args.database_url,
'INGEST_ORIGINAL_DIRECTORY':str(args.storage/'originals'),
'INGEST_EXTRACTION_DIRECTORY':str(args.storage/'extractions'),
'VOICE_PROVIDER':'gemini','COOKIE_SECURE':'false',
'TRUSTED_HOSTS':'["localhost:18081"]', 'TRUSTED_ORIGINS':'["http://localhost:18081"]',
'INGEST_OCR_REVIEW_REQUIRED':'true'}
os.environ.update(env)
from app.modules.documents.settings import IngestionSettings
from app.modules.voice.configuration import VoiceSettings
settings=IngestionSettings(); voice=VoiceSettings()
manifest=json.loads((ROOT/'docs/calibration/phase4-cases.draft.json').read_text())
originals=manifest['originals']
# Verify the approved original identities before any provider work.
for original in originals.values():
assert hashlib.sha256((ROOT/original['path']).read_bytes()).hexdigest()==original['sha256']
report=dict(run_id=str(uuid4()),provider_http_attempt_budget=1,provider_http_attempts=0,
voice_provider=voice.provider,vision_provider=settings.vision_provider,
real_voice_sessions=0,usage='unavailable',billing='unavailable',documents=[],observations=[])
def command(module,*items,input=None):
result=subprocess.run([str(ROOT/'.venv/bin/python'),'-m',module,*items],env=env,
input=input,text=True,capture_output=True,timeout=90,cwd=ROOT)
if result.returncode:
raise RuntimeError('Supported operator command failed: '+module)
return result.stdout
log=(args.storage/'api.log').open('w')
server=None; engine=None
try:
result=subprocess.run([str(ROOT/'.venv/bin/alembic'),'upgrade','head'],env=env,
capture_output=True,text=True,timeout=90,cwd=ROOT)
assert result.returncode==0,'Isolated migration failed'
password=secrets.token_hex(24)
account=json.loads(command('app.bootstrap','--organization-name','Approved originals test',
'--username','bounded-admin','--assistant-name','Acceptance','--instruction','Use authorized evidence.',
'--password-stdin',input=password+'\n'))
report['actor_id']=account['administrator_id']
server=subprocess.Popen([str(ROOT/'.venv/bin/python'),'-m','app.server','--host','127.0.0.1','--port','18081'],
env=env,cwd=ROOT,stdout=log,stderr=log)
with httpx.Client(base_url='http://localhost:18081',timeout=15) as client:
deadline=time.monotonic()+40
while True:
try:
if client.get('/health/ready').status_code==200:break
except httpx.HTTPError:pass
if time.monotonic()>deadline:raise TimeoutError('API readiness deadline')
time.sleep(.25)
login=client.post('/api/v1/auth/login',json=dict(username='bounded-admin',password=password),headers={'Origin':'http://localhost:18081'})
assert login.status_code==200
headers={'Origin':'http://localhost:18081','X-CSRF-Token':login.json()['csrf_token']}
from app.infrastructure.database import create_database
from app.api.v1.documents import get_document_services
from app.modules.documents.worker import Worker
from app.worker import factories
engine=create_database(args.database_url)
services=get_document_services(engine,settings)
extractor,embedding=factories(settings)
# One shared guard at the actual HTTP opener. Includes failed attempts;
# no automatic retries or additional vision/embedding requests allowed.
original_opener=urllib.request.build_opener; lock=threading.Lock()
def guarded_opener(*handlers):
opener=original_opener(*handlers); real_open=opener.open
def once(*a,**kw):
with lock:
if report['provider_http_attempts']>=1:
raise ValueError('Acceptance HTTP budget exhausted')
report['provider_http_attempts']+=1
return real_open(*a,**kw)
opener.open=once
return opener
urllib.request.build_opener=guarded_opener
worker=Worker(services.worker,services.store,services.candidates,extractor,embedding,settings)
# Process DOCX first (factual review), then the one-image OCR job.
# PDFs are only uploaded: no accidental per-page paid loop.
ordered=sorted(originals.items(),key=lambda kv: {'.docx':0,'.jpg':1,'.pdf':2}.get(Path(kv[1]['path']).suffix,3))
for name,original in ordered:
path=ROOT/original['path']; rid=str(uuid4()); started=time.monotonic()
with path.open('rb') as source:
response=client.post('/api/v1/documents',files={'file':(path.name,source)},
headers=dict(headers,**{'Idempotency-Key':str(uuid4()),'X-Request-ID':rid}))
assert response.status_code==202,(name,response.status_code)
document=response.json()['document_id']
item=dict(original=name,original_sha256=original['sha256'],document_id=document,
job_id=response.json()['job_id'],request_id=rid)
if path.suffix in ('.docx','.jpg'):
# A single eligible job, no poll loop or retry command.
worker.run_once('bounded-approved-input')
state=client.get('/api/v1/documents/'+document).json()
item.update(status=state['status'],review_required=state['review_required'],
review_state=state['review_state'],job_error=state['job']['error'],
searchable=state['searchable'],elapsed_seconds=time.monotonic()-started)
report['documents'].append(item)
if state['review_required']:
review=client.get('/api/v1/documents/'+document+'/extraction-review').json()
# Store safe digests/check names, never extracted bodies or fabricated decisions.
item['pending_reviews']=[dict(evidence_sha256=x['evidence_sha256'],review_kind=x['review_kind'],
required_checks=x['required_checks']) for x in review['items']]
args.output.write_text(json.dumps(report,indent=2)+'\n')
time.sleep(1)
rid=str(uuid4())
conversation=client.post('/api/v1/conversations',json={'client_request_id':str(uuid4())},headers=headers)
assert conversation.status_code==201
reservation=client.post('/api/v1/voice/sessions',json=dict(conversation_id=conversation.json()['id'],client_request_id=str(uuid4())),
headers=dict(headers,**{'X-Request-ID':rid}))
assert reservation.status_code==503
report['observations'].append(dict(scenario='selected_gemini_http_voice_preflight',status='blocked',
request_id=rid,conversation_id=conversation.json()['id'],error_code=reservation.json()['error']['code'],
voice_provider_calls=0,reason='No finalized measured calibration; no human-approved selected corpus.'))
report['status']='completed_bounded_intake_quality_blocked'
finally:
if server is not None:
server.terminate()
try:report['api_exit_code']=server.wait(timeout=15)
except subprocess.TimeoutExpired:
server.kill();server.wait();report['api_exit_code']='forced'
log.close()
if engine is not None:engine.dispose()
args.output.write_text(json.dumps(report,indent=2)+'\n')
if __name__=='__main__':main()
+281
View File
@@ -0,0 +1,281 @@
"""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()
+61
View File
@@ -0,0 +1,61 @@
# Isolated, provider-free operational acceptance; never reads the deployment .env.
services:
db:
image: pgvector/pgvector:pg16
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: fixture
POSTGRES_DB: rag_ops_test
ports: ["127.0.0.1:55459:5432"]
networks: [default, access]
volumes: ["database:/var/lib/postgresql/data"]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d rag_ops_test"]
interval: 2s
timeout: 2s
retries: 30
migrations:
image: rag-phase4-operational:verified
build:
context: ../..
dockerfile: Dockerfile
env_file: ["${ACCEPTANCE_ENV_FILE:?Supply the isolated fixture env file}"]
command: alembic upgrade head
depends_on:
db: {condition: service_healthy}
api:
image: rag-phase4-operational:verified
env_file: ["${ACCEPTANCE_ENV_FILE:?Supply the isolated fixture env file}"]
command: python -m app.server --host 0.0.0.0 --port 8000
ports: ["127.0.0.1:18080:8000"]
networks: [default, access]
volumes:
- originals:/app/data/originals
- extractions:/app/data/extractions
- ${ACCEPTANCE_TLS_DIRECTORY:?Supply fixture TLS directory}/cert.pem:/fixtures/ca.pem:ro
depends_on:
migrations: {condition: service_completed_successfully}
worker:
image: rag-phase4-operational:verified
env_file: ["${ACCEPTANCE_ENV_FILE:?Supply the isolated fixture env file}"]
command: python -m app.worker
volumes:
- originals:/app/data/originals
- extractions:/app/data/extractions
- ${ACCEPTANCE_TLS_DIRECTORY:?Supply fixture TLS directory}/cert.pem:/fixtures/ca.pem:ro
depends_on:
migrations: {condition: service_completed_successfully}
embedding:
image: rag-phase4-operational:verified
command: python /fixtures/phase4_embedding_fixture.py
volumes:
- ./phase4_embedding_fixture.py:/fixtures/phase4_embedding_fixture.py:ro
- ${ACCEPTANCE_TLS_DIRECTORY:?Supply fixture TLS directory}:/fixtures/tls:ro
volumes:
database:
originals:
extractions:
networks:
default:
internal: true
access: {}
+50
View File
@@ -0,0 +1,50 @@
"""Loopback/internal-network fixture, never a production embedding provider."""
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import ssl
from threading import Event
CALLS = 0
RELEASE = Event()
RELEASE.set()
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass # Never log inputs or Authorization headers.
def reply(self, data):
body = json.dumps(data).encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == '/block':
RELEASE.clear()
elif self.path == '/release':
RELEASE.set()
self.reply({'fixture_calls': CALLS, 'real_provider_calls': 0})
def do_POST(self):
global CALLS
length = int(self.headers.get('Content-Length', '0'))
if self.path != '/v1/embeddings' or not 0 < length <= 1024 * 1024:
self.send_error(400)
return
data = json.loads(self.rfile.read(length))
CALLS += 1
RELEASE.wait(30)
self.reply({'model': data['model'], 'data': [dict(index=i, embedding=[float(1 + n) for n in hashlib.sha256(value.encode()).digest()[:3]])
for i, value in enumerate(data['input'])]})
if __name__ == '__main__':
server=ThreadingHTTPServer(('0.0.0.0', 8090), Handler)
context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/fixtures/tls/cert.pem','/fixtures/tls/key.pem')
server.socket=context.wrap_socket(server.socket,server_side=True)
server.serve_forever()
+29
View File
@@ -0,0 +1,29 @@
"""SIGTERM drains the current fenced job, wakes idle polling and releases DB resources."""
from contextlib import nullcontext
import signal
from types import SimpleNamespace
import pytest
from app import worker
@pytest.mark.parametrize('processed', [False, True])
def test_sigterm_stops_new_claims_and_disposes_engine(settings, monkeypatch, processed):
calls=[]
previous=signal.getsignal(signal.SIGTERM)
engine=SimpleNamespace(connect=lambda: nullcontext(None), dispose=lambda: calls.append('dispose'))
monkeypatch.setattr(worker,'IngestionSettings',lambda: settings)
monkeypatch.setattr(worker,'create_database',lambda _: engine)
monkeypatch.setattr(worker,'check_compatibility',lambda *a,**kw: None)
monkeypatch.setattr(worker,'SqlWorkerRepository',lambda *a: None)
class Active:
def run_once(self, _):
calls.append('claim')
signal.getsignal(signal.SIGTERM)(signal.SIGTERM,None)
calls.append('finished')
return processed
monkeypatch.setattr(worker,'Worker',lambda *a: Active())
assert worker.main([])==0
assert calls==['claim','finished','dispose']
assert signal.getsignal(signal.SIGTERM)==previous