Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
1771 lines
70 KiB
Python
1771 lines
70 KiB
Python
"""Durable routing, failover, execution, polling, and exact-cost readback."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import tempfile
|
|
import threading
|
|
from dataclasses import asdict, dataclass, field, replace
|
|
from pathlib import Path
|
|
from typing import Any, Protocol
|
|
from uuid import uuid4
|
|
|
|
from app.domains.gateway.media_catalog import get_model, list_models
|
|
from app.domains.routing.policy import Candidate, RoutePolicy, select_route
|
|
from reelforge_provider_adapter.execution import (
|
|
ProviderHandleV1,
|
|
ProviderRequestV1,
|
|
ProviderResultV1,
|
|
should_fail_over,
|
|
)
|
|
|
|
from .auth import Principal
|
|
from .limits import SpendLedger
|
|
from .models import (
|
|
Attempt,
|
|
GenerationRequest,
|
|
GenerationResponse,
|
|
GenerationSettlement,
|
|
ModelResponse,
|
|
SettlementReceipt,
|
|
)
|
|
from .settlement import (
|
|
HoldAuthorization,
|
|
MintSettlementClient,
|
|
MintSettlementError,
|
|
SettlementCommand,
|
|
SettlementPort,
|
|
)
|
|
|
|
|
|
# Modalities Prism routes through the media catalog + provider execution boundary.
|
|
# Image and video have always been routable; audio (music/voice) is served by the
|
|
# same durable submit/poll/settlement pipeline via the catalog's audio models.
|
|
_ROUTABLE_MODALITIES = frozenset({"image", "video", "audio"})
|
|
# Modalities whose cost is metered per second and therefore consume the request's
|
|
# ``duration_seconds`` (clamped to the model's ``max_seconds``). Image and audio
|
|
# are billed per unit (one image / one clip), so they ignore duration.
|
|
_DURATION_MODALITIES = frozenset({"video"})
|
|
# Public generation lifecycle states accepted by the owner-scoped list filter.
|
|
_GENERATION_STATUSES = frozenset({"queued", "running", "completed", "failed"})
|
|
# Upper bound on one history page so a list call stays a cheap indexed read.
|
|
_MAX_LIST_LIMIT = 200
|
|
|
|
|
|
class PrismError(Exception):
|
|
def __init__(self, message: str, status_code: int = 400) -> None:
|
|
super().__init__(message)
|
|
self.status_code = status_code
|
|
|
|
|
|
class ExecutionNotAccepted(Exception):
|
|
"""A provider explicitly rejected a request before creating any work.
|
|
|
|
This is the only executor failure that may authorize equivalent-provider
|
|
fallback. Ambiguous transport failures, auth failures, validation failures,
|
|
and failures involving a caller-supplied provider key must stop immediately.
|
|
"""
|
|
|
|
|
|
class ExecutionBlocked(Exception):
|
|
"""A typed provider failure that must not authorize fallback."""
|
|
|
|
def __init__(self, message: str, acceptance: str) -> None:
|
|
self.acceptance = acceptance
|
|
super().__init__(message)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ExecutionOutcome:
|
|
status: str
|
|
output_url: str = ""
|
|
cost_micros: int | None = None
|
|
provider_ref: str = ""
|
|
status_url: str = ""
|
|
response_url: str = ""
|
|
error: str = ""
|
|
provider_handle: dict[str, Any] = field(default_factory=dict)
|
|
credential_mode: str = ""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GenerationIntent:
|
|
request_hash: str
|
|
generation_id: str = ""
|
|
|
|
|
|
class MediaExecutor(Protocol):
|
|
def execute(
|
|
self,
|
|
candidate: Candidate,
|
|
request: GenerationRequest,
|
|
principal: Principal,
|
|
correlation_id: str,
|
|
) -> ExecutionOutcome: ...
|
|
|
|
|
|
class GenerationStorePort(Protocol):
|
|
"""Durable owner-scoped storage boundary for provider execution handles."""
|
|
|
|
def put(
|
|
self, owner: str, record: GenerationResponse, handle: ExecutionOutcome
|
|
) -> GenerationResponse: ...
|
|
|
|
def get(
|
|
self, owner: str, generation_id: str
|
|
) -> tuple[GenerationResponse, ExecutionOutcome] | None: ...
|
|
|
|
def reserve_intent(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
request_json: str,
|
|
) -> tuple[GenerationIntent, bool]: ...
|
|
|
|
def get_by_correlation(
|
|
self, owner: str, correlation_id: str
|
|
) -> tuple[GenerationResponse, ExecutionOutcome] | None: ...
|
|
|
|
def release_intent_if_unbound(
|
|
self, owner: str, correlation_id: str, request_hash: str
|
|
) -> None: ...
|
|
|
|
def get_settlement(
|
|
self, owner: str, correlation_id: str
|
|
) -> SettlementCommand | None: ...
|
|
|
|
def bind_settlement(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
command: SettlementCommand,
|
|
) -> SettlementCommand: ...
|
|
|
|
def update_settlement(
|
|
self, owner: str, correlation_id: str, command: SettlementCommand
|
|
) -> SettlementCommand: ...
|
|
|
|
def begin_submission(
|
|
self, owner: str, correlation_id: str
|
|
) -> SettlementCommand: ...
|
|
|
|
def list(
|
|
self, owner: str, limit: int, status: str | None = None
|
|
) -> list[GenerationResponse]: ...
|
|
|
|
|
|
class AdapterExecutor:
|
|
"""Execute only through Menivor's public, typed provider boundary."""
|
|
|
|
@staticmethod
|
|
def _provider_executor(api_key: str = ""):
|
|
from app.domains.gateway.provider_execution import MediaProviderExecutor
|
|
|
|
return MediaProviderExecutor(api_key=api_key)
|
|
|
|
@staticmethod
|
|
def _outcome(
|
|
result: ProviderResultV1,
|
|
fallback_cost: int,
|
|
*,
|
|
credential_mode: str = "service",
|
|
) -> ExecutionOutcome:
|
|
public_status = {
|
|
"IN_QUEUE": "queued",
|
|
"IN_PROGRESS": "running",
|
|
"COMPLETED": "completed",
|
|
"FAILED": "failed",
|
|
"CANCELLED": "failed",
|
|
}.get(result.state, "")
|
|
output_url = result.outputs[0].reference if result.outputs else ""
|
|
cost = result.cost.cost_micros if result.cost.success else fallback_cost
|
|
if public_status == "failed":
|
|
cost = 0
|
|
return ExecutionOutcome(
|
|
status=public_status,
|
|
output_url=output_url,
|
|
cost_micros=cost,
|
|
provider_ref=result.handle.run_id,
|
|
status_url=result.handle.status_url,
|
|
response_url=result.handle.response_url,
|
|
error=result.error.message if result.error is not None else "",
|
|
provider_handle=result.handle.to_dict(),
|
|
credential_mode=credential_mode,
|
|
)
|
|
|
|
@staticmethod
|
|
def _raise_failure(exc: Exception) -> None:
|
|
from app.domains.gateway.provider_execution import ProviderExecutionFailure
|
|
|
|
if isinstance(exc, ProviderExecutionFailure):
|
|
if should_fail_over(exc.error):
|
|
raise ExecutionNotAccepted(exc.error.message) from exc
|
|
raise ExecutionBlocked(exc.error.message, exc.error.acceptance) from exc
|
|
raise exc
|
|
|
|
def execute(
|
|
self,
|
|
candidate: Candidate,
|
|
request: GenerationRequest,
|
|
principal: Principal,
|
|
correlation_id: str,
|
|
) -> ExecutionOutcome:
|
|
model = get_model(candidate.model_id)
|
|
if model is None:
|
|
raise RuntimeError(
|
|
f"model {candidate.model_id!r} disappeared from the catalog"
|
|
)
|
|
byok = (
|
|
principal.provider_api_key
|
|
if principal.provider_key == candidate.provider_key
|
|
else ""
|
|
)
|
|
metered_by_duration = model.modality in _DURATION_MODALITIES
|
|
duration = (
|
|
min(request.duration_seconds, model.max_seconds)
|
|
if metered_by_duration and model.max_seconds
|
|
else request.duration_seconds
|
|
if metered_by_duration
|
|
else 0
|
|
)
|
|
provider_request = ProviderRequestV1(
|
|
provider_key=model.provider,
|
|
model_ref=model.model_ref,
|
|
correlation_id=correlation_id,
|
|
modality=model.modality,
|
|
prompt=request.prompt,
|
|
duration_seconds=duration,
|
|
aspect_ratio=request.aspect_ratio if metered_by_duration else "",
|
|
input_refs=(request.image_url,) if request.image_url else (),
|
|
parameters={
|
|
"estimated_cost_micros": candidate.est_cost_micros,
|
|
"cost_source": "catalog_estimate",
|
|
"unit": model.unit,
|
|
"quantity_units": duration if metered_by_duration else 1,
|
|
# Modality-specific inputs; providers read only what they support.
|
|
# Coerced to JSON-native scalars for the versioned request contract.
|
|
"instrumental": bool(request.instrumental),
|
|
"voice_id": request.voice_id or "",
|
|
"reference_audio_url": request.reference_audio_url or "",
|
|
"language": request.language or "",
|
|
},
|
|
)
|
|
try:
|
|
result = self._provider_executor(byok).submit(provider_request)
|
|
except Exception as exc:
|
|
self._raise_failure(exc)
|
|
raise AssertionError("unreachable") # pragma: no cover
|
|
return self._outcome(
|
|
result,
|
|
candidate.est_cost_micros,
|
|
credential_mode="byok" if byok else "service",
|
|
)
|
|
|
|
def poll(
|
|
self,
|
|
record: GenerationResponse,
|
|
handle: ExecutionOutcome,
|
|
principal: Principal,
|
|
) -> ExecutionOutcome:
|
|
model = get_model(record.model)
|
|
if model is None:
|
|
raise RuntimeError(f"model {record.model!r} disappeared from the catalog")
|
|
provider_handle = (
|
|
ProviderHandleV1.from_dict(handle.provider_handle)
|
|
if handle.provider_handle
|
|
else ProviderHandleV1(
|
|
provider_key=record.provider,
|
|
model_ref=model.model_ref,
|
|
run_id=handle.provider_ref,
|
|
state="IN_PROGRESS",
|
|
status_url=handle.status_url,
|
|
response_url=handle.response_url,
|
|
)
|
|
)
|
|
# `credential_mode` is Prism orchestration metadata, not provider state.
|
|
# Read the old opaque location only for rows written before this split.
|
|
credential_mode = handle.credential_mode or str(
|
|
provider_handle.opaque.get("credential_mode", "service")
|
|
)
|
|
if credential_mode == "byok" and (
|
|
principal.provider_key != record.provider or not principal.provider_api_key
|
|
):
|
|
raise ExecutionBlocked(
|
|
"polling this generation requires its request-scoped BYOK credential",
|
|
"accepted",
|
|
)
|
|
byok = (
|
|
principal.provider_api_key
|
|
if principal.provider_key == record.provider
|
|
else ""
|
|
)
|
|
try:
|
|
result = self._provider_executor(byok).poll(provider_handle)
|
|
except Exception as exc:
|
|
self._raise_failure(exc)
|
|
raise AssertionError("unreachable") # pragma: no cover
|
|
return self._outcome(
|
|
result, record.cost_micros, credential_mode=credential_mode
|
|
)
|
|
|
|
def cancel(
|
|
self,
|
|
record: GenerationResponse,
|
|
handle: ExecutionOutcome,
|
|
principal: Principal,
|
|
) -> ExecutionOutcome:
|
|
"""Cancel the upstream provider run behind a non-terminal generation.
|
|
|
|
Providers with an upstream cancel primitive receive it; providers without
|
|
one are abandoned locally by the execution boundary. Either way the
|
|
returned outcome is the CANCELLED (public ``failed``) terminal with zero
|
|
cost, so the Mint hold is released rather than captured.
|
|
"""
|
|
model = get_model(record.model)
|
|
if model is None:
|
|
raise RuntimeError(f"model {record.model!r} disappeared from the catalog")
|
|
provider_handle = (
|
|
ProviderHandleV1.from_dict(handle.provider_handle)
|
|
if handle.provider_handle
|
|
else ProviderHandleV1(
|
|
provider_key=record.provider,
|
|
model_ref=model.model_ref,
|
|
run_id=handle.provider_ref,
|
|
state="IN_PROGRESS",
|
|
status_url=handle.status_url,
|
|
response_url=handle.response_url,
|
|
)
|
|
)
|
|
credential_mode = handle.credential_mode or str(
|
|
provider_handle.opaque.get("credential_mode", "service")
|
|
)
|
|
byok = (
|
|
principal.provider_api_key
|
|
if principal.provider_key == record.provider
|
|
else ""
|
|
)
|
|
try:
|
|
result = self._provider_executor(byok).cancel(provider_handle)
|
|
except Exception as exc:
|
|
self._raise_failure(exc)
|
|
raise AssertionError("unreachable") # pragma: no cover
|
|
return self._outcome(result, 0, credential_mode=credential_mode)
|
|
|
|
|
|
class GenerationStore:
|
|
"""Bounded process-local store, retained for tests and explicit ephemeral use."""
|
|
|
|
def __init__(self, max_records: int = 10_000) -> None:
|
|
self._max_records = max_records
|
|
self._records: dict[str, tuple[str, GenerationResponse, ExecutionOutcome]] = {}
|
|
self._intents: dict[tuple[str, str], GenerationIntent] = {}
|
|
self._settlements: dict[tuple[str, str], SettlementCommand] = {}
|
|
self._lock = threading.Lock()
|
|
|
|
def put(
|
|
self, owner: str, record: GenerationResponse, handle: ExecutionOutcome
|
|
) -> GenerationResponse:
|
|
with self._lock:
|
|
existing = self._records.get(record.id)
|
|
if existing is not None:
|
|
if existing[0] != owner:
|
|
raise PrismError("generation id collision", 500)
|
|
stored = existing[1]
|
|
if stored.status in {"completed", "failed"} or (
|
|
stored.status == "running" and record.status == "queued"
|
|
):
|
|
return stored
|
|
self._records[record.id] = (owner, record, handle)
|
|
intent_key = (owner, record.correlation_id)
|
|
intent = self._intents.get(intent_key)
|
|
if intent is not None:
|
|
self._intents[intent_key] = GenerationIntent(
|
|
request_hash=intent.request_hash,
|
|
generation_id=record.id,
|
|
)
|
|
terminal_ids = [
|
|
generation_id
|
|
for generation_id, (_, stored, _) in self._records.items()
|
|
if stored.status in {"completed", "failed"}
|
|
]
|
|
for generation_id in terminal_ids[: -self._max_records]:
|
|
self._records.pop(generation_id, None)
|
|
for key, stored_intent in list(self._intents.items()):
|
|
if stored_intent.generation_id == generation_id:
|
|
self._intents.pop(key, None)
|
|
self._settlements.pop(key, None)
|
|
return record
|
|
|
|
def get(
|
|
self, owner: str, generation_id: str
|
|
) -> tuple[GenerationResponse, ExecutionOutcome] | None:
|
|
with self._lock:
|
|
value = self._records.get(generation_id)
|
|
return (value[1], value[2]) if value and value[0] == owner else None
|
|
|
|
def reserve_intent(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
request_json: str,
|
|
) -> tuple[GenerationIntent, bool]:
|
|
del request_json
|
|
with self._lock:
|
|
key = (owner, correlation_id)
|
|
existing = self._intents.get(key)
|
|
if existing is not None:
|
|
return existing, False
|
|
intent = GenerationIntent(request_hash=request_hash)
|
|
self._intents[key] = intent
|
|
return intent, True
|
|
|
|
def get_by_correlation(
|
|
self, owner: str, correlation_id: str
|
|
) -> tuple[GenerationResponse, ExecutionOutcome] | None:
|
|
with self._lock:
|
|
intent = self._intents.get((owner, correlation_id))
|
|
if intent is None or not intent.generation_id:
|
|
return None
|
|
value = self._records.get(intent.generation_id)
|
|
return (value[1], value[2]) if value and value[0] == owner else None
|
|
|
|
def release_intent_if_unbound(
|
|
self, owner: str, correlation_id: str, request_hash: str
|
|
) -> None:
|
|
with self._lock:
|
|
key = (owner, correlation_id)
|
|
intent = self._intents.get(key)
|
|
if (
|
|
intent is not None
|
|
and intent.request_hash == request_hash
|
|
and not intent.generation_id
|
|
):
|
|
self._intents.pop(key, None)
|
|
self._settlements.pop(key, None)
|
|
|
|
def get_settlement(
|
|
self, owner: str, correlation_id: str
|
|
) -> SettlementCommand | None:
|
|
with self._lock:
|
|
return self._settlements.get((owner, correlation_id))
|
|
|
|
def bind_settlement(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
command: SettlementCommand,
|
|
) -> SettlementCommand:
|
|
with self._lock:
|
|
key = (owner, correlation_id)
|
|
intent = self._intents.get(key)
|
|
if intent is None or intent.request_hash != request_hash:
|
|
raise PrismError("generation intent changed before authorization", 409)
|
|
existing = self._settlements.get(key)
|
|
if existing is not None:
|
|
if (
|
|
existing.hold_id != command.hold_id
|
|
or existing.reserved_micros != command.reserved_micros
|
|
):
|
|
raise PrismError("Mint authorization conflicts with intent", 409)
|
|
return existing
|
|
self._settlements[key] = command
|
|
return command
|
|
|
|
def update_settlement(
|
|
self, owner: str, correlation_id: str, command: SettlementCommand
|
|
) -> SettlementCommand:
|
|
with self._lock:
|
|
key = (owner, correlation_id)
|
|
existing = self._settlements.get(key)
|
|
if existing is None or (
|
|
existing.hold_id != command.hold_id
|
|
or existing.reserved_micros != command.reserved_micros
|
|
):
|
|
raise PrismError("generation settlement identity changed", 409)
|
|
self._settlements[key] = command
|
|
return command
|
|
|
|
def begin_submission(self, owner: str, correlation_id: str) -> SettlementCommand:
|
|
key = (owner, correlation_id)
|
|
with self._lock:
|
|
command = self._settlements.get(key)
|
|
if command is None:
|
|
raise PrismError("generation has no durable Mint authorization", 500)
|
|
if command.submission_started:
|
|
raise PrismError(
|
|
"generation intent already exists and provider acceptance is unresolved",
|
|
409,
|
|
)
|
|
claimed = replace(command, submission_started=True)
|
|
self._settlements[key] = claimed
|
|
return claimed
|
|
|
|
def list(
|
|
self, owner: str, limit: int, status: str | None = None
|
|
) -> list[GenerationResponse]:
|
|
with self._lock:
|
|
owned = [
|
|
record
|
|
for record_owner, record, _ in self._records.values()
|
|
if record_owner == owner and (status is None or record.status == status)
|
|
]
|
|
# Insertion order is creation order; newest first for callers.
|
|
return list(reversed(owned))[: max(0, limit)]
|
|
|
|
|
|
class SqliteGenerationStore:
|
|
"""Durable owner-scoped provider handles for restart-safe polling."""
|
|
|
|
def __init__(self, path: str, max_records: int = 100_000) -> None:
|
|
self._path = str(Path(path).expanduser().resolve())
|
|
self._max_records = max(1, int(max_records))
|
|
self._max_unresolved_intents = self._max_records
|
|
self._lock = threading.Lock()
|
|
Path(self._path).parent.mkdir(parents=True, exist_ok=True)
|
|
self._initialize()
|
|
|
|
@classmethod
|
|
def from_environment(cls) -> "SqliteGenerationStore":
|
|
configured = os.getenv("PRISM_STORE_PATH", "").strip()
|
|
path = configured or str(
|
|
Path(tempfile.gettempdir()) / "prism-media-gateway" / "generations.sqlite3"
|
|
)
|
|
maximum = int(os.getenv("PRISM_STORE_MAX_RECORDS", "100000"))
|
|
return cls(path, max_records=maximum)
|
|
|
|
def _connect(self) -> sqlite3.Connection:
|
|
connection = sqlite3.connect(self._path, timeout=30)
|
|
connection.execute("PRAGMA journal_mode=WAL")
|
|
connection.execute("PRAGMA busy_timeout=30000")
|
|
return connection
|
|
|
|
def _initialize(self) -> None:
|
|
with self._connect() as connection:
|
|
connection.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS prism_generations (
|
|
id TEXT PRIMARY KEY,
|
|
owner TEXT NOT NULL,
|
|
record_json TEXT NOT NULL,
|
|
handle_json TEXT NOT NULL,
|
|
status TEXT NOT NULL DEFAULT 'queued',
|
|
updated_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
)
|
|
"""
|
|
)
|
|
columns = {
|
|
str(row[1])
|
|
for row in connection.execute("PRAGMA table_info(prism_generations)")
|
|
}
|
|
if "status" not in columns:
|
|
connection.execute(
|
|
"ALTER TABLE prism_generations "
|
|
"ADD COLUMN status TEXT NOT NULL DEFAULT 'queued'"
|
|
)
|
|
connection.execute(
|
|
"UPDATE prism_generations "
|
|
"SET status = COALESCE(json_extract(record_json, '$.status'), status)"
|
|
)
|
|
connection.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS prism_generation_intents (
|
|
owner TEXT NOT NULL,
|
|
correlation_id TEXT NOT NULL,
|
|
request_hash TEXT NOT NULL,
|
|
request_json TEXT NOT NULL,
|
|
generation_id TEXT NOT NULL DEFAULT '',
|
|
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
PRIMARY KEY (owner, correlation_id)
|
|
)
|
|
"""
|
|
)
|
|
connection.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS prism_generation_settlements (
|
|
owner TEXT NOT NULL,
|
|
correlation_id TEXT NOT NULL,
|
|
request_hash TEXT NOT NULL,
|
|
hold_id TEXT NOT NULL,
|
|
reserved_micros INTEGER NOT NULL,
|
|
status TEXT NOT NULL,
|
|
charged_micros INTEGER NOT NULL DEFAULT 0,
|
|
receipt_json TEXT NOT NULL DEFAULT '',
|
|
submission_started INTEGER NOT NULL DEFAULT 0,
|
|
last_error TEXT NOT NULL DEFAULT '',
|
|
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
|
PRIMARY KEY (owner, correlation_id)
|
|
)
|
|
"""
|
|
)
|
|
connection.execute(
|
|
"""
|
|
UPDATE prism_generation_intents
|
|
SET request_json =
|
|
'{"schema":"prism.generation-intent/v1","redacted":true}'
|
|
WHERE instr(
|
|
request_json, '"schema":"prism.generation-intent/v1"'
|
|
) = 0
|
|
"""
|
|
)
|
|
connection.execute(
|
|
"CREATE INDEX IF NOT EXISTS ix_prism_generations_owner "
|
|
"ON prism_generations(owner, updated_at DESC)"
|
|
)
|
|
|
|
def put(
|
|
self, owner: str, record: GenerationResponse, handle: ExecutionOutcome
|
|
) -> GenerationResponse:
|
|
record_json = record.model_dump_json()
|
|
handle_json = json.dumps(asdict(handle), separators=(",", ":"))
|
|
with self._lock, self._connect() as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
connection.execute(
|
|
"""
|
|
INSERT INTO prism_generations (
|
|
id, owner, record_json, handle_json, status, updated_at
|
|
) VALUES (?, ?, ?, ?, ?, unixepoch())
|
|
ON CONFLICT(id) DO UPDATE SET
|
|
owner=excluded.owner,
|
|
record_json=excluded.record_json,
|
|
handle_json=excluded.handle_json,
|
|
status=excluded.status,
|
|
updated_at=unixepoch()
|
|
WHERE prism_generations.status NOT IN ('completed', 'failed')
|
|
AND prism_generations.owner = excluded.owner
|
|
AND NOT (
|
|
prism_generations.status = 'running'
|
|
AND excluded.status = 'queued'
|
|
)
|
|
""",
|
|
(record.id, owner, record_json, handle_json, record.status),
|
|
)
|
|
connection.execute(
|
|
"""
|
|
UPDATE prism_generation_intents
|
|
SET generation_id = ?, updated_at = unixepoch()
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(record.id, owner, record.correlation_id),
|
|
)
|
|
if record.status in {"completed", "failed"}:
|
|
stale_terminal = connection.execute(
|
|
"""
|
|
SELECT id FROM prism_generations
|
|
WHERE status IN ('completed', 'failed') AND id != ?
|
|
ORDER BY updated_at DESC, id DESC
|
|
LIMIT -1 OFFSET ?
|
|
""",
|
|
(record.id, self._max_records - 1),
|
|
).fetchall()
|
|
else:
|
|
stale_terminal = connection.execute(
|
|
"""
|
|
SELECT id FROM prism_generations
|
|
WHERE status IN ('completed', 'failed')
|
|
ORDER BY updated_at DESC, id DESC
|
|
LIMIT -1 OFFSET ?
|
|
""",
|
|
(self._max_records,),
|
|
).fetchall()
|
|
connection.executemany(
|
|
"DELETE FROM prism_generation_settlements "
|
|
"WHERE owner = (SELECT owner FROM prism_generation_intents "
|
|
"WHERE generation_id = ?) AND correlation_id = "
|
|
"(SELECT correlation_id FROM prism_generation_intents "
|
|
"WHERE generation_id = ?)",
|
|
[(row[0], row[0]) for row in stale_terminal],
|
|
)
|
|
connection.executemany(
|
|
"DELETE FROM prism_generation_intents WHERE generation_id = ?",
|
|
stale_terminal,
|
|
)
|
|
connection.executemany(
|
|
"DELETE FROM prism_generations WHERE id = ?", stale_terminal
|
|
)
|
|
stored = connection.execute(
|
|
"SELECT record_json FROM prism_generations WHERE id = ? AND owner = ?",
|
|
(record.id, owner),
|
|
).fetchone()
|
|
if stored is None: # pragma: no cover - UUID collision/corrupt ownership
|
|
raise PrismError("failed to persist generation state", 500)
|
|
try:
|
|
return GenerationResponse.model_validate_json(stored[0])
|
|
except (TypeError, ValueError) as exc:
|
|
raise PrismError("stored generation state is invalid", 500) from exc
|
|
|
|
def get(
|
|
self, owner: str, generation_id: str
|
|
) -> tuple[GenerationResponse, ExecutionOutcome] | None:
|
|
with self._lock, self._connect() as connection:
|
|
row = connection.execute(
|
|
"SELECT record_json, handle_json FROM prism_generations "
|
|
"WHERE id = ? AND owner = ?",
|
|
(generation_id, owner),
|
|
).fetchone()
|
|
if row is None:
|
|
return None
|
|
try:
|
|
return (
|
|
GenerationResponse.model_validate_json(row[0]),
|
|
ExecutionOutcome(**json.loads(row[1])),
|
|
)
|
|
except (TypeError, ValueError, json.JSONDecodeError) as exc:
|
|
raise PrismError("stored generation state is invalid", 500) from exc
|
|
|
|
def reserve_intent(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
request_json: str,
|
|
) -> tuple[GenerationIntent, bool]:
|
|
with self._lock, self._connect() as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
existing = connection.execute(
|
|
"""
|
|
SELECT request_hash, generation_id
|
|
FROM prism_generation_intents
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
if existing is not None:
|
|
return GenerationIntent(str(existing[0]), str(existing[1] or "")), False
|
|
unresolved = connection.execute(
|
|
"""
|
|
SELECT COUNT(*) FROM prism_generation_intents
|
|
WHERE generation_id = ''
|
|
"""
|
|
).fetchone()
|
|
if (
|
|
unresolved is not None
|
|
and int(unresolved[0]) >= self._max_unresolved_intents
|
|
):
|
|
raise PrismError("too many unresolved generation intents", 503)
|
|
cursor = connection.execute(
|
|
"""
|
|
INSERT OR IGNORE INTO prism_generation_intents (
|
|
owner, correlation_id, request_hash, request_json
|
|
) VALUES (?, ?, ?, ?)
|
|
""",
|
|
(owner, correlation_id, request_hash, request_json),
|
|
)
|
|
row = connection.execute(
|
|
"""
|
|
SELECT request_hash, generation_id
|
|
FROM prism_generation_intents
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
if row is None: # pragma: no cover - guarded by the transaction above
|
|
raise PrismError("failed to reserve generation intent", 500)
|
|
return GenerationIntent(str(row[0]), str(row[1] or "")), cursor.rowcount == 1
|
|
|
|
def get_by_correlation(
|
|
self, owner: str, correlation_id: str
|
|
) -> tuple[GenerationResponse, ExecutionOutcome] | None:
|
|
with self._lock, self._connect() as connection:
|
|
row = connection.execute(
|
|
"""
|
|
SELECT g.record_json, g.handle_json
|
|
FROM prism_generation_intents AS i
|
|
JOIN prism_generations AS g
|
|
ON g.id = i.generation_id AND g.owner = i.owner
|
|
WHERE i.owner = ? AND i.correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
if row is None:
|
|
return None
|
|
try:
|
|
return (
|
|
GenerationResponse.model_validate_json(row[0]),
|
|
ExecutionOutcome(**json.loads(row[1])),
|
|
)
|
|
except (TypeError, ValueError, json.JSONDecodeError) as exc:
|
|
raise PrismError("stored generation state is invalid", 500) from exc
|
|
|
|
def release_intent_if_unbound(
|
|
self, owner: str, correlation_id: str, request_hash: str
|
|
) -> None:
|
|
with self._lock, self._connect() as connection:
|
|
connection.execute(
|
|
"""
|
|
DELETE FROM prism_generation_settlements
|
|
WHERE owner = ? AND correlation_id = ? AND request_hash = ?
|
|
AND EXISTS (
|
|
SELECT 1 FROM prism_generation_intents
|
|
WHERE owner = ? AND correlation_id = ? AND request_hash = ?
|
|
AND generation_id = ''
|
|
)
|
|
""",
|
|
(
|
|
owner,
|
|
correlation_id,
|
|
request_hash,
|
|
owner,
|
|
correlation_id,
|
|
request_hash,
|
|
),
|
|
)
|
|
connection.execute(
|
|
"""
|
|
DELETE FROM prism_generation_intents
|
|
WHERE owner = ? AND correlation_id = ? AND request_hash = ?
|
|
AND generation_id = ''
|
|
""",
|
|
(owner, correlation_id, request_hash),
|
|
)
|
|
|
|
@staticmethod
|
|
def _settlement_from_row(row: tuple[Any, ...]) -> SettlementCommand:
|
|
return SettlementCommand(
|
|
hold_id=str(row[0]),
|
|
reserved_micros=int(row[1]),
|
|
status=str(row[2]),
|
|
charged_micros=int(row[3]),
|
|
receipt_json=str(row[4]),
|
|
submission_started=bool(row[5]),
|
|
last_error=str(row[6]),
|
|
)
|
|
|
|
def get_settlement(
|
|
self, owner: str, correlation_id: str
|
|
) -> SettlementCommand | None:
|
|
with self._lock, self._connect() as connection:
|
|
row = connection.execute(
|
|
"""
|
|
SELECT hold_id, reserved_micros, status, charged_micros,
|
|
receipt_json, submission_started, last_error
|
|
FROM prism_generation_settlements
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
return self._settlement_from_row(row) if row is not None else None
|
|
|
|
def bind_settlement(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
command: SettlementCommand,
|
|
) -> SettlementCommand:
|
|
with self._lock, self._connect() as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
intent = connection.execute(
|
|
"""
|
|
SELECT request_hash FROM prism_generation_intents
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
if intent is None or str(intent[0]) != request_hash:
|
|
raise PrismError("generation intent changed before authorization", 409)
|
|
connection.execute(
|
|
"""
|
|
INSERT OR IGNORE INTO prism_generation_settlements (
|
|
owner, correlation_id, request_hash, hold_id,
|
|
reserved_micros, status, charged_micros, receipt_json,
|
|
submission_started, last_error
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(
|
|
owner,
|
|
correlation_id,
|
|
request_hash,
|
|
command.hold_id,
|
|
command.reserved_micros,
|
|
command.status,
|
|
command.charged_micros,
|
|
command.receipt_json,
|
|
int(command.submission_started),
|
|
command.last_error,
|
|
),
|
|
)
|
|
row = connection.execute(
|
|
"""
|
|
SELECT hold_id, reserved_micros, status, charged_micros,
|
|
receipt_json, submission_started, last_error
|
|
FROM prism_generation_settlements
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
if row is None: # pragma: no cover - transaction guarantees it
|
|
raise PrismError("failed to persist Mint authorization", 500)
|
|
existing = self._settlement_from_row(row)
|
|
if (
|
|
existing.hold_id != command.hold_id
|
|
or existing.reserved_micros != command.reserved_micros
|
|
):
|
|
raise PrismError("Mint authorization conflicts with intent", 409)
|
|
return existing
|
|
|
|
def update_settlement(
|
|
self, owner: str, correlation_id: str, command: SettlementCommand
|
|
) -> SettlementCommand:
|
|
with self._lock, self._connect() as connection:
|
|
cursor = connection.execute(
|
|
"""
|
|
UPDATE prism_generation_settlements
|
|
SET status = ?, charged_micros = ?, receipt_json = ?,
|
|
submission_started = ?, last_error = ?, updated_at = unixepoch()
|
|
WHERE owner = ? AND correlation_id = ? AND hold_id = ?
|
|
AND reserved_micros = ?
|
|
""",
|
|
(
|
|
command.status,
|
|
command.charged_micros,
|
|
command.receipt_json,
|
|
int(command.submission_started),
|
|
command.last_error,
|
|
owner,
|
|
correlation_id,
|
|
command.hold_id,
|
|
command.reserved_micros,
|
|
),
|
|
)
|
|
if cursor.rowcount != 1:
|
|
raise PrismError("generation settlement identity changed", 409)
|
|
return command
|
|
|
|
def spent_since(self, owner: str, since_epoch: int) -> int:
|
|
"""Authoritative daily spend for ``owner`` from the durable settlement ledger.
|
|
|
|
Sums the outstanding financial exposure of every settlement this owner's
|
|
key created at or after ``since_epoch`` (the midnight-UTC window start, as a
|
|
Unix timestamp): a captured hold counts its charged amount, a released hold
|
|
counts zero, and a hold still outstanding counts its full reservation.
|
|
Attribution to a UTC day uses the intent's creation time, the moment the
|
|
reservation was made. Because every gateway worker writes to this same
|
|
SQLite ledger, the sum is identical across processes — which is what makes
|
|
the per-key daily cap hold cluster-wide instead of resetting per worker.
|
|
"""
|
|
with self._lock, self._connect() as connection:
|
|
row = connection.execute(
|
|
"""
|
|
SELECT COALESCE(SUM(
|
|
CASE s.status
|
|
WHEN 'released' THEN 0
|
|
WHEN 'captured' THEN s.charged_micros
|
|
ELSE s.reserved_micros
|
|
END
|
|
), 0)
|
|
FROM prism_generation_settlements AS s
|
|
JOIN prism_generation_intents AS i
|
|
ON i.owner = s.owner AND i.correlation_id = s.correlation_id
|
|
WHERE s.owner = ? AND i.created_at >= ?
|
|
""",
|
|
(owner, int(since_epoch)),
|
|
).fetchone()
|
|
return int(row[0]) if row is not None else 0
|
|
|
|
def begin_submission(self, owner: str, correlation_id: str) -> SettlementCommand:
|
|
with self._lock, self._connect() as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
cursor = connection.execute(
|
|
"""
|
|
UPDATE prism_generation_settlements
|
|
SET submission_started = 1, updated_at = unixepoch()
|
|
WHERE owner = ? AND correlation_id = ? AND submission_started = 0
|
|
""",
|
|
(owner, correlation_id),
|
|
)
|
|
row = connection.execute(
|
|
"""
|
|
SELECT hold_id, reserved_micros, status, charged_micros,
|
|
receipt_json, submission_started, last_error
|
|
FROM prism_generation_settlements
|
|
WHERE owner = ? AND correlation_id = ?
|
|
""",
|
|
(owner, correlation_id),
|
|
).fetchone()
|
|
if row is None:
|
|
raise PrismError("generation has no durable Mint authorization", 500)
|
|
if cursor.rowcount != 1:
|
|
raise PrismError(
|
|
"generation intent already exists and provider acceptance is unresolved",
|
|
409,
|
|
)
|
|
return self._settlement_from_row(row)
|
|
|
|
def list(
|
|
self, owner: str, limit: int, status: str | None = None
|
|
) -> list[GenerationResponse]:
|
|
bounded = max(0, int(limit))
|
|
with self._lock, self._connect() as connection:
|
|
if status is None:
|
|
rows = connection.execute(
|
|
"SELECT record_json FROM prism_generations WHERE owner = ? "
|
|
"ORDER BY updated_at DESC, id DESC LIMIT ?",
|
|
(owner, bounded),
|
|
).fetchall()
|
|
else:
|
|
rows = connection.execute(
|
|
"SELECT record_json FROM prism_generations "
|
|
"WHERE owner = ? AND status = ? "
|
|
"ORDER BY updated_at DESC, id DESC LIMIT ?",
|
|
(owner, status, bounded),
|
|
).fetchall()
|
|
try:
|
|
return [GenerationResponse.model_validate_json(row[0]) for row in rows]
|
|
except (TypeError, ValueError) as exc:
|
|
raise PrismError("stored generation state is invalid", 500) from exc
|
|
|
|
|
|
class PrismService:
|
|
def __init__(
|
|
self,
|
|
executor: MediaExecutor | None = None,
|
|
store: GenerationStorePort | None = None,
|
|
settlement: SettlementPort | None = None,
|
|
spend_ledger: SpendLedger | None = None,
|
|
) -> None:
|
|
self._executor = executor or AdapterExecutor()
|
|
self._store = store or GenerationStore()
|
|
self._settlement = settlement or MintSettlementClient.from_environment()
|
|
# Per-key daily spend ceiling, checked before any Mint hold is authorized.
|
|
# Defaults to unlimited unless PRISM_DAILY_CAP_MICROS configures a cap.
|
|
self._spend_ledger = spend_ledger or SpendLedger.from_environment()
|
|
# Make that cap authoritative across worker processes: when the store is a
|
|
# durable, shared settlement ledger, hand it to the spend ledger so the cap
|
|
# sums committed spend from disk instead of a per-process in-memory window.
|
|
# A leaked key then cannot exceed the cap by fanning out across workers.
|
|
# Ephemeral stores expose no ``spent_since`` and keep the in-memory-only
|
|
# behaviour; the durable path additionally requires a shared
|
|
# ``PRISM_STORE_PATH`` mounted by every worker.
|
|
if (
|
|
self._spend_ledger.enabled
|
|
and not self._spend_ledger.durable
|
|
and hasattr(self._store, "spent_since")
|
|
):
|
|
self._spend_ledger.attach_spend_source(self._store)
|
|
|
|
def health(self) -> dict[str, Any]:
|
|
readiness = self._settlement.readiness()
|
|
return {
|
|
"status": "ok" if readiness.get("status") == "ready" else "degraded",
|
|
"settlement": readiness,
|
|
}
|
|
|
|
@staticmethod
|
|
def _settlement_view(command: SettlementCommand) -> GenerationSettlement:
|
|
receipt = (
|
|
SettlementReceipt.model_validate_json(command.receipt_json)
|
|
if command.receipt_json
|
|
else None
|
|
)
|
|
return GenerationSettlement(
|
|
status=command.status,
|
|
reserved_micros=command.reserved_micros,
|
|
charged_micros=command.charged_micros,
|
|
receipt=receipt,
|
|
)
|
|
|
|
def _with_settlement(
|
|
self, owner: str, record: GenerationResponse
|
|
) -> GenerationResponse:
|
|
command = self._store.get_settlement(owner, record.correlation_id)
|
|
if command is None:
|
|
raise PrismError("generation has no durable Mint authorization", 500)
|
|
return record.model_copy(update={"settlement": self._settlement_view(command)})
|
|
|
|
def _authorize(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
request_hash: str,
|
|
reserved_micros: int,
|
|
) -> SettlementCommand:
|
|
existing = self._store.get_settlement(owner, correlation_id)
|
|
if existing is not None:
|
|
if existing.reserved_micros != reserved_micros:
|
|
raise PrismError("generation authorization amount changed", 409)
|
|
return existing
|
|
try:
|
|
authorization = self._settlement.authorize(
|
|
owner, correlation_id, reserved_micros
|
|
)
|
|
except MintSettlementError as exc:
|
|
raise PrismError(str(exc), exc.status_code) from exc
|
|
return self._store.bind_settlement(
|
|
owner,
|
|
correlation_id,
|
|
request_hash,
|
|
SettlementCommand(
|
|
hold_id=authorization.hold_id,
|
|
reserved_micros=authorization.reserved_micros,
|
|
),
|
|
)
|
|
|
|
def _settle_terminal(
|
|
self,
|
|
owner: str,
|
|
record: GenerationResponse,
|
|
) -> GenerationResponse:
|
|
command = self._store.get_settlement(owner, record.correlation_id)
|
|
if command is None:
|
|
raise PrismError("generation has no durable Mint authorization", 500)
|
|
if record.status == "completed" and record.cost_micros > 0:
|
|
if command.status == "captured":
|
|
return self._with_settlement(owner, record)
|
|
if command.status in {"released", "release_pending"}:
|
|
raise PrismError("completed generation authorization was released", 500)
|
|
pending = replace(
|
|
command,
|
|
status="capture_pending",
|
|
charged_micros=record.cost_micros,
|
|
last_error="",
|
|
)
|
|
self._store.update_settlement(owner, record.correlation_id, pending)
|
|
try:
|
|
receipt = self._settlement.capture(
|
|
owner,
|
|
HoldAuthorization(command.hold_id, command.reserved_micros),
|
|
record.id,
|
|
record.cost_micros,
|
|
)
|
|
except MintSettlementError as exc:
|
|
self._store.update_settlement(
|
|
owner,
|
|
record.correlation_id,
|
|
replace(pending, last_error=str(exc)),
|
|
)
|
|
raise PrismError(str(exc), exc.status_code) from exc
|
|
self._store.update_settlement(
|
|
owner,
|
|
record.correlation_id,
|
|
replace(
|
|
pending,
|
|
status="captured",
|
|
receipt_json=receipt.model_dump_json(),
|
|
last_error="",
|
|
),
|
|
)
|
|
return self._with_settlement(owner, record)
|
|
|
|
if record.status == "failed" or (
|
|
record.status == "completed" and record.cost_micros == 0
|
|
):
|
|
if command.status == "released":
|
|
return self._with_settlement(owner, record)
|
|
if command.status in {"captured", "capture_pending"}:
|
|
raise PrismError(
|
|
"zero-charge generation authorization was captured", 500
|
|
)
|
|
pending = replace(
|
|
command,
|
|
status="release_pending",
|
|
charged_micros=0,
|
|
last_error="",
|
|
)
|
|
self._store.update_settlement(owner, record.correlation_id, pending)
|
|
try:
|
|
receipt = self._settlement.release(
|
|
owner,
|
|
HoldAuthorization(command.hold_id, command.reserved_micros),
|
|
record.id,
|
|
)
|
|
except MintSettlementError as exc:
|
|
self._store.update_settlement(
|
|
owner,
|
|
record.correlation_id,
|
|
replace(pending, last_error=str(exc)),
|
|
)
|
|
raise PrismError(str(exc), exc.status_code) from exc
|
|
self._store.update_settlement(
|
|
owner,
|
|
record.correlation_id,
|
|
replace(
|
|
pending,
|
|
status="released",
|
|
receipt_json=receipt.model_dump_json(),
|
|
last_error="",
|
|
),
|
|
)
|
|
return self._with_settlement(owner, record)
|
|
return self._with_settlement(owner, record)
|
|
|
|
def _record_definitive_failure(
|
|
self,
|
|
owner: str,
|
|
correlation_id: str,
|
|
modality: str,
|
|
candidate: Candidate,
|
|
attempts: list[Attempt],
|
|
error: str,
|
|
) -> GenerationResponse:
|
|
record = GenerationResponse(
|
|
id=f"gen_{uuid4().hex}",
|
|
correlation_id=correlation_id,
|
|
status="failed",
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
modality=modality,
|
|
error=error,
|
|
cost_micros=0,
|
|
attempts=attempts,
|
|
)
|
|
stored = self._store.put(
|
|
owner,
|
|
record,
|
|
ExecutionOutcome(status="failed", error=error, cost_micros=0),
|
|
)
|
|
return self._settle_terminal(owner, stored)
|
|
|
|
@staticmethod
|
|
def models(modality: str | None = None) -> list[ModelResponse]:
|
|
if modality and modality not in _ROUTABLE_MODALITIES:
|
|
raise PrismError("modality must be image, video, or audio", 422)
|
|
return [
|
|
ModelResponse(
|
|
id=model.id,
|
|
modality=model.modality,
|
|
provider=model.provider,
|
|
price_micros=model.price_micros,
|
|
unit=model.unit,
|
|
description=model.description,
|
|
)
|
|
for model in list_models(modality)
|
|
if model.modality in _ROUTABLE_MODALITIES
|
|
]
|
|
|
|
@staticmethod
|
|
def _candidates(request: GenerationRequest) -> tuple[str, list[Candidate]]:
|
|
primary = get_model(request.model)
|
|
if primary is None or primary.modality not in _ROUTABLE_MODALITIES:
|
|
raise PrismError(f"unknown Sx0 media model {request.model!r}", 404)
|
|
if request.modality and request.modality != primary.modality:
|
|
raise PrismError(
|
|
"requested modality does not match the selected model", 422
|
|
)
|
|
candidates = []
|
|
for model in list_models(primary.modality):
|
|
quantity = (
|
|
min(request.duration_seconds, model.max_seconds)
|
|
if model.modality in _DURATION_MODALITIES and model.max_seconds
|
|
else request.duration_seconds
|
|
if model.modality in _DURATION_MODALITIES
|
|
else 1
|
|
)
|
|
candidates.append(
|
|
Candidate(
|
|
model_id=model.id,
|
|
provider_key=model.provider,
|
|
capability=model.modality,
|
|
est_cost_micros=model.price_micros * quantity,
|
|
)
|
|
)
|
|
return primary.modality, candidates
|
|
|
|
@staticmethod
|
|
def _canonical_request(
|
|
request: GenerationRequest, principal: Principal
|
|
) -> tuple[str, str]:
|
|
credential_mode = "byok" if principal.provider_api_key else "service"
|
|
canonical = {
|
|
"request": request.model_dump(mode="json"),
|
|
"provider_key": principal.provider_key,
|
|
"credential_mode": credential_mode,
|
|
}
|
|
canonical_json = json.dumps(
|
|
canonical,
|
|
sort_keys=True,
|
|
separators=(",", ":"),
|
|
)
|
|
safe_intent_json = json.dumps(
|
|
{
|
|
"schema": "prism.generation-intent/v1",
|
|
"model": request.model,
|
|
"modality": request.modality or "",
|
|
"provider_key": principal.provider_key,
|
|
"credential_mode": credential_mode,
|
|
},
|
|
sort_keys=True,
|
|
separators=(",", ":"),
|
|
)
|
|
return (
|
|
hashlib.sha256(canonical_json.encode("utf-8")).hexdigest(),
|
|
safe_intent_json,
|
|
)
|
|
|
|
@staticmethod
|
|
def _exact_cost(candidate: Candidate, outcome: ExecutionOutcome) -> int:
|
|
raw = (
|
|
candidate.est_cost_micros
|
|
if outcome.cost_micros is None
|
|
else outcome.cost_micros
|
|
)
|
|
try:
|
|
exact = int(raw)
|
|
except (TypeError, ValueError) as exc:
|
|
raise PrismError(
|
|
"provider returned an invalid generation cost", 502
|
|
) from exc
|
|
if exact < 0 or exact > candidate.est_cost_micros:
|
|
raise PrismError(
|
|
"provider-reported cost exceeded the reserved model estimate", 502
|
|
)
|
|
return exact
|
|
|
|
@staticmethod
|
|
def _validate_initial_outcome(outcome: ExecutionOutcome) -> None:
|
|
if outcome.status not in {"queued", "running", "completed"}:
|
|
raise PrismError("provider returned an invalid initial status", 502)
|
|
if outcome.status == "completed" and not outcome.output_url:
|
|
raise PrismError("provider completed without an output URL", 502)
|
|
if outcome.status in {"queued", "running"} and not outcome.provider_ref:
|
|
raise PrismError("provider accepted work without a durable handle", 502)
|
|
|
|
@staticmethod
|
|
def _updated_attempts(record: GenerationResponse, status: str) -> list[Attempt]:
|
|
outcome = "failed" if status == "failed" else "completed"
|
|
if status not in {"failed", "completed"}:
|
|
return list(record.attempts)
|
|
attempts = list(record.attempts)
|
|
for index in range(len(attempts) - 1, -1, -1):
|
|
attempt = attempts[index]
|
|
if attempt.model == record.model and attempt.provider == record.provider:
|
|
attempts[index] = attempt.model_copy(update={"outcome": outcome})
|
|
break
|
|
return attempts
|
|
|
|
def generate(
|
|
self, request: GenerationRequest, principal: Principal, correlation_id: str
|
|
) -> GenerationResponse:
|
|
if not correlation_id or len(correlation_id) > 128:
|
|
raise PrismError("correlation id must contain 1 to 128 characters", 422)
|
|
modality, candidates = self._candidates(request)
|
|
route = select_route(
|
|
request.model,
|
|
candidates,
|
|
RoutePolicy(
|
|
fallback=request.routing.fallback,
|
|
max_cost_micros=request.routing.max_cost_micros,
|
|
provider_order=tuple(request.routing.provider_order),
|
|
sort=request.routing.sort,
|
|
),
|
|
)
|
|
if not route:
|
|
raise PrismError(
|
|
"selected model is unavailable under the routing policy", 422
|
|
)
|
|
if (
|
|
principal.provider_api_key
|
|
and principal.provider_key != route[0].provider_key
|
|
):
|
|
raise PrismError(
|
|
"BYOK provider must match the selected model's provider", 422
|
|
)
|
|
|
|
request_hash, request_json = self._canonical_request(request, principal)
|
|
intent, created = self._store.reserve_intent(
|
|
principal.key_fingerprint,
|
|
correlation_id,
|
|
request_hash,
|
|
request_json,
|
|
)
|
|
if not created:
|
|
if intent.request_hash != request_hash:
|
|
raise PrismError(
|
|
"correlation id is already bound to a different request", 409
|
|
)
|
|
if intent.generation_id:
|
|
stored = self._store.get(
|
|
principal.key_fingerprint, intent.generation_id
|
|
)
|
|
if stored is None:
|
|
raise PrismError(
|
|
"the idempotent generation record is no longer available", 410
|
|
)
|
|
record = stored[0]
|
|
return (
|
|
self._settle_terminal(principal.key_fingerprint, record)
|
|
if record.status in {"completed", "failed"}
|
|
else self._with_settlement(principal.key_fingerprint, record)
|
|
)
|
|
|
|
reserved_micros = max(candidate.est_cost_micros for candidate in route)
|
|
spend = self._spend_ledger.try_reserve(
|
|
principal.key_fingerprint,
|
|
reserved_micros,
|
|
correlation_id=correlation_id,
|
|
)
|
|
if not spend.allow:
|
|
raise PrismError(
|
|
f"per-key daily spend cap exceeded: {spend.reason}", 429
|
|
)
|
|
self._authorize(
|
|
principal.key_fingerprint,
|
|
correlation_id,
|
|
request_hash,
|
|
reserved_micros,
|
|
)
|
|
self._store.begin_submission(principal.key_fingerprint, correlation_id)
|
|
|
|
attempts: list[Attempt] = []
|
|
failed_providers: set[str] = set()
|
|
last_error = "no provider accepted the request"
|
|
for candidate in route:
|
|
if candidate.provider_key in failed_providers:
|
|
continue
|
|
try:
|
|
outcome = self._executor.execute(
|
|
candidate, request, principal, correlation_id
|
|
)
|
|
except ExecutionNotAccepted as exc:
|
|
if principal.provider_api_key:
|
|
attempts.append(
|
|
Attempt(
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
outcome="failed",
|
|
)
|
|
)
|
|
self._record_definitive_failure(
|
|
principal.key_fingerprint,
|
|
correlation_id,
|
|
modality,
|
|
candidate,
|
|
attempts,
|
|
str(exc) or type(exc).__name__,
|
|
)
|
|
raise PrismError(
|
|
f"BYOK provider did not accept the request: {exc}", 502
|
|
) from exc
|
|
failed_providers.add(candidate.provider_key)
|
|
last_error = str(exc) or type(exc).__name__
|
|
attempts.append(
|
|
Attempt(
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
outcome="failed",
|
|
)
|
|
)
|
|
continue
|
|
except ExecutionBlocked as exc:
|
|
if exc.acceptance == "not_accepted":
|
|
attempts.append(
|
|
Attempt(
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
outcome="failed",
|
|
)
|
|
)
|
|
self._record_definitive_failure(
|
|
principal.key_fingerprint,
|
|
correlation_id,
|
|
modality,
|
|
candidate,
|
|
attempts,
|
|
str(exc) or type(exc).__name__,
|
|
)
|
|
prefix = (
|
|
"provider acceptance is unknown"
|
|
if exc.acceptance == "unknown"
|
|
else "provider rejected the request"
|
|
)
|
|
raise PrismError(f"{prefix}: {exc}", 502) from exc
|
|
except Exception as exc:
|
|
raise PrismError(
|
|
f"provider acceptance is unknown: {str(exc) or type(exc).__name__}",
|
|
502,
|
|
) from exc
|
|
|
|
generation_id = f"gen_{uuid4().hex}"
|
|
accepted_evidence = bool(outcome.provider_ref) or outcome.status in {
|
|
"completed",
|
|
"failed",
|
|
}
|
|
provisional_status = (
|
|
"failed"
|
|
if outcome.status == "failed"
|
|
else "queued"
|
|
if outcome.status == "queued" and outcome.provider_ref
|
|
else "running"
|
|
)
|
|
provisional_attempts = [
|
|
*attempts,
|
|
Attempt(
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
outcome=(
|
|
"failed" if provisional_status == "failed" else "submitted"
|
|
),
|
|
),
|
|
]
|
|
provisional_record = GenerationResponse(
|
|
id=generation_id,
|
|
correlation_id=correlation_id,
|
|
status=provisional_status,
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
modality=modality,
|
|
output_url=(
|
|
outcome.output_url if outcome.status == "completed" else ""
|
|
),
|
|
error=outcome.error,
|
|
provider_ref=outcome.provider_ref,
|
|
cost_micros=(
|
|
0 if provisional_status == "failed" else candidate.est_cost_micros
|
|
),
|
|
attempts=provisional_attempts,
|
|
)
|
|
if accepted_evidence:
|
|
self._store.put(principal.key_fingerprint, provisional_record, outcome)
|
|
|
|
try:
|
|
self._validate_initial_outcome(outcome)
|
|
except PrismError:
|
|
if provisional_status == "failed":
|
|
self._settle_terminal(principal.key_fingerprint, provisional_record)
|
|
raise
|
|
public_status = outcome.status
|
|
exact_cost = self._exact_cost(candidate, outcome)
|
|
if (
|
|
request.routing.max_cost_micros is not None
|
|
and exact_cost > request.routing.max_cost_micros
|
|
):
|
|
raise PrismError(
|
|
"provider-reported cost exceeded the caller's hard cap", 502
|
|
)
|
|
attempts.append(
|
|
Attempt(
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
outcome="completed"
|
|
if public_status == "completed"
|
|
else "submitted",
|
|
)
|
|
)
|
|
record = GenerationResponse(
|
|
id=generation_id,
|
|
correlation_id=correlation_id,
|
|
status=public_status,
|
|
model=candidate.model_id,
|
|
provider=candidate.provider_key,
|
|
modality=modality,
|
|
output_url=outcome.output_url,
|
|
provider_ref=outcome.provider_ref,
|
|
cost_micros=exact_cost,
|
|
attempts=attempts,
|
|
)
|
|
stored = self._store.put(principal.key_fingerprint, record, outcome)
|
|
return (
|
|
self._settle_terminal(principal.key_fingerprint, stored)
|
|
if stored.status in {"completed", "failed"}
|
|
else self._with_settlement(principal.key_fingerprint, stored)
|
|
)
|
|
self._record_definitive_failure(
|
|
principal.key_fingerprint,
|
|
correlation_id,
|
|
modality,
|
|
route[-1],
|
|
attempts,
|
|
last_error,
|
|
)
|
|
raise PrismError(f"all eligible providers failed: {last_error}", 502)
|
|
|
|
def generation_by_correlation(
|
|
self, principal: Principal, correlation_id: str
|
|
) -> GenerationResponse:
|
|
stored = self._store.get_by_correlation(
|
|
principal.key_fingerprint, correlation_id
|
|
)
|
|
if stored is None:
|
|
raise PrismError("generation not found", 404)
|
|
record = stored[0]
|
|
return (
|
|
self._settle_terminal(principal.key_fingerprint, record)
|
|
if record.status in {"completed", "failed"}
|
|
else self._with_settlement(principal.key_fingerprint, record)
|
|
)
|
|
|
|
def generation(
|
|
self, principal: Principal, generation_id: str, correlation_id: str = ""
|
|
) -> GenerationResponse:
|
|
stored = self._store.get(principal.key_fingerprint, generation_id)
|
|
if stored is None:
|
|
raise PrismError("generation not found", 404)
|
|
record, handle = stored
|
|
if correlation_id and record.correlation_id != correlation_id:
|
|
raise PrismError("generation correlation mismatch", 409)
|
|
if principal.provider_api_key and principal.provider_key != record.provider:
|
|
raise PrismError(
|
|
"BYOK provider does not match the generation provider", 422
|
|
)
|
|
if record.status in {"completed", "failed"}:
|
|
return self._settle_terminal(principal.key_fingerprint, record)
|
|
poll = getattr(self._executor, "poll", None)
|
|
if record.status in {"queued", "running"} and callable(poll):
|
|
try:
|
|
outcome = poll(record, handle, principal)
|
|
except Exception as exc:
|
|
raise PrismError(f"provider poll failed: {exc}", 502) from exc
|
|
if outcome.status not in {"queued", "running", "completed", "failed"}:
|
|
raise PrismError("provider returned an invalid generation status", 502)
|
|
if outcome.status == "completed" and not outcome.output_url:
|
|
raise PrismError("provider completed without an output URL", 502)
|
|
provider_ref = outcome.provider_ref or handle.provider_ref
|
|
if outcome.status in {"queued", "running"} and not provider_ref:
|
|
raise PrismError("provider lost the durable generation handle", 502)
|
|
cost = record.cost_micros
|
|
if outcome.cost_micros is not None:
|
|
try:
|
|
polled_cost = int(outcome.cost_micros)
|
|
except (TypeError, ValueError) as exc:
|
|
raise PrismError(
|
|
"provider returned an invalid generation cost", 502
|
|
) from exc
|
|
if polled_cost < 0 or polled_cost > record.cost_micros:
|
|
raise PrismError(
|
|
"provider-reported cost exceeded the accepted cost", 502
|
|
)
|
|
cost = polled_cost
|
|
if outcome.status == "failed":
|
|
cost = 0
|
|
persisted_handle = ExecutionOutcome(
|
|
status=outcome.status,
|
|
output_url=outcome.output_url,
|
|
cost_micros=cost,
|
|
provider_ref=provider_ref,
|
|
status_url=outcome.status_url or handle.status_url,
|
|
response_url=outcome.response_url or handle.response_url,
|
|
error=outcome.error,
|
|
provider_handle=outcome.provider_handle or handle.provider_handle,
|
|
credential_mode=outcome.credential_mode or handle.credential_mode,
|
|
)
|
|
record = record.model_copy(
|
|
update={
|
|
"status": outcome.status,
|
|
"output_url": (
|
|
outcome.output_url if outcome.status == "completed" else ""
|
|
),
|
|
"error": outcome.error,
|
|
"provider_ref": provider_ref,
|
|
"cost_micros": cost,
|
|
"attempts": self._updated_attempts(record, outcome.status),
|
|
}
|
|
)
|
|
record = self._store.put(
|
|
principal.key_fingerprint, record, persisted_handle
|
|
)
|
|
return (
|
|
self._settle_terminal(principal.key_fingerprint, record)
|
|
if record.status in {"completed", "failed"}
|
|
else self._with_settlement(principal.key_fingerprint, record)
|
|
)
|
|
|
|
def list_generations(
|
|
self, principal: Principal, limit: int = 50, status: str | None = None
|
|
) -> list[GenerationResponse]:
|
|
"""Owner-scoped generation history, newest first.
|
|
|
|
Settlement views are attached from the durable ledger so callers can
|
|
reconcile charges; list reads never poll providers or move money.
|
|
"""
|
|
if status is not None and status not in _GENERATION_STATUSES:
|
|
raise PrismError(f"unknown generation status {status!r}", 422)
|
|
records = self._store.list(
|
|
principal.key_fingerprint, min(max(1, limit), _MAX_LIST_LIMIT), status
|
|
)
|
|
views: list[GenerationResponse] = []
|
|
for record in records:
|
|
command = self._store.get_settlement(
|
|
principal.key_fingerprint, record.correlation_id
|
|
)
|
|
views.append(
|
|
record.model_copy(
|
|
update={
|
|
"settlement": (
|
|
self._settlement_view(command) if command else None
|
|
)
|
|
}
|
|
)
|
|
)
|
|
return views
|
|
|
|
def cancel(
|
|
self, principal: Principal, generation_id: str, correlation_id: str = ""
|
|
) -> GenerationResponse:
|
|
"""Cancel a queued/running generation and release its Mint hold.
|
|
|
|
Terminal generations are returned unchanged (idempotent): a completed
|
|
generation keeps its capture, a failed one keeps its release. For an
|
|
active generation the provider run is cancelled (or abandoned when the
|
|
provider has no cancel primitive), the record becomes ``failed`` with
|
|
zero cost, and the hold is released so nothing is charged.
|
|
"""
|
|
stored = self._store.get(principal.key_fingerprint, generation_id)
|
|
if stored is None:
|
|
raise PrismError("generation not found", 404)
|
|
record, handle = stored
|
|
if correlation_id and record.correlation_id != correlation_id:
|
|
raise PrismError("generation correlation mismatch", 409)
|
|
if principal.provider_api_key and principal.provider_key != record.provider:
|
|
raise PrismError(
|
|
"BYOK provider does not match the generation provider", 422
|
|
)
|
|
if record.status in {"completed", "failed"}:
|
|
return self._settle_terminal(principal.key_fingerprint, record)
|
|
|
|
error = "cancelled by caller"
|
|
cancel = getattr(self._executor, "cancel", None)
|
|
provider_handle = dict(handle.provider_handle)
|
|
if callable(cancel):
|
|
try:
|
|
outcome = cancel(record, handle, principal)
|
|
except ExecutionBlocked as exc:
|
|
# The provider refused the cancel (e.g. the run already finished
|
|
# upstream). Re-poll so a finished run is settled truthfully
|
|
# instead of being released while the provider still bills it.
|
|
refreshed = self.generation(principal, generation_id, correlation_id)
|
|
if refreshed.status in {"completed", "failed"}:
|
|
return refreshed
|
|
raise PrismError(
|
|
f"provider refused cancellation; generation still active: {exc}",
|
|
502,
|
|
) from exc
|
|
except Exception as exc:
|
|
raise PrismError(f"provider cancel failed: {exc}", 502) from exc
|
|
error = outcome.error or error
|
|
provider_handle = outcome.provider_handle or provider_handle
|
|
|
|
persisted_handle = ExecutionOutcome(
|
|
status="failed",
|
|
output_url="",
|
|
cost_micros=0,
|
|
provider_ref=handle.provider_ref,
|
|
status_url=handle.status_url,
|
|
response_url=handle.response_url,
|
|
error=error,
|
|
provider_handle=provider_handle,
|
|
credential_mode=handle.credential_mode,
|
|
)
|
|
cancelled = record.model_copy(
|
|
update={
|
|
"status": "failed",
|
|
"output_url": "",
|
|
"error": error,
|
|
"cost_micros": 0,
|
|
"attempts": self._updated_attempts(record, "failed"),
|
|
}
|
|
)
|
|
stored_record = self._store.put(
|
|
principal.key_fingerprint, cancelled, persisted_handle
|
|
)
|
|
# ``put`` never overwrites a terminal row, so if a concurrent poll already
|
|
# completed the generation the stored record wins and is settled as such.
|
|
return self._settle_terminal(principal.key_fingerprint, stored_record)
|
|
|