Files
rag-technical-docs-assistant/app/voice_smoke.py
T
11linear11 a73a496c54 feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
2026-10-09 17:43:52 -04:00

168 lines
8.3 KiB
Python

"""Operator-only diagnostic selected-provider/search smoke; no HTTP/text-chat route."""
import argparse
import asyncio
from dataclasses import asdict
import json
from pathlib import Path
import sys
from uuid import UUID
from sqlalchemy import text
from app.infrastructure.database import create_database, check_compatibility
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.langchain_tool import SearchToolRunner
from app.modules.knowledge.service import SearchService, authority, transaction
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json
from app.modules.voice.configuration import VoiceSettings
from app.infrastructure.voice_provider import create_adapter
def preflight(engine, settings, actor, cutoff):
if cutoff.profile != asdict(settings.embedding_profile):
raise ValueError("Calibration profile mismatch")
with transaction(engine) as conn:
current, _ = authority(conn, actor)
check_compatibility(conn, settings.embedding_profile, require_worker=True)
count = conn.execute(text("""
SELECT count(*) FROM documents WHERE organization_id=:org
AND status='ready' AND is_active AND deleted_at IS NULL
AND content_purged_at IS NULL
AND processing_profile->'embedding'=CAST(:profile AS jsonb)
"""), dict(org=current["organization_id"],
profile=json.dumps(cutoff.profile))).scalar_one()
if not count:
raise ValueError("Eligible selected documents required")
async def run(service, runner, actor, config, query, seconds, max_calls):
try:
limits = getattr(config, "runtime_settings", None) or RuntimeSettings()
if (not isinstance(limits, RuntimeSettings) or type(seconds) not in (int, float)
or not 0 < seconds <= 600 or type(max_calls) is not int
or not 1 <= max_calls <= min(10, limits.max_tool_calls)
or not isinstance(query, str) or not query.strip() or len(query) > 2000):
raise ValueError("Invalid smoke bounds")
async with asyncio.timeout(seconds):
return await _run(service, runner, actor, config, query, max_calls, limits)
except TimeoutError:
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
return 1
async def _run(service, runner, actor, config, query, max_calls, limits):
adapter = await create_adapter(config, limits)
async def emit(event):
if isinstance(event, bytes):
return # No playback assertion: diagnostic smoke never claims heard audio.
print(bounded_json(event, limits.max_server_event_bytes), flush=True)
runtime = VoiceRuntime(adapter,
service, runner, actor, emit, max_calls=max_calls,
settings=limits)
receiver = None
try:
await runtime.start()
receiver = asyncio.create_task(runtime.receive_loop())
while not runtime.ready and runtime.usable:
await asyncio.sleep(.01)
if not runtime.usable:
return 1
turn_ref = await runtime.diagnostic_text(query)
while runtime.usable:
await asyncio.sleep(.01)
async with runtime.lock:
if not runtime.check_deadlines():
return 1
current = runtime.current
if current is None or current.ref != turn_ref or current.superseded:
return 1
responses = [r for r in runtime.responses.values() if r.turn is current]
answer = responses[-1] if responses else None
if answer is None or not answer.terminal or answer.calls:
continue
if answer.status != "completed" or answer.interrupted:
return 1
if not answer.transcript_delivered:
continue
actual = [(cid, r, c) for cid, (r, c) in runtime.calls.items()
if r.turn is current]
if (not actual or any(not c["sent"] or c["result"] is None or
not r.terminal or r.status not in ("completed", "waiting_tools") or r.interrupted
for _, r, c in actual)):
continue
chain, cursor = set(), answer
while cursor.parent_response is not None:
chain.add(cursor.parent_response)
cursor = runtime.responses[cursor.parent_response]
if any(r.id not in chain for _, r, _ in actual):
return 1
report = dict(type="smoke_correlation", turn_ref=turn_ref,
final_response_id=answer.id, transcript_delivered=True,
calls=[dict(call_id=cid, response_id=r.id,
continuation_response_id=next(child.id for child in responses
if child.parent_response == r.id),
status=c["result"]["status"],
sources=[{k: s[k] for k in ("source_ref", "document_id", "chunk_id")}
for s in c["result"]["sources"]]) for cid, r, c in actual],
audio_playback_verified=False)
print(json.dumps(report, ensure_ascii=True), flush=True)
return 0 if all(c["result"]["status"] != "error" for _, _, c in actual) else 1
return 1
except TimeoutError:
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
return 1
finally:
if receiver:
receiver.cancel()
await asyncio.gather(receiver, return_exceptions=True)
await runtime.close()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--query", required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize the selected voice provider plus up to --max-tool-calls query embeddings")
parser.add_argument("--seconds", type=int, choices=range(1, 601), default=90, metavar="1..600")
parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10")
args = parser.parse_args(argv)
engine = runner = None
try:
# Validate everything before opening the provider connection.
if not args.query.strip() or len(args.query) > 2000:
raise ValueError("Bounded query required")
settings, config = IngestionSettings(), VoiceSettings()
config.require_voice()
if config.search_calibration_report is None:
raise ValueError('CALIBRATION_REQUIRED')
cutoff = load_cutoff(json.loads(config.search_calibration_report.read_text(encoding="utf-8")))
if settings.embedding_timeout_seconds > 75:
raise ValueError("Smoke embedding timeout must not exceed 75 seconds")
from sqlalchemy.engine import make_url
url = make_url(settings.database_url.get_secret_value())
options = url.query.get("options", "") + " -c statement_timeout=5000 -c lock_timeout=5000"
url = url.update_query_dict(dict(connect_timeout="5", options=options))
engine = create_database(url.render_as_string(hide_password=False))
preflight(engine, settings, args.user_id, cutoff)
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
service = SearchService(engine, settings, provider, counter, cutoff=cutoff)
runner = SearchToolRunner()
return asyncio.run(run(service, runner, args.user_id, config, args.query,
args.seconds, args.max_tool_calls))
except Exception:
print(json.dumps(dict(error=dict(code="SMOKE_FAILED",
message="Verify actor, database/profile, measured calibration, provider access and configuration"))),
file=sys.stderr)
return 1
finally:
if runner:
runner.close()
if engine:
engine.dispose()
if __name__ == "__main__":
sys.exit(main())