"""Bounded typed execution over existing providers, without research side effects.""" from __future__ import annotations import asyncio import concurrent.futures import contextvars import os from contextlib import suppress import threading import time from datetime import datetime, timezone from fastapi import APIRouter, HTTPException, Response, Request from pydantic import Field, ValidationError from src.inference_service import execution_deadline, execution_provider_budget from src.language_contract import clarify_result, reply_result, translate_result from src.hf_agent_workflow import MODE, run_workflow, Coordinator from src.stage0_contracts import AgentResult, StrictModel, TaskEnvelope _POOL = concurrent.futures.ThreadPoolExecutor(max_workers=2, thread_name_prefix="typed-inference") _SLOTS = threading.BoundedSemaphore(4) _VERSION = "1.0.0" _CAPABILITIES = ("translate.v1", "interpret.compat.v1", "reply.v1") def hf_workflow_tenants(): allowed = {"pureversation"} selected = {value.strip() for value in os.getenv("PURE_HF_WORKFLOW_TENANTS", ",".join(sorted(allowed))).split(",") if value.strip()} if not selected <= allowed: raise ValueError("PURE_HF_WORKFLOW_TENANTS contains an unenrolled platform.") return selected async def _observe_disconnect(request, cancelled, future): while not future.done(): if await request.is_disconnected(): cancelled.set() future.cancel() return await asyncio.sleep(0.05) class TextPayload(StrictModel): text: str = Field(min_length=1, max_length=4000) source_language: str = Field(min_length=1, max_length=120) source_dialect: str = Field(min_length=1, max_length=120) model_choice: str = Field(default="auto", min_length=1, max_length=128) class TranslationPayload(TextPayload): target_language: str = Field(min_length=1, max_length=120) target_dialect: str = Field(min_length=1, max_length=120) class ReplyPayload(TranslationPayload): reviewed_meaning: str = Field(min_length=1, max_length=4000) def create_execution_router(*, system_id, tenant_id, app_id, route_prefix="/api/agent/v1", _workflow=False): if _workflow and (tenant_id, app_id) not in {("purepolyglot", "PurePolyglot"), ("purekitchat", "PureKITchat"), ("purebilingual", "PureBilingual"), ("pacycx", "PACYCx"), ("pureversation", "PureVersation")}: raise ValueError("HF workflow is not enrolled for this application.") identity = {"system_id": system_id, "tenant_id": tenant_id, "app_id": app_id} router = APIRouter(prefix=route_prefix, tags=["typed-compatibility"]) @router.get("/runtime/status") async def status(response: Response): response.headers["Cache-Control"] = "no-store" result = { **identity, "execution_version": _VERSION, "mode": "bounded-typed-compatibility", "capabilities": list(_CAPABILITIES), "autonomous_agents_deployed": False, "distributed_runtime_enabled": False, "research_writes": False, "training_enabled": False, "chain_writes": False, "durable_idempotency": False, "max_workers": 2, "max_outstanding": 4, "cost_accounting": "unavailable", "confidence": None, } if _workflow: result.update(execution_version="2.0.0", mode=MODE, bounded_agent_workflow_enabled=True, agents=["coordinator", "interpreter", "critic"], postgres_required=False, nats_required=False, persistence="request-scoped", restart_recovery="explicit-client-retry", max_agent_steps=5, max_provider_requests=3, semantic_accuracy_verified=False, dataset_publication_enabled=False) return result @router.post("/execute", response_model=AgentResult) async def execute(task: TaskEnvelope, response: Response, request: Request): response.headers["Cache-Control"] = "no-store" if any(getattr(task, key) != value for key, value in identity.items()): raise HTTPException(409, "Task identity does not match this execution route.") if task.capability not in _CAPABILITIES: raise HTTPException(422, "This route executes text inference only.") if task.artifacts or task.constraints.allowed_tools or task.constraints.human_gates: raise HTTPException(422, "Artifacts, external tools and human-gate actions are not supported here.") if task.constraints.max_cost_usd is not None: raise HTTPException(422, "A monetary budget cannot be attested by this provider adapter.") now = datetime.now(timezone.utc) if (task.created_at - now).total_seconds() > 300: raise HTTPException(422, "Task creation time is in the future.") remaining = min(30.0, task.constraints.max_latency_ms / 1000) if task.deadline: remaining = min(remaining, (task.deadline - now).total_seconds()) if remaining <= 0: raise HTTPException(408, "Task deadline has expired.") model = {"translate.v1": TranslationPayload, "interpret.compat.v1": TextPayload, "reply.v1": ReplyPayload}[task.capability] try: payload = model.model_validate(task.payload) if _workflow: Coordinator().plan(task.capability, payload.model_dump(), task.constraints.max_steps) except ValidationError: raise HTTPException(422, "Payload does not match this text capability.") from None except ValueError: raise HTTPException(422, "Choose complete language labels and allow at least three workflow steps.") from None if not _SLOTS.acquire(blocking=False): raise HTTPException(429, "Inference is at capacity. Retry shortly.") started = time.monotonic() deadline = started + remaining cancelled = threading.Event() def provider(capability, value, feedback=()): options = {"review_feedback": feedback} if feedback else {} if capability == "translate.v1": return translate_result(value["text"], value["source_language"], value["source_dialect"], value["target_language"], value["target_dialect"], value["model_choice"], **options) if capability == "reply.v1": return reply_result(value["text"], value["reviewed_meaning"], value["source_language"], value["source_dialect"], value["target_language"], value["target_dialect"], value["model_choice"], **options) return clarify_result(value["text"], value["source_language"], value["source_dialect"], value["model_choice"], **options) def invoke(): token = execution_deadline.set(deadline) budget = {"limit": 3, "used": 0} budget_token = execution_provider_budget.set(budget if _workflow else None) try: if time.monotonic() >= deadline: return {"ok": False, "error": {"code": "DEADLINE_EXCEEDED"}} if _workflow: result = run_workflow(task.capability, payload.model_dump(), raw_payload=task.payload, max_steps=min(5, task.constraints.max_steps), deadline=deadline, cancelled=cancelled, provider=provider) if "workflow" in result: result["workflow"]["provider_requests"] = budget["used"] return result return provider(task.capability, payload.model_dump()) finally: execution_provider_budget.reset(budget_token) execution_deadline.reset(token) try: context = contextvars.copy_context() future = _POOL.submit(context.run, invoke) except BaseException: _SLOTS.release() raise # Capacity is released by actual completion, not an HTTP timeout. future.add_done_callback(lambda _: _SLOTS.release()) observer = asyncio.create_task(_observe_disconnect(request, cancelled, future)) if _workflow else None try: result = await asyncio.wait_for(asyncio.wrap_future(future), timeout=max(0.001, deadline - time.monotonic())) except (TimeoutError, asyncio.TimeoutError): cancelled.set() future.cancel() raise HTTPException(504, "Inference deadline exceeded; no output was accepted.") from None except asyncio.CancelledError: cancelled.set() future.cancel() raise except Exception: raise HTTPException(503, "Inference unavailable; no output was accepted.") from None finally: if observer: observer.cancel() with suppress(asyncio.CancelledError): await observer if _workflow and isinstance(result, dict) and result.get("escalated") is True: return AgentResult(task_id=task.task_id, agent_id="agent_hf_workflow", agent_version="2.0.0", status="escalated", action=task.capability, reason_codes=["HUMAN_REVIEW_REQUIRED"], output={"ok": False, "identity": identity, "execution_mode": MODE, "workflow": result["workflow"], "error": result["error"]}, latency_ms=round((time.monotonic() - started) * 1000)) if not isinstance(result, dict) or result.get("ok") is not True: error = result.get("error", {}) if isinstance(result, dict) else {} code = str(error.get("code", "INFERENCE_UNAVAILABLE")) raise HTTPException(422 if code.startswith("INVALID_") else 503, {"code": code, "message": "Inference did not produce a verified result."}) if not all(isinstance(result.get(key), str) and result[key].strip() for key in ("text", "model", "route")): raise HTTPException(502, "Provider returned an incomplete result.") return AgentResult( task_id=task.task_id, agent_id="agent_hf_workflow" if _workflow else "agent_compatibility", agent_version="2.0.0" if _workflow else _VERSION, status="completed", action=task.capability, reason_codes=["HF_BOUNDED_AGENT_WORKFLOW" if _workflow else "EXISTING_PROVIDER_ADAPTER", "HUMAN_REVIEW_REQUIRED"], output={**result, "identity": identity, "execution_mode": MODE if _workflow else "bounded-typed-compatibility"}, model_id=result["model"], latency_ms=round((time.monotonic() - started) * 1000), ) return router def create_hf_workflow_router(*, system_id, tenant_id, app_id, route_prefix="/api/agent/v1"): return create_execution_router(system_id=system_id, tenant_id=tenant_id, app_id=app_id, route_prefix=route_prefix.replace("/v1", "/v2", 1), _workflow=True)