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:
@@ -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()
|
||||
Reference in New Issue
Block a user