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:
+2
-2
@@ -19,7 +19,7 @@ COPY pyproject.toml /app/
|
||||
|
||||
# Stub package to leverage Docker layer caching for pip dependencies
|
||||
RUN mkdir -p /app/app && touch /app/app/__init__.py \
|
||||
&& pip install --no-cache-dir -e ".[prototype,embedding]"
|
||||
&& pip install --no-cache-dir -e ".[api,voice,embedding]"
|
||||
|
||||
# Copy application source code and migrations
|
||||
COPY app/ /app/app/
|
||||
@@ -34,4 +34,4 @@ RUN pip install --no-deps -e .
|
||||
EXPOSE 8000
|
||||
|
||||
# Default command: FastAPI API server
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
CMD ["python", "-m", "app.server", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
||||
+8
-2
@@ -3,6 +3,7 @@ import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
from threading import Event
|
||||
from uuid import uuid4
|
||||
@@ -62,6 +63,8 @@ def main(argv=None):
|
||||
parser.add_argument("--once", action="store_true", help="Process at most one eligible job")
|
||||
args = parser.parse_args(argv)
|
||||
engine = None
|
||||
stop = Event()
|
||||
previous_sigterm = None
|
||||
handler = logging.StreamHandler(sys.stderr)
|
||||
handler.setFormatter(logging.Formatter("%(message)s"))
|
||||
old_level, old_propagate = worker_logger.level, worker_logger.propagate
|
||||
@@ -79,8 +82,8 @@ def main(argv=None):
|
||||
original_directory=settings.original_directory)
|
||||
worker = Worker(repository, store, candidates, *factories(settings), settings)
|
||||
worker_id = str(os.getpid()) + ":" + uuid4().hex
|
||||
stop = Event()
|
||||
while True:
|
||||
previous_sigterm = signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
while not stop.is_set():
|
||||
try:
|
||||
processed = worker.run_once(worker_id)
|
||||
except Exception:
|
||||
@@ -93,6 +96,7 @@ def main(argv=None):
|
||||
return 0
|
||||
if not processed:
|
||||
stop.wait(settings.poll_seconds)
|
||||
return 0
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
except Exception:
|
||||
@@ -100,6 +104,8 @@ def main(argv=None):
|
||||
"message": "Verify configuration, migration and storage."}}), file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if previous_sigterm is not None:
|
||||
signal.signal(signal.SIGTERM, previous_sigterm)
|
||||
worker_logger.removeHandler(handler)
|
||||
worker_logger.setLevel(old_level)
|
||||
worker_logger.propagate = old_propagate
|
||||
|
||||
+5
-1
@@ -30,6 +30,7 @@ services:
|
||||
environment:
|
||||
- INGEST_DATABASE_URL=postgresql+psycopg://${POSTGRES_USER:-rag}:${POSTGRES_PASSWORD:-rag_password}@db:5432/${POSTGRES_DB:-rag}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://host.docker.internal:11434/v1}
|
||||
- INGEST_OCR_REVIEW_REQUIRED=${INGEST_OCR_REVIEW_REQUIRED:-true}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
depends_on:
|
||||
@@ -42,7 +43,7 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
container_name: rag-api
|
||||
restart: unless-stopped
|
||||
command: uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||
command: python -m app.server --host 0.0.0.0 --port 8000
|
||||
ports:
|
||||
- "${API_PORT:-8080}:8000"
|
||||
env_file:
|
||||
@@ -50,6 +51,7 @@ services:
|
||||
environment:
|
||||
- INGEST_DATABASE_URL=postgresql+psycopg://${POSTGRES_USER:-rag}:${POSTGRES_PASSWORD:-rag_password}@db:5432/${POSTGRES_DB:-rag}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://host.docker.internal:11434/v1}
|
||||
- INGEST_OCR_REVIEW_REQUIRED=${INGEST_OCR_REVIEW_REQUIRED:-true}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
@@ -69,12 +71,14 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
container_name: rag-worker
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 90s
|
||||
command: python -m app.worker
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- INGEST_DATABASE_URL=postgresql+psycopg://${POSTGRES_USER:-rag}:${POSTGRES_PASSWORD:-rag_password}@db:5432/${POSTGRES_DB:-rag}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://host.docker.internal:11434/v1}
|
||||
- INGEST_OCR_REVIEW_REQUIRED=${INGEST_OCR_REVIEW_REQUIRED:-true}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
# Phase 4 backend startup and recovery
|
||||
|
||||
This guide describes the modular document/voice backend. The older prototype
|
||||
chat instructions in README are not its deployment procedure. Provider readiness,
|
||||
measured retrieval quality and actual browser acceptance are separate gates.
|
||||
See the [acceptance report](realtime-agent-phase4-acceptance.md) for executed
|
||||
results, correlations, actual failures and remaining prerequisites.
|
||||
|
||||
## Isolated provider-free deployment verification
|
||||
|
||||
The harness uses the actual Dockerfile, online Alembic migrations, application
|
||||
lifespan, opaque-cookie authentication, HTTP upload/review/retry/selection and
|
||||
worker. It creates one API process, a separate worker, PostgreSQL/pgvector and
|
||||
persistent named original/extraction/database volumes. A deterministic HTTP
|
||||
embedding fixture exercises the real embedding adapter. It certifies operations,
|
||||
never retrieval quality or human approval. Generated fixture decisions are
|
||||
explicitly synthetic and never apply to the four approved originals.
|
||||
|
||||
The API/DB publish only loopback ports 18080/55459. The worker and embedding
|
||||
fixture use only the internal network. API/DB additionally join a bridge for
|
||||
host access; no real keys are supplied and no deployment `.env` is read. The
|
||||
fixture embedding profile is intentionally separate from the frozen real profile.
|
||||
Never repoint the harness at an existing database, reuse its fixture account in
|
||||
production, or replace an operational profile with this fixture profile.
|
||||
The fixture uses HTTPS with a generated two-day certificate and a test-only
|
||||
trusted CA; normal hostname/certificate verification stays enabled. This internal
|
||||
fixture TLS does not certify public HTTPS/WSS deployment.
|
||||
|
||||
From repository root, with Docker, OpenSSL and the existing `.venv`:
|
||||
|
||||
```sh
|
||||
.venv/bin/python -m tests.phase4_operations --prepare --env-file /tmp/rag-phase4-ops.env
|
||||
export ACCEPTANCE_ENV_FILE=/tmp/rag-phase4-ops.env
|
||||
export ACCEPTANCE_TLS_DIRECTORY=/tmp/rag-phase4-ops-tls
|
||||
docker compose -p rag-phase4-ops -f tests/support/phase4-compose.yml build migrations
|
||||
docker compose -p rag-phase4-ops -f tests/support/phase4-compose.yml up -d db embedding migrations api worker
|
||||
.venv/bin/python -m tests.phase4_operations --verify --env-file /tmp/rag-phase4-ops.env --output /tmp/phase4-operations.json
|
||||
docker compose -p rag-phase4-ops -f tests/support/phase4-compose.yml down
|
||||
```
|
||||
|
||||
Use unused ports/project names or stop on a collision; do not stop existing
|
||||
services to make room. `--prepare` and `--verify` require new file paths. Verify
|
||||
requires an empty fixture organization/database, so a complete second run needs
|
||||
a new isolated database/project or removal of only this harness's volumes after
|
||||
retaining its evidence. `down` preserves named volumes. Service recreation within
|
||||
the verification run must preserve them. Never use `down -v` on an operational
|
||||
project; removing task-owned volumes after acceptance is test cleanup only.
|
||||
|
||||
Timing uses monotonic clocks: scenario elapsed time includes the actions named
|
||||
in the scenario, polling and service recreation. It is not per-turn speech or
|
||||
search latency. Reports include real HTTP request IDs, actor/document/job/live
|
||||
IDs, terminal outcomes, fixture-call counts and zero real-provider calls. They
|
||||
omit passwords, cookies, CSRF and provider tokens, source bodies and audio.
|
||||
|
||||
## Operational configuration and startup
|
||||
|
||||
Install `.[api,voice,embedding]` for this backend, or build the repository Dockerfile.
|
||||
Set the actual frozen embedding provider/endpoint/model/dimension/preprocessing
|
||||
and request limits, `INGEST_DATABASE_URL`, and durable original/extraction paths.
|
||||
Configured endpoint/model request limits must be established before real embedding
|
||||
work; do not invent limits or change a persisted profile to bypass validation.
|
||||
Verify the canonical embedding endpoint is reachable from each actual API/worker
|
||||
process. Host `localhost:11434` is not container localhost. A host Ollama inventory
|
||||
probe alone cannot establish container reachability. Preserve the frozen endpoint
|
||||
identity when choosing the deployment topology; do not silently rewrite profiles
|
||||
or database comments to switch to a different host address.
|
||||
Configure `VOICE_PROVIDER=gemini` for the temporary Gemini selection and the
|
||||
corresponding server-side key/model/voice. OpenAI remains selectable with its
|
||||
separate key/profile and no automatic fallback. A key is not call authorization.
|
||||
|
||||
Authentication has **no session-secret setting**. It generates random opaque
|
||||
tokens, stores token hashes in PostgreSQL and derives CSRF with HMAC keyed by the
|
||||
session token. Provision enabled accounts through `app.bootstrap` / `app.provision`;
|
||||
do not manually mint cookies or put provider keys in the frontend.
|
||||
|
||||
For loopback direct HTTP on 8080:
|
||||
|
||||
```dotenv
|
||||
TRUSTED_HOSTS=["localhost:8080","127.0.0.1:8080"]
|
||||
TRUSTED_ORIGINS=["http://localhost:8080","http://127.0.0.1:8080"]
|
||||
COOKIE_SECURE=false
|
||||
INGEST_OCR_REVIEW_REQUIRED=true
|
||||
```
|
||||
|
||||
For the developer UI proxy, also configure its exact Host/Origin as explained in
|
||||
the [connection handoff](frontend-backend-connection-handoff.md). Use Secure
|
||||
cookies and explicit HTTPS Origin/Host in deployment. The API process must use
|
||||
`app.server`, which selects the bounded parser; generic Uvicorn defaults are not
|
||||
the supported voice transport admission path.
|
||||
|
||||
```sh
|
||||
alembic upgrade head
|
||||
python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from authorized documents."
|
||||
python -m app.provision --username acceptance-user --role user
|
||||
python -m app.server --host 0.0.0.0 --port 8080
|
||||
# Separate process, only against an approved queue and within ingestion budget:
|
||||
python -m app.worker
|
||||
```
|
||||
|
||||
Password commands prompt securely; automation can use `--password-stdin` from a
|
||||
secure pipe. Bootstrap is only for a new installation and refuses to reset an
|
||||
existing organization. Never downgrade or edit applied migrations 0001–0005.
|
||||
|
||||
Existing production Compose starts migrations before one API and the separate
|
||||
worker, with shared durable original/extraction directories. Build with
|
||||
`docker compose build`; start DB/migrations/API explicitly while ingestion
|
||||
authorization is absent. Start `worker` only once its queue and call budget are
|
||||
approved. The worker itself has no budget CLI: `--once` caps jobs, not provider
|
||||
requests; one PDF can require multiple paid calls. Do not use it as a call cap.
|
||||
|
||||
`/health/live` checks process transport and `/health/ready` checks the lifespan
|
||||
readiness flag after reconciliation. They never call providers. Database-ready
|
||||
HTTP may be usable while `capabilities.voice=false` / `CALIBRATION_REQUIRED`
|
||||
correctly prevents an ungrounded voice session.
|
||||
|
||||
## Shutdown and recovery
|
||||
|
||||
SIGTERM tells the worker to stop claiming new jobs and wakes idle polling. An
|
||||
already owned job completes through the existing claim/heartbeat/fencing path;
|
||||
the worker then disposes its database engine. Production Compose allows 90 seconds
|
||||
for this drain. If a long job exceeds the grace period, forced termination is
|
||||
recovered by lease expiry/reclaim; never manually publish partial chunks or reset
|
||||
claim tokens. The harness kills a blocked fixture embedding request and verifies
|
||||
a second fenced attempt publishes one complete chunk, with no duplicate.
|
||||
|
||||
The API completes application lifespan cleanup on shutdown. Uvicorn may then
|
||||
re-raise SIGTERM (container exit 143 / subprocess -15); that alone is not a cleanup
|
||||
failure. Require the shutdown-complete evidence and reject a forced SIGKILL.
|
||||
On recreation, startup reconciliation marks abandoned live sessions/tools failed
|
||||
before readiness. Reauthenticate as needed and create a new voice session. Resolve
|
||||
ambiguous create/upload/review/retry results by replaying the retained key/payload;
|
||||
do not silently reconnect or switch providers.
|
||||
|
||||
Ready documents remain inactive until explicit K02 selection. Complete genuine
|
||||
pending extraction decisions and independent factual approval before same-job
|
||||
retry. OCR policy defaults true and is frozen per job; false does not waive
|
||||
factual or legacy review. Do not invent human checks, calibrate against held-out
|
||||
questions, or rewrite originals to make failed acceptance pass.
|
||||
|
||||
## Remaining frontend and deployment checks
|
||||
|
||||
The frontend developer must execute these through the actual UI with approved
|
||||
accounts/corpus and separately bounded provider authorization:
|
||||
|
||||
- Login/reload/logout, safe errors and request ID display; server permissions,
|
||||
trusted Origin/Host, cookie and CSRF behavior.
|
||||
- Upload uncertainty/replay, polling cancellation, review evidence/preview and
|
||||
genuine decisions; explicit same-job retry and complete-set selection conflicts.
|
||||
- Persian speech recognition, audible playback, transcripts and source display;
|
||||
factual questions, follow-ups, topic changes, ambiguity and unsupported evidence.
|
||||
- Microphone/worklet ownership, actual played-sample progress, interruption during
|
||||
search/playback, provider loss, logout/revocation and API restart recovery.
|
||||
- Confirm the UI has no provider selector, secrets or automatic approval/retry.
|
||||
|
||||
HTTPS/WSS deployment needs an authorized endpoint, domain/certificate, reverse
|
||||
proxy upgrade/timeouts, exact Origin/Host, Secure cookies and durable volumes.
|
||||
Run external browser TLS/WSS, disconnect, audio and recovery checks there.
|
||||
Missing TLS infrastructure is a deployment prerequisite, not a UI dependency.
|
||||
|
||||
|
||||
Explicit uncalibrated connectivity testing: set `VOICE_TRANSPORT_TESTING=true`
|
||||
and restart the API. Configure a compatible embedding adapter, credentials and
|
||||
bounded request limits first. Pending/missing calibration then permits voice
|
||||
reservation and provider streaming; create/recovery/poll report
|
||||
`calibration_status: "uncalibrated"`. F01 also reports the policy and calibration
|
||||
status. Treat this as connectivity testing: shared search still returns
|
||||
`CALIBRATION_REQUIRED` with no sources. Disable the policy for strict admission;
|
||||
existing reservations remain pinned and may require a new session after policy or
|
||||
calibration changes. No automatic provider switch, calibration or paid call occurs
|
||||
when enabling the policy. Existing client examples tolerate the additive metadata;
|
||||
the actual developer UI should display the status.
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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: {}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user