diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -5,7 +5,7 @@ # Authors: The scikit-plots developers # SPDX-License-Identifier: BSD-3-Clause # -# scikit-plots/ai · _hf_spaces_proxy/app.py v7.2.0 +# scikit-plots/ai · _hf_spaces_proxy/app.py v7.3.0 # # Server-authoritative chat proxy for sphinx-ai-assistant. # @@ -125,8 +125,11 @@ # Redis initialization/runtime failure returns HTTP 503. # RATE_LIMIT_REDIS_TIMEOUT_SECONDS Redis operation timeout; clamped 0.25..10 s. # FEEDBACK_PERSIST_ENABLED Persist privacy-minimal consent-gated rating telemetry only. Default false. -# CONTRIBUTION_REVIEW_TOKEN Server/operator token required to promote quarantined -# contributions into durable training-eligible storage. +# CONTRIBUTION_REVIEW_MODE ledger (compatibility) or provider-pr. provider-pr +# stores consented submissions in a native Git/HF review ref; +# only merge into the canonical branch makes them eligible. +# CONTRIBUTION_REVIEW_TOKEN Optional operator token for API-driven merge/promotion. +# Native provider UI merge/close remains the preferred review path. # CONTRIBUTION_QUARANTINE_TTL_SECONDS Pending contribution lifetime. Default 86400. # CONTRIBUTION_LEDGER_BACKEND memory (default compatibility) or sqlite. # CONTRIBUTION_LEDGER_SQLITE_PATH SQLite control-plane file when backend=sqlite. @@ -183,6 +186,7 @@ import time as _time import uuid from collections.abc import AsyncGenerator from contextlib import asynccontextmanager +from dataclasses import replace from typing import Any import httpx @@ -193,28 +197,26 @@ from fastapi.responses import JSONResponse, Response, StreamingResponse # Private service helpers live in the sibling _utils package. try: from ._utils._dataset_schema import ( # type: ignore[import] - CONSENT_VERSION_ENABLED, - RESERVED_CONSENT_VERSION, - LEGACY_CONSENT_VERSIONS, FEEDBACK_TELEMETRY_CONSENT_VERSION, FEEDBACK_TELEMETRY_SCHEMA_VERSION, - MAX_CONVERSATION_MESSAGES, - MAX_CONVERSATION_MESSAGE_CHARS, + LEGACY_CONSENT_VERSIONS, MAX_CONTRIBUTION_NOTE_CHARS, + MAX_CONVERSATION_MESSAGE_CHARS, + MAX_CONVERSATION_MESSAGES, + RESERVED_CONSENT_VERSION, normalize_contribution_record, normalize_contribution_withdrawal_record, normalize_feedback_record, ) except Exception: # noqa: BLE001 from _utils._dataset_schema import ( # type: ignore[import] - CONSENT_VERSION_ENABLED, - RESERVED_CONSENT_VERSION, - LEGACY_CONSENT_VERSIONS, FEEDBACK_TELEMETRY_CONSENT_VERSION, FEEDBACK_TELEMETRY_SCHEMA_VERSION, - MAX_CONVERSATION_MESSAGES, - MAX_CONVERSATION_MESSAGE_CHARS, + LEGACY_CONSENT_VERSIONS, MAX_CONTRIBUTION_NOTE_CHARS, + MAX_CONVERSATION_MESSAGE_CHARS, + MAX_CONVERSATION_MESSAGES, + RESERVED_CONSENT_VERSION, normalize_contribution_record, normalize_contribution_withdrawal_record, normalize_feedback_record, @@ -247,14 +249,26 @@ except Exception: # noqa: BLE001 ) try: - from ._utils._share_store import ShareStoreError, build_share_store # type: ignore[import] + from ._utils._share_store import ( # type: ignore[import] + ShareStoreError, + build_share_store, + ) except Exception: # noqa: BLE001 - from _utils._share_store import ShareStoreError, build_share_store # type: ignore[import] + from _utils._share_store import ( # type: ignore[import] + ShareStoreError, + build_share_store, + ) try: - from ._utils._rate_limit import RateLimitBackendError, RedisRateLimiter # type: ignore[import] + from ._utils._rate_limit import ( # type: ignore[import] + RateLimitBackendError, + RedisRateLimiter, + ) except Exception: # noqa: BLE001 - from _utils._rate_limit import RateLimitBackendError, RedisRateLimiter # type: ignore[import] + from _utils._rate_limit import ( # type: ignore[import] + RateLimitBackendError, + RedisRateLimiter, + ) try: from ._utils._telemetry import PrivacyJsonFormatter @@ -304,14 +318,6 @@ except Exception: # noqa: BLE001 ) try: - from ._utils._stub_model import ( # type: ignore[import] - is_stub_model, - parse_stub_mode, - stub_delay_ms, - stub_modes, - stub_payload, - stub_sse_frames, - ) from ._utils._shared_logic import ( # type: ignore[import] DEFAULT_HF_BASE, DEFAULT_HF_PROVIDER_MODELS, @@ -327,14 +333,13 @@ try: _mask_ip, _RedactingFilter, _resolve_upstream_url, - _validate_credential_destination, _safe_float, _safe_int, + _validate_credential_destination, _validate_env, _validate_token_config, ) -except Exception: # noqa: BLE001 - from _utils._stub_model import ( # type: ignore[import] + from ._utils._stub_model import ( # type: ignore[import] is_stub_model, parse_stub_mode, stub_delay_ms, @@ -342,6 +347,7 @@ except Exception: # noqa: BLE001 stub_payload, stub_sse_frames, ) +except Exception: # noqa: BLE001 from _utils._shared_logic import ( # type: ignore[import] DEFAULT_HF_BASE, DEFAULT_HF_PROVIDER_MODELS, @@ -357,12 +363,20 @@ except Exception: # noqa: BLE001 _mask_ip, _RedactingFilter, _resolve_upstream_url, - _validate_credential_destination, _safe_float, _safe_int, + _validate_credential_destination, _validate_env, _validate_token_config, ) + from _utils._stub_model import ( # type: ignore[import] + is_stub_model, + parse_stub_mode, + stub_delay_ms, + stub_modes, + stub_payload, + stub_sse_frames, + ) # ───────────────────────────────────────────────────────────────────────────── # Helpers — placed before configuration so they are available at module scope @@ -414,7 +428,9 @@ def _opaque_share_request_mode(request: Request) -> str: return "none" method = request.method.upper() if method == "OPTIONS": - method = request.headers.get("access-control-request-method", "").strip().upper() + method = ( + request.headers.get("access-control-request-method", "").strip().upper() + ) if path == "/v1/share" and method in {"GET", "HEAD"}: return "read" if path == "/v1/share/read" and method == "POST": @@ -424,7 +440,9 @@ def _opaque_share_request_mode(request: Request) -> str: return "write" -def _origin_allowed(request: Request) -> bool: +def _origin_allowed( # ruff: ignore[too-many-return-statements] + request: Request, +) -> bool: """Return whether a browser-supplied Origin is allowed for this service. Missing Origin is accepted for server-to-server/curl traffic. Origin is a @@ -454,7 +472,8 @@ def _origin_allowed(request: Request) -> bool: host = request.headers.get("host", "").strip().lower() if host: try: - from urllib.parse import urlsplit + from urllib.parse import urlsplit # ruff: ignore[import-outside-top-level] + parsed = urlsplit(origin) if parsed.scheme in {"http", "https"} and parsed.netloc.lower() == host: return True @@ -463,7 +482,9 @@ def _origin_allowed(request: Request) -> bool: return False -class _UpstreamResponseTooLarge(RuntimeError): +class _UpstreamResponseTooLarge( # ruff: ignore[error-suffix-on-exception-name] + RuntimeError, +): """Raised when decoded upstream response bytes exceed the hard application cap.""" @@ -506,16 +527,22 @@ async def _read_upstream_limited( return bytes(out) -async def _read_limited_body(request: Request, max_bytes: int, label: str = "Request") -> bytes: +async def _read_limited_body( + request: Request, max_bytes: int, label: str = "Request" +) -> bytes: """Read an ASGI request incrementally and stop once *max_bytes* is crossed.""" raw_cl = request.headers.get("content-length") if raw_cl not in (None, ""): try: content_length = int(raw_cl) except (TypeError, ValueError) as exc: - raise HTTPException(status_code=400, detail="Invalid Content-Length header.") from exc + raise HTTPException( + status_code=400, detail="Invalid Content-Length header." + ) from exc if content_length < 0: - raise HTTPException(status_code=400, detail="Invalid Content-Length header.") + raise HTTPException( + status_code=400, detail="Invalid Content-Length header." + ) if content_length > max_bytes: raise HTTPException(status_code=413, detail=f"{label} body too large.") @@ -546,18 +573,30 @@ async def _consume_rate_limit( advertised quota into independent replica-local windows. """ if RATE_LIMIT_REQUIRE_SHARED and RATE_LIMIT_BACKEND == "local": - raise HTTPException(status_code=503, detail="Shared rate limiter required by deployment policy.") + raise HTTPException( + status_code=503, detail="Shared rate limiter required by deployment policy." + ) if RATE_LIMIT_BACKEND != "local": - if _RATE_LIMIT_CONFIG_ERROR or _SHARED_RATE_LIMITER is None or not _SHARED_RATE_LIMITER_READY: - raise HTTPException(status_code=503, detail="Shared rate limiter unavailable.") + if ( + _RATE_LIMIT_CONFIG_ERROR + or _SHARED_RATE_LIMITER is None + or not _SHARED_RATE_LIMITER_READY + ): + raise HTTPException( + status_code=503, detail="Shared rate limiter unavailable." + ) try: allowed, count, _retry_after = await _SHARED_RATE_LIMITER.consume( identity, scope=scope, limit=limit, window_seconds=window_seconds ) return allowed, count except RateLimitBackendError as exc: - logger.error("Shared rate limiter failure: code=%s scope=%s", exc.code, scope) - raise HTTPException(status_code=503, detail="Shared rate limiter unavailable.") from exc + logger.error( + "Shared rate limiter failure: code=%s scope=%s", exc.code, scope + ) + raise HTTPException( + status_code=503, detail="Shared rate limiter unavailable." + ) from exc now = _time.time() async with lock: @@ -610,7 +649,10 @@ def _share_public_base(request: Request) -> str: raise HTTPException(status_code=500, detail="Share public base URL is invalid.") if safe.startswith("http://"): - from urllib.parse import urlsplit, urlunsplit + from urllib.parse import ( # ruff: ignore[import-outside-top-level] + urlsplit, + urlunsplit, + ) parsed = urlsplit(safe) host = (parsed.hostname or "").lower() @@ -625,7 +667,9 @@ def _share_public_base(request: Request) -> str: if space_base and host == space_base.removeprefix("https://"): return urlunsplit(("https", parsed.netloc, parsed.path, "", "")).rstrip("/") - raise HTTPException(status_code=500, detail="Share public base URL must use HTTPS.") + raise HTTPException( + status_code=500, detail="Share public base URL must use HTTPS." + ) return safe @@ -778,47 +822,65 @@ _DEFAULT_ALLOWED_MODELS: tuple[str, ...] = tuple( _raw_allowed_models = os.environ.get( "ALLOWED_MODELS", ",".join(_DEFAULT_ALLOWED_MODELS) ) -ALLOWED_MODELS: tuple[str, ...] = tuple( - dict.fromkeys(m.strip() for m in _raw_allowed_models.split(",") if m.strip()) -) or _DEFAULT_ALLOWED_MODELS +ALLOWED_MODELS: tuple[str, ...] = ( + tuple(dict.fromkeys(m.strip() for m in _raw_allowed_models.split(",") if m.strip())) + or _DEFAULT_ALLOWED_MODELS +) #: Maximum accepted request body size (bytes). -MAX_BODY_BYTES: int = max(16_384, min( - _safe_int(os.environ.get("MAX_BODY_BYTES"), DEFAULT_MAX_BODY_BYTES), - 16 * 1024 * 1024, -)) +MAX_BODY_BYTES: int = max( + 16_384, + min( + _safe_int(os.environ.get("MAX_BODY_BYTES"), DEFAULT_MAX_BODY_BYTES), + 16 * 1024 * 1024, + ), +) #: Maximum decoded upstream response bytes accepted before the proxy aborts the #: provider stream. This is independent from request-body limits because a #: malicious/misconfigured upstream controls response size. -MAX_UPSTREAM_RESPONSE_BYTES: int = max(64 * 1024, min( - _safe_int(os.environ.get("MAX_UPSTREAM_RESPONSE_BYTES"), 8 * 1024 * 1024), - 32 * 1024 * 1024, -)) +MAX_UPSTREAM_RESPONSE_BYTES: int = max( + 64 * 1024, + min( + _safe_int(os.environ.get("MAX_UPSTREAM_RESPONSE_BYTES"), 8 * 1024 * 1024), + 32 * 1024 * 1024, + ), +) #: Maximum JSON request size accepted by Global Share. Kept independent from #: chat bodies so a public share service cannot consume 10 MiB per request. -SHARE_MAX_BODY_BYTES: int = max(16_384, min( - _safe_int(os.environ.get("SHARE_MAX_BODY_BYTES"), 512_000), - 2_000_000, -)) +SHARE_MAX_BODY_BYTES: int = max( + 16_384, + min( + _safe_int(os.environ.get("SHARE_MAX_BODY_BYTES"), 512_000), + 2_000_000, + ), +) #: Hard in-memory share-store bounds. A deployment can lower these values but #: cannot raise them beyond conservative process-safety ceilings here. -SHARE_MAX_ENTRIES: int = max(1, min( - _safe_int(os.environ.get("SHARE_MAX_ENTRIES"), 256), - 2048, -)) -SHARE_MAX_TOTAL_BYTES: int = max(SHARE_MAX_BODY_BYTES, min( - _safe_int(os.environ.get("SHARE_MAX_TOTAL_BYTES"), 16 * 1024 * 1024), - 64 * 1024 * 1024, -)) +SHARE_MAX_ENTRIES: int = max( + 1, + min( + _safe_int(os.environ.get("SHARE_MAX_ENTRIES"), 256), + 2048, + ), +) +SHARE_MAX_TOTAL_BYTES: int = max( + SHARE_MAX_BODY_BYTES, + min( + _safe_int(os.environ.get("SHARE_MAX_TOTAL_BYTES"), 16 * 1024 * 1024), + 64 * 1024 * 1024, + ), +) #: Deployment hardening profile. ``compat`` preserves existing deployments. #: ``strict`` is used by the release container and cannot be weakened by a #: per-feature setting: it requires non-root execution, exact-origin CORS, and #: verified TLS for every configured Redis control plane. -DEPLOYMENT_PROFILE: str = os.environ.get("DEPLOYMENT_PROFILE", "compat").strip().lower() or "compat" +DEPLOYMENT_PROFILE: str = ( + os.environ.get("DEPLOYMENT_PROFILE", "compat").strip().lower() or "compat" +) _DEPLOYMENT_PROFILE_VALID: bool = DEPLOYMENT_PROFILE in {"compat", "strict"} DEPLOYMENT_STRICT: bool = DEPLOYMENT_PROFILE == "strict" REDIS_REQUIRE_TLS: bool = DEPLOYMENT_STRICT or os.environ.get( @@ -842,22 +904,36 @@ SHARE_PUBLIC_BASE_URL: str = os.environ.get("SHARE_PUBLIC_BASE_URL", "").strip() #: Global Share lifecycle storage. ``memory`` is compatibility only; it must #: never be represented as durable/shared. Requirements fail writes closed. -SHARE_STORE_BACKEND: str = os.environ.get("SHARE_STORE_BACKEND", "memory").strip().lower() or "memory" +SHARE_STORE_BACKEND: str = ( + os.environ.get("SHARE_STORE_BACKEND", "memory").strip().lower() or "memory" +) SHARE_STORE_SQLITE_PATH: str = os.environ.get( - "SHARE_STORE_SQLITE_PATH", "/tmp/scikitplot-ai-global-share.sqlite3" + "SHARE_STORE_SQLITE_PATH", + "/tmp/scikitplot-ai-global-share.sqlite3", # ruff: ignore[hardcoded-temp-file] ).strip() SHARE_STORE_REDIS_URL: str = os.environ.get("SHARE_STORE_REDIS_URL", "").strip() -SHARE_STORE_KEY_PREFIX: str = os.environ.get("SHARE_STORE_KEY_PREFIX", "sphinx-ai-assistant").strip() or "sphinx-ai-assistant" +SHARE_STORE_KEY_PREFIX: str = ( + os.environ.get("SHARE_STORE_KEY_PREFIX", "sphinx-ai-assistant").strip() + or "sphinx-ai-assistant" +) try: - _raw_share_redis_timeout = float(os.environ.get("SHARE_STORE_REDIS_TIMEOUT_SECONDS", "2") or 2) + _raw_share_redis_timeout = float( + os.environ.get("SHARE_STORE_REDIS_TIMEOUT_SECONDS", "2") or 2 + ) except (TypeError, ValueError): _raw_share_redis_timeout = 2.0 -SHARE_STORE_REDIS_TIMEOUT_SECONDS: float = max(0.25, min(10.0, _raw_share_redis_timeout)) +SHARE_STORE_REDIS_TIMEOUT_SECONDS: float = max( + 0.25, min(10.0, _raw_share_redis_timeout) +) SHARE_REDIS_DURABILITY_CONFIRMED: bool = os.environ.get( "SHARE_REDIS_DURABILITY_CONFIRMED", "false" ).strip().lower() in {"1", "true", "yes", "on"} -SHARE_REQUIRE_DURABLE: bool = os.environ.get("SHARE_REQUIRE_DURABLE", "false").strip().lower() in {"1", "true", "yes", "on"} -SHARE_REQUIRE_SHARED: bool = os.environ.get("SHARE_REQUIRE_SHARED", "false").strip().lower() in {"1", "true", "yes", "on"} +SHARE_REQUIRE_DURABLE: bool = os.environ.get( + "SHARE_REQUIRE_DURABLE", "false" +).strip().lower() in {"1", "true", "yes", "on"} +SHARE_REQUIRE_SHARED: bool = os.environ.get( + "SHARE_REQUIRE_SHARED", "false" +).strip().lower() in {"1", "true", "yes", "on"} #: Hugging Face-provided public Space hostname (for example, #: ``owner-space.hf.space``). This is deployment metadata, not caller input. @@ -927,7 +1003,8 @@ def _normalise_browser_origin(value: str) -> str: if not candidate: return "" try: - from urllib.parse import urlsplit + from urllib.parse import urlsplit # ruff: ignore[import-outside-top-level] + parsed = urlsplit(candidate) except ValueError: return "" @@ -953,12 +1030,14 @@ def _build_allowed_origins(raw: str) -> list[str]: return ["*"] merged: list[str] = list(_OFFICIAL_ALLOWED_ORIGINS) for item in text.split(","): - item = item.strip() + item = item.strip() # ruff: ignore[redefined-loop-name] if not item: continue normalised = _normalise_browser_origin(item) if not normalised: - logger.warning("AI proxy [CORS_ORIGIN_IGNORED]: malformed ALLOWED_ORIGINS entry ignored.") + logger.warning( + "AI proxy [CORS_ORIGIN_IGNORED]: malformed ALLOWED_ORIGINS entry ignored." + ) continue if normalised not in merged: merged.append(normalised) @@ -1034,14 +1113,46 @@ FEEDBACK_PERSIST_ENABLED: bool = os.environ.get( FEEDBACK_MAX_BODY_BYTES: int = 16 * 1024 #: Pending contribution review configuration. +#: ``ledger`` keeps the historical process/DB quarantine and requires explicit +#: promotion. ``provider-pr`` writes the future eligible record to a native +#: provider review ref (GitHub PR, GitLab MR, Bitbucket PR, or Hugging Face PR); +#: only merging into the configured canonical branch makes it training eligible. +CONTRIBUTION_REVIEW_MODE: str = ( + os.environ.get("CONTRIBUTION_REVIEW_MODE", "ledger").strip().lower() or "ledger" +) +if CONTRIBUTION_REVIEW_MODE not in {"ledger", "provider-pr"}: + CONTRIBUTION_REVIEW_MODE = "ledger" CONTRIBUTION_REVIEW_TOKEN: str = os.environ.get("CONTRIBUTION_REVIEW_TOKEN", "").strip() CONTRIBUTION_MAX_BODY_BYTES: int = 256 * 1024 -CONTRIBUTION_QUARANTINE_TTL_SECONDS: int = max(300, min(604800, int(os.environ.get("CONTRIBUTION_QUARANTINE_TTL_SECONDS", "86400") or 86400))) -CONTRIBUTION_QUARANTINE_MAX_ENTRIES: int = max(1, min(1024, int(os.environ.get("CONTRIBUTION_QUARANTINE_MAX_ENTRIES", "128") or 128))) -CONTRIBUTION_QUARANTINE_MAX_TOTAL_BYTES: int = max(65536, min(64 * 1024 * 1024, int(os.environ.get("CONTRIBUTION_QUARANTINE_MAX_TOTAL_BYTES", str(4 * 1024 * 1024)) or (4 * 1024 * 1024)))) -CONTRIBUTION_LEDGER_BACKEND: str = os.environ.get("CONTRIBUTION_LEDGER_BACKEND", "memory").strip().lower() or "memory" +CONTRIBUTION_QUARANTINE_TTL_SECONDS: int = max( + 300, + min( + 604800, + int(os.environ.get("CONTRIBUTION_QUARANTINE_TTL_SECONDS", "86400") or 86400), + ), +) +CONTRIBUTION_QUARANTINE_MAX_ENTRIES: int = max( + 1, + min(1024, int(os.environ.get("CONTRIBUTION_QUARANTINE_MAX_ENTRIES", "128") or 128)), +) +CONTRIBUTION_QUARANTINE_MAX_TOTAL_BYTES: int = max( + 65536, + min( + 64 * 1024 * 1024, + int( + os.environ.get( + "CONTRIBUTION_QUARANTINE_MAX_TOTAL_BYTES", str(4 * 1024 * 1024) + ) + or (4 * 1024 * 1024) + ), + ), +) +CONTRIBUTION_LEDGER_BACKEND: str = ( + os.environ.get("CONTRIBUTION_LEDGER_BACKEND", "memory").strip().lower() or "memory" +) CONTRIBUTION_LEDGER_SQLITE_PATH: str = os.environ.get( - "CONTRIBUTION_LEDGER_SQLITE_PATH", "/tmp/scikitplot-ai-contribution-lifecycle.sqlite3" + "CONTRIBUTION_LEDGER_SQLITE_PATH", + "/tmp/scikitplot-ai-contribution-lifecycle.sqlite3", # ruff: ignore[hardcoded-temp-file] ).strip() CONTRIBUTION_REQUIRE_DURABLE: bool = os.environ.get( "CONTRIBUTION_REQUIRE_DURABLE", "false" @@ -1049,27 +1160,40 @@ CONTRIBUTION_REQUIRE_DURABLE: bool = os.environ.get( CONTRIBUTION_REQUIRE_SHARED: bool = os.environ.get( "CONTRIBUTION_REQUIRE_SHARED", "false" ).strip().lower() in {"1", "true", "yes", "on"} -CONTRIBUTION_LEDGER_REDIS_URL: str = os.environ.get("CONTRIBUTION_LEDGER_REDIS_URL", "").strip() -CONTRIBUTION_LEDGER_KEY_SECRET: str = os.environ.get("CONTRIBUTION_LEDGER_KEY_SECRET", "") -CONTRIBUTION_LEDGER_KEY_PREFIX: str = os.environ.get( - "CONTRIBUTION_LEDGER_KEY_PREFIX", "sphinx-ai-assistant" -).strip() or "sphinx-ai-assistant" -CONTRIBUTION_OPERATION_LEASE_SECONDS: int = max(30, min(900, _safe_int( - os.environ.get("CONTRIBUTION_OPERATION_LEASE_SECONDS"), 120 -))) +CONTRIBUTION_LEDGER_REDIS_URL: str = os.environ.get( + "CONTRIBUTION_LEDGER_REDIS_URL", "" +).strip() +CONTRIBUTION_LEDGER_KEY_SECRET: str = os.environ.get( + "CONTRIBUTION_LEDGER_KEY_SECRET", "" +) +CONTRIBUTION_LEDGER_KEY_PREFIX: str = ( + os.environ.get("CONTRIBUTION_LEDGER_KEY_PREFIX", "sphinx-ai-assistant").strip() + or "sphinx-ai-assistant" +) +CONTRIBUTION_OPERATION_LEASE_SECONDS: int = max( + 30, min(900, _safe_int(os.environ.get("CONTRIBUTION_OPERATION_LEASE_SECONDS"), 120)) +) try: - _raw_contribution_redis_timeout = float(os.environ.get("CONTRIBUTION_LEDGER_REDIS_TIMEOUT_SECONDS", "2") or 2) + _raw_contribution_redis_timeout = float( + os.environ.get("CONTRIBUTION_LEDGER_REDIS_TIMEOUT_SECONDS", "2") or 2 + ) except (TypeError, ValueError): _raw_contribution_redis_timeout = 2.0 -CONTRIBUTION_LEDGER_REDIS_TIMEOUT_SECONDS: float = max(0.25, min(10.0, _raw_contribution_redis_timeout)) +CONTRIBUTION_LEDGER_REDIS_TIMEOUT_SECONDS: float = max( + 0.25, min(10.0, _raw_contribution_redis_timeout) +) CONTRIBUTION_LEDGER_MAX_RECEIPTS: int = max( CONTRIBUTION_QUARANTINE_MAX_ENTRIES, min(100_000, _safe_int(os.environ.get("CONTRIBUTION_LEDGER_MAX_RECEIPTS"), 10_000)), ) CONTRIBUTION_LEDGER_TERMINAL_RETENTION_SECONDS: int = max( - 300, min(30 * 86400, _safe_int( - os.environ.get("CONTRIBUTION_LEDGER_TERMINAL_RETENTION_SECONDS"), 86400 - )) + 300, + min( + 30 * 86400, + _safe_int( + os.environ.get("CONTRIBUTION_LEDGER_TERMINAL_RETENTION_SECONDS"), 86400 + ), + ), ) @@ -1077,23 +1201,38 @@ CONTRIBUTION_LEDGER_TERMINAL_RETENTION_SECONDS: int = max( #: ``redis`` is a shared atomic fixed-window decision domain suitable for #: horizontally scaled proxy replicas. Redis mode requires a >=32-byte secret #: so raw client identities are HMACed before they enter external storage. -RATE_LIMIT_BACKEND: str = os.environ.get("RATE_LIMIT_BACKEND", "local").strip().lower() or "local" +RATE_LIMIT_BACKEND: str = ( + os.environ.get("RATE_LIMIT_BACKEND", "local").strip().lower() or "local" +) RATE_LIMIT_REDIS_URL: str = os.environ.get("RATE_LIMIT_REDIS_URL", "").strip() RATE_LIMIT_IDENTITY_SECRET: str = os.environ.get("RATE_LIMIT_IDENTITY_SECRET", "") -RATE_LIMIT_KEY_PREFIX: str = os.environ.get("RATE_LIMIT_KEY_PREFIX", "sphinx-ai-assistant").strip() or "sphinx-ai-assistant" +RATE_LIMIT_KEY_PREFIX: str = ( + os.environ.get("RATE_LIMIT_KEY_PREFIX", "sphinx-ai-assistant").strip() + or "sphinx-ai-assistant" +) RATE_LIMIT_REQUIRE_SHARED: bool = os.environ.get( "RATE_LIMIT_REQUIRE_SHARED", "false" ).strip().lower() in {"1", "true", "yes", "on"} try: - _raw_rate_limit_timeout = float(os.environ.get("RATE_LIMIT_REDIS_TIMEOUT_SECONDS", "2") or 2) + _raw_rate_limit_timeout = float( + os.environ.get("RATE_LIMIT_REDIS_TIMEOUT_SECONDS", "2") or 2 + ) except (TypeError, ValueError): _raw_rate_limit_timeout = 2.0 RATE_LIMIT_REDIS_TIMEOUT_SECONDS: float = max(0.25, min(10.0, _raw_rate_limit_timeout)) -CHAT_RATE_LIMIT_PER_HOUR: int = max(1, min(_safe_int(os.environ.get("CHAT_RATE_LIMIT_PER_HOUR"), 30), 10_000)) -SHARE_RATE_LIMIT_PER_HOUR: int = max(1, min(_safe_int(os.environ.get("SHARE_RATE_LIMIT_PER_HOUR"), 10), 10_000)) -FEEDBACK_RATE_LIMIT_PER_HOUR: int = max(1, min(_safe_int(os.environ.get("FEEDBACK_RATE_LIMIT_PER_HOUR"), 30), 10_000)) -CONTRIBUTION_RATE_LIMIT_PER_HOUR: int = max(1, min(_safe_int(os.environ.get("CONTRIBUTION_RATE_LIMIT_PER_HOUR"), 5), 10_000)) +CHAT_RATE_LIMIT_PER_HOUR: int = max( + 1, min(_safe_int(os.environ.get("CHAT_RATE_LIMIT_PER_HOUR"), 30), 10_000) +) +SHARE_RATE_LIMIT_PER_HOUR: int = max( + 1, min(_safe_int(os.environ.get("SHARE_RATE_LIMIT_PER_HOUR"), 10), 10_000) +) +FEEDBACK_RATE_LIMIT_PER_HOUR: int = max( + 1, min(_safe_int(os.environ.get("FEEDBACK_RATE_LIMIT_PER_HOUR"), 30), 10_000) +) +CONTRIBUTION_RATE_LIMIT_PER_HOUR: int = max( + 1, min(_safe_int(os.environ.get("CONTRIBUTION_RATE_LIMIT_PER_HOUR"), 5), 10_000) +) #: Whether this proxy forwards the reasoning-control parameters that the #: documentation panel can send (``reasoning_effort`` for OpenAI-compatible @@ -1131,7 +1270,8 @@ CONTRIBUTION_RATE_LIMIT_PER_HOUR: int = max(1, min(_safe_int(os.environ.get("CON #: this off, the proxy returns a local HTTP 503 ``stub_disabled`` response and #: never forwards the diagnostic request to a real inference provider. STUB_ENABLED: bool = os.environ.get( - "STUB_ENABLED", "true" # "false" + "STUB_ENABLED", + "true", # "false" ).strip().lower() in ("true", "1", "yes") REASONING_ENABLED: bool = os.environ.get( @@ -1146,16 +1286,14 @@ REASONING_EFFORT_PARAM: str = os.environ.get( #: Wire field name for the extended-reasoning object. Set to an empty string #: for an upstream that offers effort but not a thinking budget. -REASONING_THINKING_PARAM: str = os.environ.get( - "REASONING_THINKING_PARAM", "" -).strip() +REASONING_THINKING_PARAM: str = os.environ.get("REASONING_THINKING_PARAM", "").strip() #: Thinking payload mode advertised to the panel when a Thinking field is #: configured. The proxy remains a transparent forwarder; this tells the UI #: only which validated adapter shape the upstream is known to accept. -_raw_reasoning_thinking_mode = os.environ.get( - "REASONING_THINKING_MODE", "budget" -).strip().lower() +_raw_reasoning_thinking_mode = ( + os.environ.get("REASONING_THINKING_MODE", "budget").strip().lower() +) if _raw_reasoning_thinking_mode not in {"boolean", "adaptive", "budget"}: logger.error( "AI proxy [REASONING_CONFIG_INVALID]: invalid REASONING_THINKING_MODE; " @@ -1195,10 +1333,13 @@ MAX_CONTRIBUTION_RECORDS: int = 100 #: Expired windows are swept before admission; when all remaining entries are #: live, a new identity fails closed instead of growing the map. This keeps #: attacker-controlled identity cardinality strictly O(_MAX_RL_ENTRIES). -_MAX_RL_ENTRIES: int = max(128, min( - _safe_int(os.environ.get("RATE_LIMIT_MAX_IDENTITIES"), 10_000), - 50_000, -)) +_MAX_RL_ENTRIES: int = max( + 128, + min( + _safe_int(os.environ.get("RATE_LIMIT_MAX_IDENTITIES"), 10_000), + 50_000, + ), +) #: In-memory per-IP rate-limit stores. Raw identities are process-memory only; #: application logs receive only the existing masked representation. @@ -1262,7 +1403,9 @@ except ContributionLedgerError as _ledger_exc: # Compatibility-only inspection alias used by older tests/debug tooling. Routes # never use this mapping as authority. It is populated only by memory backend. -_contrib_quarantine: dict[str, dict[str, Any]] = getattr(_CONTRIBUTION_LEDGER, "entries", {}) +_contrib_quarantine: dict[str, dict[str, Any]] = getattr( + _CONTRIBUTION_LEDGER, "entries", {} +) #: In-memory per-IP rate-limit store for share endpoint. _share_rl: dict[str, tuple[int, float]] = {} @@ -1274,18 +1417,23 @@ _SHARE_STORE_CONFIG_ERROR: str = "" _SHARE_STORE_READY: bool = False try: _SHARE_STORE = build_share_store( - SHARE_STORE_BACKEND, sqlite_path=SHARE_STORE_SQLITE_PATH, - redis_url=SHARE_STORE_REDIS_URL, redis_key_prefix=SHARE_STORE_KEY_PREFIX, + SHARE_STORE_BACKEND, + sqlite_path=SHARE_STORE_SQLITE_PATH, + redis_url=SHARE_STORE_REDIS_URL, + redis_key_prefix=SHARE_STORE_KEY_PREFIX, redis_timeout_seconds=SHARE_STORE_REDIS_TIMEOUT_SECONDS, redis_durable_confirmed=SHARE_REDIS_DURABILITY_CONFIRMED, require_redis_tls=REDIS_REQUIRE_TLS, - max_entries=SHARE_MAX_ENTRIES, max_total_bytes=SHARE_MAX_TOTAL_BYTES, + max_entries=SHARE_MAX_ENTRIES, + max_total_bytes=SHARE_MAX_TOTAL_BYTES, ) except ShareStoreError as _share_store_exc: _SHARE_STORE_CONFIG_ERROR = _share_store_exc.code _SHARE_STORE = build_share_store( - "memory", sqlite_path=SHARE_STORE_SQLITE_PATH, - max_entries=SHARE_MAX_ENTRIES, max_total_bytes=SHARE_MAX_TOTAL_BYTES, + "memory", + sqlite_path=SHARE_STORE_SQLITE_PATH, + max_entries=SHARE_MAX_ENTRIES, + max_total_bytes=SHARE_MAX_TOTAL_BYTES, ) _share_store: dict[str, dict[str, Any]] = getattr(_SHARE_STORE, "entries", {}) _share_store_lock = asyncio.Lock() # compatibility-only test/debug symbol @@ -1301,12 +1449,18 @@ _storage_tasks: set[asyncio.Task[Any]] = set() async def _persist_storage_record( - *, kind: str, content: bytes, commit_message: str, path_timestamp: float | None = None + *, + kind: str, + content: bytes, + commit_message: str, + path_timestamp: float | None = None, ): """Run one storage write independently of the request socket lifetime.""" task = asyncio.create_task( _STORAGE.write( - kind=kind, content=content, commit_message=commit_message, + kind=kind, + content=content, + commit_message=commit_message, path_timestamp=path_timestamp, ) ) @@ -1358,7 +1512,9 @@ if HF_TOKEN: # TRAINING_DATASET_REPO available for legacy discovery/rollback, but do not run # the legacy HF token-consistency checks against it when provider-neutral # storage is active: those writes use each target's token_env instead. -_LEGACY_HF_STORAGE_ACTIVE: bool = bool(TRAINING_DATASET_REPO and not RECORD_STORAGE_TARGETS) +_LEGACY_HF_STORAGE_ACTIVE: bool = bool( + TRAINING_DATASET_REPO and not RECORD_STORAGE_TARGETS +) _token_config_issues: list[str] = _validate_token_config( HF_TOKEN, HF_DATASET_TOKEN, @@ -1378,7 +1534,17 @@ if not BACKEND_URL and not HF_TOKEN: len(HF_SPACES_MODEL_NAMESPACES), ) -if _LEGACY_HF_STORAGE_ACTIVE and HF_DATASET_TOKEN and HF_DATASET_TOKEN_TYPE == "read": + +def is_read_only(token_type: str = HF_DATASET_TOKEN_TYPE): + """is_read_only.""" + return token_type == "read" # ruff: ignore[hardcoded-password-string] + + +if ( + _LEGACY_HF_STORAGE_ACTIVE + and HF_DATASET_TOKEN + and is_read_only(HF_DATASET_TOKEN_TYPE) +): logger.error( "Dataset persistence token is read-only; configure a repo-scoped " "fine-grained token or a classic write token." @@ -1420,7 +1586,8 @@ def _is_non_root_process() -> bool: return True try: return int(geteuid()) != 0 - except Exception: # pragma: no cover - defensive platform fallback + # defensive platform fallback + except Exception: # pragma: no cover # ruff: ignore[blind-except] return False @@ -1451,7 +1618,9 @@ def _deployment_public_status() -> dict[str, Any]: @asynccontextmanager -async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]: +async def _lifespan( # ruff: ignore[too-many-branches] + app: FastAPI, +) -> AsyncGenerator[None, None]: """ Create and close the shared HTTP client on application startup / shutdown. @@ -1470,17 +1639,25 @@ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]: global _http_client, _SHARED_RATE_LIMITER_READY, _CONTRIBUTION_LEDGER_READY, _SHARE_STORE_READY # noqa: PLW0603 _deployment_error = _deployment_policy_error() if _deployment_error: - logger.critical("Deployment hardening policy rejected startup: code=%s", _deployment_error) + logger.critical( + "Deployment hardening policy rejected startup: code=%s", _deployment_error + ) raise RuntimeError(_deployment_error) _http_client = httpx.AsyncClient(follow_redirects=False) _STORAGE.set_client(_http_client) - if RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER is not None and not _RATE_LIMIT_CONFIG_ERROR: + if ( + RATE_LIMIT_BACKEND == "redis" + and _SHARED_RATE_LIMITER is not None + and not _RATE_LIMIT_CONFIG_ERROR + ): try: await _SHARED_RATE_LIMITER.initialize() _SHARED_RATE_LIMITER_READY = True except RateLimitBackendError as exc: _SHARED_RATE_LIMITER_READY = False - logger.error("Shared rate limiter unavailable at startup: code=%s", exc.code) + logger.error( + "Shared rate limiter unavailable at startup: code=%s", exc.code + ) try: await _CONTRIBUTION_LEDGER.initialize() _CONTRIBUTION_LEDGER_READY = True @@ -1495,7 +1672,7 @@ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]: logger.error("Global Share lifecycle backend unavailable: code=%s", exc.code) await _STORAGE.initialize() for _storage_target in _STORAGE.manifest().get("targets", []): - _cap = ((_storage_target.get("token") or {}).get("write_capability") or "unknown") + _cap = (_storage_target.get("token") or {}).get("write_capability") or "unknown" if _cap in {"missing-token", "denied", "denied-read-token"}: logger.error( "Record storage target unavailable: provider=%s code=%s", @@ -1510,13 +1687,22 @@ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]: ) _ledger_manifest = _CONTRIBUTION_LEDGER.manifest() if _CONTRIBUTION_LEDGER_CONFIG_ERROR: - logger.error("Contribution lifecycle backend invalid: code=%s", _CONTRIBUTION_LEDGER_CONFIG_ERROR) + logger.error( + "Contribution lifecycle backend invalid: code=%s", + _CONTRIBUTION_LEDGER_CONFIG_ERROR, + ) if CONTRIBUTION_REQUIRE_DURABLE and not bool(_ledger_manifest.get("durable")): - logger.error("Contribution intake requires durable lifecycle storage but configured backend is non-durable.") + logger.error( + "Contribution intake requires durable lifecycle storage but configured backend is non-durable." + ) if CONTRIBUTION_REQUIRE_SHARED and not ( - bool(_ledger_manifest.get("shared")) and bool(_ledger_manifest.get("authoritative")) and _CONTRIBUTION_LEDGER_READY + bool(_ledger_manifest.get("shared")) + and bool(_ledger_manifest.get("authoritative")) + and _CONTRIBUTION_LEDGER_READY ): - logger.error("Contribution intake requires shared authoritative lifecycle storage but it is unavailable.") + logger.error( + "Contribution intake requires shared authoritative lifecycle storage but it is unavailable." + ) logger.info( "Contribution lifecycle ready: backend=%s durability=%s shared=%s", _ledger_manifest.get("backend"), @@ -1525,22 +1711,41 @@ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]: ) _share_manifest = _SHARE_STORE.manifest() if _SHARE_STORE_CONFIG_ERROR: - logger.error("Global Share lifecycle backend invalid: code=%s", _SHARE_STORE_CONFIG_ERROR) + logger.error( + "Global Share lifecycle backend invalid: code=%s", _SHARE_STORE_CONFIG_ERROR + ) if SHARE_REQUIRE_DURABLE and not bool(_share_manifest.get("durable")): - logger.error("Global Share requires durable storage but configured backend is non-durable.") - if SHARE_REQUIRE_SHARED and not (bool(_share_manifest.get("shared")) and bool(_share_manifest.get("authoritative")) and _SHARE_STORE_READY): - logger.error("Global Share requires shared authoritative storage but it is unavailable.") + logger.error( + "Global Share requires durable storage but configured backend is non-durable." + ) + if SHARE_REQUIRE_SHARED and not ( + bool(_share_manifest.get("shared")) + and bool(_share_manifest.get("authoritative")) + and _SHARE_STORE_READY + ): + logger.error( + "Global Share requires shared authoritative storage but it is unavailable." + ) logger.info( "Global Share lifecycle ready: backend=%s durability=%s shared=%s", - _share_manifest.get("backend"), _share_manifest.get("durability"), bool(_share_manifest.get("shared")), + _share_manifest.get("backend"), + _share_manifest.get("durability"), + bool(_share_manifest.get("shared")), + ) + _rl_manifest = ( + _SHARED_RATE_LIMITER.manifest() + if _SHARED_RATE_LIMITER is not None + else { + "backend": "local", + "shared": False, + "authoritative": False, + "consistency_scope": "process_local", + } ) - _rl_manifest = _SHARED_RATE_LIMITER.manifest() if _SHARED_RATE_LIMITER is not None else { - "backend": "local", "shared": False, "authoritative": False, - "consistency_scope": "process_local", - } logger.info( "Rate limit control plane: backend=%s shared=%s authoritative=%s ready=%s", - _rl_manifest.get("backend"), bool(_rl_manifest.get("shared")), + _rl_manifest.get("backend"), + bool(_rl_manifest.get("shared")), bool(_rl_manifest.get("authoritative")), RATE_LIMIT_BACKEND == "local" or _SHARED_RATE_LIMITER_READY, ) @@ -1548,6 +1753,12 @@ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]: "Proxy v%s started. HTTP client ready (timeout=per-request).", PROXY_VERSION, ) + logger.info( + "Contribution review workflow: mode=%s provider=%s canonical_branch=%s", + CONTRIBUTION_REVIEW_MODE, + getattr(getattr(_STORAGE, "primary", None), "provider", "none"), + getattr(getattr(_STORAGE, "primary", None), "branch", "none"), + ) logger.info( "Routing initialized: backend_configured=%s | model_space_configured=%s | " "hf_token_set=%s hf_token_type=%s | dataset_token_set=%s dataset_token_type=%s | " @@ -1620,7 +1831,16 @@ app.add_middleware( # HEAD added so the JS _pingUrl health-check and the HF Space internal health # monitor can send cross-origin HEAD / and HEAD /health without a CORS error. # PATCH added for PATCH /v1/share/{uuid} (content update, URL preserved). - allow_headers=["Content-Type", "Authorization", "X-Share-Edit-Token", "X-Contribution-Delete-Token", "X-AI-Operation-Id", "X-AI-Resource-Id", "X-AI-Management-Token-Hash", "X-AI-Operation-Created-At"], + allow_headers=[ + "Content-Type", + "Authorization", + "X-Share-Edit-Token", + "X-Contribution-Delete-Token", + "X-AI-Operation-Id", + "X-AI-Resource-Id", + "X-AI-Management-Token-Hash", + "X-AI-Operation-Created-At", + ], allow_credentials=False, ) @@ -1635,10 +1855,12 @@ async def _browser_origin_guard(request: Request, call_next): detail = ( "Opaque browser origin not allowed. Read-only local-file Share " "compatibility requires SHARE_ALLOW_OPAQUE_ORIGIN=true. " - + ("Opaque-origin mutation additionally requires the high-risk " - "SHARE_ALLOW_OPAQUE_ORIGIN_WRITE=true opt-in, which strict deployments forbid." - if mode == "write" else - "This compatibility also admits sandboxed opaque documents, so keep it off unless required.") + + ( + "Opaque-origin mutation additionally requires the high-risk " + "SHARE_ALLOW_OPAQUE_ORIGIN_WRITE=true opt-in, which strict deployments forbid." + if mode == "write" + else "This compatibility also admits sandboxed opaque documents, so keep it off unless required." + ) ) else: detail = ( @@ -1837,7 +2059,11 @@ async def _stub_intercept(body: bytes, headers: Any) -> Response | None: return JSONResponse(doc, status_code=status, headers={"X-Stub-Model": "true"}) -async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Response: +async def _forward( # ruff: ignore[too-many-branches, too-many-return-statements] + body: bytes, + *, + structured_body: bytes | None = None, +) -> Response: """Forward one OpenAI-compatible request with mode-aware stream bridging. Streaming is treated as a negotiated transport, not an assumption. The @@ -1911,7 +2137,9 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp clone["stream"] = bool(value) return json.dumps(clone, ensure_ascii=False, separators=(",", ":")).encode() - async def _post_buffered(request_body: bytes) -> Response: + async def _post_buffered( # ruff: ignore[too-many-return-statements] + request_body: bytes, + ) -> Response: upstream: httpx.Response | None = None try: request = _http_client.build_request( @@ -1919,11 +2147,12 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp ) upstream = await _http_client.send(request, stream=True) status = upstream.status_code - if status < 200 or status >= 300: + if status < 200 or status >= 300: # ruff: ignore[magic-value-comparison] code = _upstream_public_error_code(status) logger.warning( "AI proxy [UPSTREAM_STATUS]: upstream rejected non-streaming request status=%d code=%s", - status, code, + status, + code, ) return _error_response( status, code, "The upstream AI provider rejected the request." @@ -1931,7 +2160,9 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp media_type = upstream.headers.get("content-type", "application/json") content = await _read_upstream_limited(upstream) except _UpstreamResponseTooLarge: - logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: upstream response exceeded the application byte ceiling") + logger.warning( + "AI proxy [UPSTREAM_RESPONSE_LIMIT]: upstream response exceeded the application byte ceiling" + ) return _error_response( 502, "upstream_response_too_large", @@ -2008,7 +2239,11 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp while True: try: request = _http_client.build_request( - "POST", url, content=wire_body, headers=stream_headers, timeout=req_timeout + "POST", + url, + content=wire_body, + headers=stream_headers, + timeout=req_timeout, ) upstream = await _http_client.send(request, stream=True) break @@ -2070,7 +2305,7 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp "Failed to reach the upstream service.", ) - assert upstream is not None + assert upstream is not None # ruff: ignore[assert] if upstream.status_code != 200: # noqa: PLR2004 status = upstream.status_code @@ -2089,7 +2324,9 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp _check_upstream_declared_length(upstream) except _UpstreamResponseTooLarge: await upstream.aclose() - logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: declared upstream response exceeded the application byte ceiling") + logger.warning( + "AI proxy [UPSTREAM_RESPONSE_LIMIT]: declared upstream response exceeded the application byte ceiling" + ) return _error_response( 502, "upstream_response_too_large", @@ -2106,7 +2343,9 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp content = await _read_upstream_limited(upstream) except _UpstreamResponseTooLarge: await upstream.aclose() - logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: buffered JSON fallback exceeded the application byte ceiling") + logger.warning( + "AI proxy [UPSTREAM_RESPONSE_LIMIT]: buffered JSON fallback exceeded the application byte ceiling" + ) return _error_response( 502, "upstream_response_too_large", @@ -2161,7 +2400,7 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp # its Content-Type. A bounded prefix sniff lets us recover that format # without interpreting arbitrary provider payloads. prefix = content.lstrip()[:32].lower() - if prefix.startswith(b"data:") or prefix.startswith(b"event:"): + if prefix.startswith((b"data:", b"event:")): return Response( content=content, status_code=200, @@ -2190,7 +2429,9 @@ async def _forward(body: bytes, *, structured_body: bytes | None = None) -> Resp continue total_bytes += len(chunk) if total_bytes > MAX_UPSTREAM_RESPONSE_BYTES: - logger.warning("AI proxy [UPSTREAM_RESPONSE_LIMIT]: SSE response exceeded the application byte ceiling") + logger.warning( + "AI proxy [UPSTREAM_RESPONSE_LIMIT]: SSE response exceeded the application byte ceiling" + ) yield _sse_error_frame( 502, "upstream_response_too_large", @@ -2327,7 +2568,9 @@ def _contribution_pipeline_ready() -> bool: return False if CONTRIBUTION_REQUIRE_DURABLE and not bool(ledger.get("durable")): return False - if CONTRIBUTION_REQUIRE_SHARED and not (bool(ledger.get("shared")) and bool(ledger.get("authoritative"))): + if CONTRIBUTION_REQUIRE_SHARED and not ( + bool(ledger.get("shared")) and bool(ledger.get("authoritative")) + ): return False return _STORAGE.primary_ready() @@ -2338,7 +2581,9 @@ def _share_store_public_status() -> dict[str, Any]: ready = bool(_SHARE_STORE_READY and not _SHARE_STORE_CONFIG_ERROR) if SHARE_REQUIRE_DURABLE and not bool(manifest.get("durable")): ready = False - if SHARE_REQUIRE_SHARED and not (bool(manifest.get("shared")) and bool(manifest.get("authoritative"))): + if SHARE_REQUIRE_SHARED and not ( + bool(manifest.get("shared")) and bool(manifest.get("authoritative")) + ): ready = False return { "ready": ready, @@ -2356,7 +2601,10 @@ def _share_store_public_status() -> dict[str, Any]: def _require_share_store_ready() -> dict[str, Any]: status = _share_store_public_status() if not status["ready"]: - raise HTTPException(status_code=503, detail="Global Share lifecycle storage is unavailable for this deployment.") + raise HTTPException( + status_code=503, + detail="Global Share lifecycle storage is unavailable for this deployment.", + ) return status @@ -2381,7 +2629,9 @@ def _share_store_http_error(exc: ShareStoreError) -> HTTPException: return HTTPException(status_code=status, detail=detail) -def _operation_envelope(request: Request, payload: dict[str, Any], purpose: str, *, max_age_ms: int) -> tuple[str, str, str] | None: +def _operation_envelope( + request: Request, payload: dict[str, Any], purpose: str, *, max_age_ms: int +) -> tuple[str, str, str] | None: """Resolve a create-once envelope without receiving the raw management capability. The browser creates the public resource locator and the management token @@ -2395,26 +2645,61 @@ def _operation_envelope(request: Request, payload: dict[str, Any], purpose: str, resource_id = request.headers.get("X-AI-Resource-Id") token_hash = request.headers.get("X-AI-Management-Token-Hash") created_raw = request.headers.get("X-AI-Operation-Created-At") - if op_id is None and resource_id is None and token_hash is None and created_raw is None: + if ( + op_id is None + and resource_id is None + and token_hash is None + and created_raw is None + ): return None - if not isinstance(op_id, str) or not (16 <= len(op_id) <= 128) or any(ch not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for ch in op_id): + if ( + not isinstance(op_id, str) + or not (16 <= len(op_id) <= 128) # ruff: ignore[magic-value-comparison] + or any( + ch not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" + for ch in op_id + ) + ): raise HTTPException(status_code=422, detail="Invalid operationId.") - if not isinstance(resource_id, str) or len(resource_id) != 32 or any(ch not in "0123456789abcdefABCDEF" for ch in resource_id): - raise HTTPException(status_code=422, detail="Invalid operation resource locator.") - if not isinstance(token_hash, str) or len(token_hash) != 64 or any(ch not in "0123456789abcdefABCDEF" for ch in token_hash): - raise HTTPException(status_code=422, detail="Invalid management capability digest.") + if ( + not isinstance(resource_id, str) + or len(resource_id) != 32 # ruff: ignore[magic-value-comparison] + or any(ch not in "0123456789abcdefABCDEF" for ch in resource_id) + ): + raise HTTPException( + status_code=422, detail="Invalid operation resource locator." + ) + if ( + not isinstance(token_hash, str) + or len(token_hash) != 64 # ruff: ignore[magic-value-comparison] + or any(ch not in "0123456789abcdefABCDEF" for ch in token_hash) + ): + raise HTTPException( + status_code=422, detail="Invalid management capability digest." + ) try: created_at = int(created_raw) except (TypeError, ValueError) as exc: - raise HTTPException(status_code=422, detail="Invalid operationCreatedAt.") from exc + raise HTTPException( + status_code=422, detail="Invalid operationCreatedAt." + ) from exc now_ms = int(_time.time() * 1000) - if created_at > now_ms + 300_000 or created_at <= 0 or now_ms - created_at > max(60_000, int(max_age_ms)): - raise HTTPException(status_code=409, detail="Operation recovery window has expired; start a new reviewed operation.") + if ( + created_at > now_ms + 300_000 + or created_at <= 0 + or now_ms - created_at > max(60_000, int(max_age_ms)) + ): + raise HTTPException( + status_code=409, + detail="Operation recovery window has expired; start a new reviewed operation.", + ) return resource_id.lower(), token_hash.lower(), op_id def _canonical_payload_digest(value: Any) -> str: - encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + encoded = json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode("utf-8") return hashlib.sha256(encoded).hexdigest() @@ -2423,7 +2708,9 @@ def _cors_public_status() -> dict[str, Any]: wildcard = _allowed_origins == ["*"] return { "official_docs_origin": _DEFAULT_ALLOWED_ORIGINS, - "official_docs_origin_allowed": wildcard or _DEFAULT_ALLOWED_ORIGINS in _allowed_origins, + "official_docs_origin_allowed": ( + wildcard or _DEFAULT_ALLOWED_ORIGINS in _allowed_origins + ), "wildcard": wildcard, "allowed_origin_count": None if wildcard else len(_allowed_origins), "env_semantics": "additive", @@ -2438,7 +2725,11 @@ def _cors_public_status() -> dict[str, Any]: async def root() -> JSONResponse: """Public status/discovery with privacy-minimized collection capabilities.""" storage_manifest = _STORAGE.manifest() - storage_targets = storage_manifest.get("targets", []) if isinstance(storage_manifest, dict) else [] + storage_targets = ( + storage_manifest.get("targets", []) + if isinstance(storage_manifest, dict) + else [] + ) return JSONResponse( { "status": "ok", @@ -2451,13 +2742,21 @@ async def root() -> JSONResponse: "contribute_ready": _contribution_pipeline_ready(), "feedback_persist_enabled": FEEDBACK_PERSIST_ENABLED, "feedback_telemetry_schema_version": FEEDBACK_TELEMETRY_SCHEMA_VERSION, - "feedback_telemetry_consent_version": FEEDBACK_TELEMETRY_CONSENT_VERSION, + "feedback_telemetry_consent_version": ( + FEEDBACK_TELEMETRY_CONSENT_VERSION + ), + "contribution_review_mode": CONTRIBUTION_REVIEW_MODE, + "canonical_branch": getattr( + getattr(_STORAGE, "primary", None), "branch", None + ), }, "tokens": { "hf_token_type": "unknown", "hf_dataset_token_type": "unknown", "hf_write_token_type": "unknown", - "least_privilege_mode": bool(HF_DATASET_TOKEN_EXPLICIT or HF_WRITE_TOKEN), + "least_privilege_mode": bool( + HF_DATASET_TOKEN_EXPLICIT or HF_WRITE_TOKEN + ), }, "storage": { "configured": bool(storage_targets), @@ -2469,9 +2768,16 @@ async def root() -> JSONResponse: "backend": RATE_LIMIT_BACKEND, "shared": RATE_LIMIT_BACKEND == "redis", "authoritative": RATE_LIMIT_BACKEND == "redis", - "ready": (RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER_READY) or (RATE_LIMIT_BACKEND == "local" and not RATE_LIMIT_REQUIRE_SHARED), + "ready": ( + (RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER_READY) + or (RATE_LIMIT_BACKEND == "local" and not RATE_LIMIT_REQUIRE_SHARED) + ), "required_shared": RATE_LIMIT_REQUIRE_SHARED, - "scope": "single_redis_consistency_domain" if RATE_LIMIT_BACKEND == "redis" else "process_local", + "scope": ( + "single_redis_consistency_domain" + if RATE_LIMIT_BACKEND == "redis" + else "process_local" + ), }, "limits": {"max_upstream_response_bytes": MAX_UPSTREAM_RESPONSE_BYTES}, "cors": _cors_public_status(), @@ -2512,7 +2818,11 @@ def _reasoning_capability() -> dict: panel accepts. """ if not REASONING_ENABLED: - return {"reasoning": {"enabled": False}, "chat_request": {"contract": CHAT_CONTRACT}, "stub": _stub_capability()} + return { + "reasoning": {"enabled": False}, + "chat_request": {"contract": CHAT_CONTRACT}, + "stub": _stub_capability(), + } caps: dict = { "enabled": True, @@ -2533,7 +2843,11 @@ def _reasoning_capability() -> dict: if REASONING_THINKING_PARAM: caps["thinking_param"] = REASONING_THINKING_PARAM caps["thinking_mode"] = REASONING_THINKING_MODE - return {"reasoning": caps, "chat_request": {"contract": CHAT_CONTRACT}, "stub": _stub_capability()} + return { + "reasoning": caps, + "chat_request": {"contract": CHAT_CONTRACT}, + "stub": _stub_capability(), + } def _stub_capability() -> dict: @@ -2577,7 +2891,10 @@ async def health() -> JSONResponse: "backend": RATE_LIMIT_BACKEND, "shared": RATE_LIMIT_BACKEND == "redis", "authoritative": RATE_LIMIT_BACKEND == "redis", - "ready": (RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER_READY) or (RATE_LIMIT_BACKEND == "local" and not RATE_LIMIT_REQUIRE_SHARED), + "ready": ( + (RATE_LIMIT_BACKEND == "redis" and _SHARED_RATE_LIMITER_READY) + or (RATE_LIMIT_BACKEND == "local" and not RATE_LIMIT_REQUIRE_SHARED) + ), "required_shared": RATE_LIMIT_REQUIRE_SHARED, }, "limits": {"max_upstream_response_bytes": MAX_UPSTREAM_RESPONSE_BYTES}, @@ -2590,7 +2907,9 @@ async def health() -> JSONResponse: def _chat_contract_error_code(exc: ChatContractError) -> str: """Map a local chat-contract rejection to a bounded public reason code.""" text = str(exc) - if text == "requested model is not allowed by this proxy" or text.startswith("model "): + if text == "requested model is not allowed by this proxy" or text.startswith( + "model " + ): return "PROXY_MODEL_NOT_ALLOWED" if text.startswith("context") or "context field" in text: return "PROXY_CONTEXT_INVALID" @@ -2623,11 +2942,11 @@ def _upstream_public_error_code(status: int) -> str: """Map provider HTTP status to the browser's bounded diagnostic vocabulary.""" if status in {401, 403}: return "UPSTREAM_AUTH_OR_ACCESS_REJECTED" - if status == 404: + if status == 404: # ruff: ignore[magic-value-comparison] return "UPSTREAM_MODEL_OR_ROUTE_NOT_FOUND" - if status == 429: + if status == 429: # ruff: ignore[magic-value-comparison] return "UPSTREAM_RATE_LIMITED" - if 500 <= status <= 599: + if 500 <= status <= 599: # ruff: ignore[magic-value-comparison] return "UPSTREAM_SERVICE_ERROR" return "UPSTREAM_REQUEST_REJECTED" @@ -2651,7 +2970,7 @@ def _server_owned_chat_body(body: bytes) -> bytes: @app.post("/v1/chat/completions") -async def chat_completions( +async def chat_completions( # ruff: ignore[undocumented-param] request: Request, body: bytes = Depends(_validated_body) ) -> Response: """ @@ -2686,11 +3005,16 @@ async def chat_completions( """ client_ip = _client_ip(request) allowed, _count = await _consume_rate_limit( - _chat_rl, _chat_rl_lock, client_ip, - limit=CHAT_RATE_LIMIT_PER_HOUR, scope="chat", + _chat_rl, + _chat_rl_lock, + client_ip, + limit=CHAT_RATE_LIMIT_PER_HOUR, + scope="chat", ) if not allowed: - logger.warning(json.dumps({"event": "chat.ratelimit", "ip": _mask_ip(client_ip)})) + logger.warning( + json.dumps({"event": "chat.ratelimit", "ip": _mask_ip(client_ip)}) + ) raise HTTPException( status_code=429, detail="Rate limit exceeded for chat requests.", @@ -2707,7 +3031,7 @@ async def chat_completions( @app.post("/") -async def chat_completions_alias( +async def chat_completions_alias( # ruff: ignore[undocumented-param] request: Request, body: bytes = Depends(_validated_body) ) -> Response: """ @@ -2731,11 +3055,16 @@ async def chat_completions_alias( """ client_ip = _client_ip(request) allowed, _count = await _consume_rate_limit( - _chat_rl, _chat_rl_lock, client_ip, - limit=CHAT_RATE_LIMIT_PER_HOUR, scope="chat", + _chat_rl, + _chat_rl_lock, + client_ip, + limit=CHAT_RATE_LIMIT_PER_HOUR, + scope="chat", ) if not allowed: - logger.warning(json.dumps({"event": "chat.ratelimit", "ip": _mask_ip(client_ip)})) + logger.warning( + json.dumps({"event": "chat.ratelimit", "ip": _mask_ip(client_ip)}) + ) raise HTTPException( status_code=429, detail="Rate limit exceeded for chat requests.", @@ -2751,7 +3080,9 @@ async def chat_completions_alias( return await _forward(upstream_body, structured_body=body) -def _contribution_ledger_http_error(exc: ContributionLedgerError) -> HTTPException: +def _contribution_ledger_http_error( # ruff: ignore[too-many-return-statements] + exc: ContributionLedgerError, +) -> HTTPException: """Map private ledger state codes to bounded public lifecycle semantics.""" code = exc.code if code == "NOT_FOUND": @@ -2759,14 +3090,27 @@ def _contribution_ledger_http_error(exc: ContributionLedgerError) -> HTTPExcepti if code == "EXPIRED": return HTTPException(status_code=410, detail="Pending contribution expired.") if code in {"PROMOTION_IN_PROGRESS", "WITHDRAWAL_IN_PROGRESS", "BUSY"}: - return HTTPException(status_code=409, detail="Contribution lifecycle operation already in progress.") + return HTTPException( + status_code=409, + detail="Contribution lifecycle operation already in progress.", + ) if code in {"RECONCILIATION_REQUIRED", "STALE_CLAIM"}: - return HTTPException(status_code=409, detail="Contribution lifecycle outcome requires reconciliation.") + return HTTPException( + status_code=409, + detail="Contribution lifecycle outcome requires reconciliation.", + ) if code in {"PENDING_CAPACITY", "PENDING_BYTE_CAPACITY", "RECEIPT_CAPACITY"}: - return HTTPException(status_code=507, detail="Contribution lifecycle capacity reached.") + return HTTPException( + status_code=507, detail="Contribution lifecycle capacity reached." + ) if code in {"NOT_PENDING", "NOT_ELIGIBLE", "PROMOTION_STATE", "WITHDRAWAL_STATE"}: - return HTTPException(status_code=409, detail="Contribution is not in the required lifecycle state.") - return HTTPException(status_code=503, detail="Contribution lifecycle control plane unavailable.") + return HTTPException( + status_code=409, + detail="Contribution is not in the required lifecycle state.", + ) + return HTTPException( + status_code=503, detail="Contribution lifecycle control plane unavailable." + ) def _storage_receipt_metadata(receipt: Any) -> dict[str, Any]: @@ -2786,7 +3130,9 @@ def _contribution_status_payload(entry: dict[str, Any]) -> dict[str, Any]: "trainingEligible": state == "eligible", "trainingWithdrawn": state == "withdrawn", "lifecycleUncertain": state in {"promotion_uncertain", "withdrawal_uncertain"}, - "reconciliationRequired": state in {"promotion_uncertain", "withdrawal_uncertain"}, + "reconciliationRequired": ( + state in {"promotion_uncertain", "withdrawal_uncertain"} + ), "pendingPhysicalDeleteAvailable": state == "quarantined", # Even a mutable-store deletion is not represented as forensic/global # physical erasure: database pages/WAL, filesystem snapshots, backups, @@ -2794,13 +3140,28 @@ def _contribution_status_payload(entry: dict[str, Any]) -> dict[str, Any]: # active pending payload from this lifecycle ledger. "contentRemovedFromActiveLedger": ( state in {"deleted", "expired", "eligible", "withdrawn"} - or (state in {"withdrawing", "withdrawal_uncertain"} and not bool(entry.get("records"))) + or ( + state in {"withdrawing", "withdrawal_uncertain"} + and not bool(entry.get("records")) + ) ), "physicalErasureGuaranteed": False, "physicalErasureScope": "not-guaranteed", - "expiresAt": int(float(entry.get("expiresAt") or 0) * 1000) if entry.get("expiresAt") else None, - "promotedAt": int(float(entry.get("promotedAt") or 0) * 1000) if entry.get("promotedAt") else None, - "withdrawnAt": int(float(entry.get("withdrawnAt") or 0) * 1000) if entry.get("withdrawnAt") else None, + "expiresAt": ( + int(float(entry.get("expiresAt") or 0) * 1000) + if entry.get("expiresAt") + else None + ), + "promotedAt": ( + int(float(entry.get("promotedAt") or 0) * 1000) + if entry.get("promotedAt") + else None + ), + "withdrawnAt": ( + int(float(entry.get("withdrawnAt") or 0) * 1000) + if entry.get("withdrawnAt") + else None + ), } @@ -2817,7 +3178,9 @@ async def _persist_contribution_withdrawal( byte-identical tombstones at the same provider path instead of accumulating multiple logical withdrawal files. """ - server_ts_ms = int(server_ts_ms if server_ts_ms is not None else _time.time() * 1000) + server_ts_ms = int( + server_ts_ms if server_ts_ms is not None else _time.time() * 1000 + ) rows = [ normalize_contribution_withdrawal_record(key, server_ts_ms=server_ts_ms) for key in dedup_keys @@ -2825,7 +3188,9 @@ async def _persist_contribution_withdrawal( ] if not rows: raise StorageWriteError("WITHDRAWAL_KEYS") - content = ("\n".join(json.dumps(row, ensure_ascii=False) for row in rows)).encode("utf-8") + content = ("\n".join(json.dumps(row, ensure_ascii=False) for row in rows)).encode( + "utf-8" + ) return await _persist_storage_record( kind="contributions", content=content, @@ -2834,34 +3199,131 @@ async def _persist_contribution_withdrawal( ) -def _strict_current_contribution_records(records: list[Any]) -> None: +def _provider_review_enabled() -> bool: + return CONTRIBUTION_REVIEW_MODE == "provider-pr" + + +def _provider_review_content(entry: dict[str, Any]) -> bytes: + """Render the exact future-main bytes for a quarantined contribution.""" + reviewed: list[dict[str, Any]] = [] + for row in entry.get("records", []): + if not isinstance(row, dict): + continue + promoted = dict(row) + promoted["trainingStatus"] = "eligible" + reviewed.append(promoted) + if not reviewed: + raise StorageWriteError("EMPTY_REVIEW") + return ("\n".join(json.dumps(r, ensure_ascii=False) for r in reviewed)).encode( + "utf-8" + ) + + +async def _ensure_provider_review(entry: dict[str, Any]): + """Create or recover the native provider review for an intake receipt.""" + if not _provider_review_enabled(): + return None + if _STORAGE.primary is None: + raise StorageWriteError("NO_PRIMARY_TARGET") + return await _STORAGE.open_contribution_review( + receipt_id=str(entry.get("receiptId") or ""), + content=_provider_review_content(entry), + commit_message=( + "Automated dataset contribution review. " + "Merge to make this record training-eligible; close/decline to reject it." + ), + path_timestamp=float(entry.get("receivedAt") or _time.time()), + ) + + +async def _sync_provider_review_merge( + entry: dict[str, Any], +) -> tuple[dict[str, Any], Any | None]: + """Observe manual provider-UI merges and ratchet the local lifecycle forward.""" + if not _provider_review_enabled() or str(entry.get("state") or "") != "quarantined": + return entry, None + review = await _ensure_provider_review(entry) + if review is None or review.status != "merged": + return entry, review + try: + claimed = await _CONTRIBUTION_LEDGER.begin_promotion( + str(entry.get("receiptId") or "") + ) + claim = str(claimed.get("operationClaim") or "") or None + promoted = await _CONTRIBUTION_LEDGER.mark_promoted( + str(entry.get("receiptId") or ""), + storage=review.storage_metadata(), + claim_token=claim, + ) + logger.info( + json.dumps( + {"event": "contribute.review_merged", "provider": review.provider} + ) + ) + return promoted, review + except ContributionLedgerError as exc: + # Another replica/request may have observed the same merge first. Re-read + # rather than interpreting an already-ratcheted state as a merge failure. + current = await _CONTRIBUTION_LEDGER.get(str(entry.get("receiptId") or "")) + if current is not None and str(current.get("state") or "") == "eligible": + return current, review + raise _contribution_ledger_http_error(exc) from exc + + +def _strict_current_contribution_records( # ruff: ignore[too-many-branches] + records: list[Any], +) -> None: """Reject schema-v4 reviewed content that normalization would truncate/drop.""" for index, rec in enumerate(records): if not isinstance(rec, dict): - raise HTTPException(status_code=422, detail=f"records[{index}] must be an object.") + raise HTTPException( + status_code=422, detail=f"records[{index}] must be an object." + ) record_type = rec.get("recordType") if record_type not in {"qa", "conversation"}: - raise HTTPException(status_code=422, detail=f"records[{index}].recordType must be qa or conversation.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].recordType must be qa or conversation.", + ) note = rec.get("message", "") if note is not None and not isinstance(note, str): - raise HTTPException(status_code=422, detail=f"records[{index}].message must be text.") + raise HTTPException( + status_code=422, detail=f"records[{index}].message must be text." + ) if isinstance(note, str) and len(note) > MAX_CONTRIBUTION_NOTE_CHARS: - raise HTTPException(status_code=422, detail=f"records[{index}].message exceeds {MAX_CONTRIBUTION_NOTE_CHARS} characters.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].message exceeds {MAX_CONTRIBUTION_NOTE_CHARS} characters.", + ) if record_type == "qa": for field in ("query", "answer"): value = rec.get(field, "") if not isinstance(value, str): - raise HTTPException(status_code=422, detail=f"records[{index}].{field} must be text.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].{field} must be text.", + ) if len(value) > MAX_CONVERSATION_MESSAGE_CHARS: - raise HTTPException(status_code=422, detail=f"records[{index}].{field} exceeds {MAX_CONVERSATION_MESSAGE_CHARS} characters.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].{field} exceeds {MAX_CONVERSATION_MESSAGE_CHARS} characters.", + ) if not rec.get("query") and not rec.get("answer"): - raise HTTPException(status_code=422, detail=f"records[{index}] contains no Q&A content.") + raise HTTPException( + status_code=422, detail=f"records[{index}] contains no Q&A content." + ) continue messages = rec.get("messages") if not isinstance(messages, list) or not messages: - raise HTTPException(status_code=422, detail=f"records[{index}].messages must be a non-empty list.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].messages must be a non-empty list.", + ) if len(messages) > MAX_CONVERSATION_MESSAGES: - raise HTTPException(status_code=422, detail=f"records[{index}].messages exceeds {MAX_CONVERSATION_MESSAGES} messages.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].messages exceeds {MAX_CONVERSATION_MESSAGES} messages.", + ) for msg_index, message in enumerate(messages): if not isinstance(message, dict): # Legacy/current normalization deliberately ignores non-object @@ -2880,20 +3342,39 @@ def _strict_current_contribution_records(records: list[Any]) -> None: # "No valid contribution records" error remains authoritative. continue if len(content) > MAX_CONVERSATION_MESSAGE_CHARS: - raise HTTPException(status_code=422, detail=f"records[{index}].messages[{msg_index}].content exceeds {MAX_CONVERSATION_MESSAGE_CHARS} characters.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].messages[{msg_index}].content exceeds {MAX_CONVERSATION_MESSAGE_CHARS} characters.", + ) feedback = message.get("feedback") if feedback is not None: if not isinstance(feedback, dict): - raise HTTPException(status_code=422, detail=f"records[{index}].messages[{msg_index}].feedback must be an object.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].messages[{msg_index}].feedback must be an object.", + ) fb_note = feedback.get("note", "") if not isinstance(fb_note, str): - raise HTTPException(status_code=422, detail=f"records[{index}].messages[{msg_index}].feedback.note must be text.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].messages[{msg_index}].feedback.note must be text.", + ) if len(fb_note) > MAX_CONTRIBUTION_NOTE_CHARS: - raise HTTPException(status_code=422, detail=f"records[{index}].messages[{msg_index}].feedback.note exceeds {MAX_CONTRIBUTION_NOTE_CHARS} characters.") + raise HTTPException( + status_code=422, + detail=f"records[{index}].messages[{msg_index}].feedback.note exceeds {MAX_CONTRIBUTION_NOTE_CHARS} characters.", + ) -def _contribution_replay_response(entry: dict[str, Any], *, receipt_id: str, delete_token: str, - ledger_manifest: dict[str, Any], replay: bool) -> JSONResponse: +def _contribution_replay_response( + entry: dict[str, Any], + *, + receipt_id: str, + delete_token: str, + ledger_manifest: dict[str, Any], + replay: bool, + review: Any | None = None, +) -> JSONResponse: body = { "accepted": True, "status": str(entry.get("state") or "quarantined"), @@ -2903,7 +3384,14 @@ def _contribution_replay_response(entry: dict[str, Any], *, receipt_id: str, del "consentVersion": RESERVED_CONSENT_VERSION, "receiptDurability": ledger_manifest.get("durability"), "idempotentReplay": bool(replay), + "reviewMode": CONTRIBUTION_REVIEW_MODE, + "trainingEligible": str(entry.get("state") or "") == "eligible", } + if review is not None: + body["reviewProvider"] = str(getattr(review, "provider", "") or "") + body["reviewStatus"] = str(getattr(review, "status", "") or "") + elif _provider_review_enabled() and _STORAGE.primary is not None: + body["reviewProvider"] = _STORAGE.primary.provider # Legacy/non-envelope API clients need the generated capability once. # Current browser clients already hold it locally, so never echo it. if delete_token: @@ -2912,7 +3400,9 @@ def _contribution_replay_response(entry: dict[str, Any], *, receipt_id: str, del @app.post("/v1/contribute") -async def contribute(request: Request) -> JSONResponse: +async def contribute( # ruff: ignore[too-many-branches] + request: Request, +) -> JSONResponse: """Accept explicit content into quarantine with create-once recovery. Schema-v4 intake validates the exact reviewed content before normalization; @@ -2923,46 +3413,86 @@ async def contribute(request: Request) -> JSONResponse: """ ledger_manifest = _CONTRIBUTION_LEDGER.manifest() if _CONTRIBUTION_LEDGER_CONFIG_ERROR: - raise HTTPException(status_code=503, detail="Contribution lifecycle storage is misconfigured.") + raise HTTPException( + status_code=503, detail="Contribution lifecycle storage is misconfigured." + ) if not _CONTRIBUTION_LEDGER_READY: - raise HTTPException(status_code=503, detail="Contribution lifecycle storage is unavailable.") + raise HTTPException( + status_code=503, detail="Contribution lifecycle storage is unavailable." + ) if CONTRIBUTION_REQUIRE_DURABLE and not bool(ledger_manifest.get("durable")): - raise HTTPException(status_code=503, detail="Durable contribution lifecycle storage is required.") + raise HTTPException( + status_code=503, + detail="Durable contribution lifecycle storage is required.", + ) if CONTRIBUTION_REQUIRE_SHARED and not ( - bool(ledger_manifest.get("shared")) and bool(ledger_manifest.get("authoritative")) + bool(ledger_manifest.get("shared")) + and bool(ledger_manifest.get("authoritative")) ): - raise HTTPException(status_code=503, detail="Shared contribution lifecycle authority is required.") - + raise HTTPException( + status_code=503, + detail="Shared contribution lifecycle authority is required.", + ) + raw = await _read_limited_body(request, CONTRIBUTION_MAX_BODY_BYTES, "Contribution") try: payload = json.loads(raw) except json.JSONDecodeError as exc: raise HTTPException(status_code=400, detail="Invalid JSON body.") from exc if not isinstance(payload, dict): - raise HTTPException(status_code=422, detail="Contribution body must be a JSON object.") + raise HTTPException( + status_code=422, detail="Contribution body must be a JSON object." + ) if payload.get("consentFlag") is not True: - raise HTTPException(status_code=422, detail="Explicit contribution consent is required.") + raise HTTPException( + status_code=422, detail="Explicit contribution consent is required." + ) schema_version = payload.get("schemaVersion") if schema_version not in {2, 3, 4}: - raise HTTPException(status_code=422, detail="Unsupported contribution schemaVersion.") + raise HTTPException( + status_code=422, detail="Unsupported contribution schemaVersion." + ) consent_version = payload.get("consentVersion") - consent_ok = consent_version == RESERVED_CONSENT_VERSION if schema_version == 4 else consent_version in (LEGACY_CONSENT_VERSIONS | {RESERVED_CONSENT_VERSION}) + consent_ok = ( + consent_version == RESERVED_CONSENT_VERSION + if schema_version == 4 # ruff: ignore[magic-value-comparison] + else consent_version in (LEGACY_CONSENT_VERSIONS | {RESERVED_CONSENT_VERSION}) + ) if not consent_ok: - raise HTTPException(status_code=422, detail="Consent text changed or is missing. Reload the page and review consent again.") + raise HTTPException( + status_code=422, + detail="Consent text changed or is missing. Reload the page and review consent again.", + ) records = payload.get("records") if not isinstance(records, list) or not records: raise HTTPException(status_code=422, detail="records must be a non-empty list.") if len(records) > MAX_CONTRIBUTION_RECORDS: - raise HTTPException(status_code=422, detail=f"Too many records. Maximum {MAX_CONTRIBUTION_RECORDS} per request.") - if schema_version == 4: + raise HTTPException( + status_code=422, + detail=f"Too many records. Maximum {MAX_CONTRIBUTION_RECORDS} per request.", + ) + if schema_version == 4: # ruff: ignore[magic-value-comparison] _strict_current_contribution_records(records) - envelope = _operation_envelope(request, payload, "contribution", max_age_ms=min(CONTRIBUTION_QUARANTINE_TTL_SECONDS, CONTRIBUTION_LEDGER_TERMINAL_RETENTION_SECONDS) * 1000) + envelope = _operation_envelope( + request, + payload, + "contribution", + max_age_ms=min( + CONTRIBUTION_QUARANTINE_TTL_SECONDS, + CONTRIBUTION_LEDGER_TERMINAL_RETENTION_SECONDS, + ) + * 1000, + ) if envelope: receipt_id, delete_hash, operation_id = envelope delete_token = "" # raw capability never crosses the create request boundary else: - receipt_id, delete_token, operation_id = uuid.uuid4().hex, generate_edit_token(), "" + receipt_id, delete_token, operation_id = ( + uuid.uuid4().hex, + generate_edit_token(), + "", + ) delete_hash = hash_edit_token(delete_token) payload_digest = _canonical_payload_digest(payload) @@ -2975,13 +3505,51 @@ async def contribute(request: Request) -> JSONResponse: raise _contribution_ledger_http_error(exc) from exc if existing is None: return None - operation = existing.get("operation") if isinstance(existing.get("operation"), dict) else {} - if not secrets.compare_digest(str(operation.get("payloadDigest") or ""), payload_digest) or \ - not secrets.compare_digest(str(operation.get("operationId") or ""), operation_id) or \ - not secrets.compare_digest(str(existing.get("deleteTokenHash") or ""), delete_hash): - raise HTTPException(status_code=409, detail="Operation identity was already used with different contribution content.") - return _contribution_replay_response(existing, receipt_id=receipt_id, delete_token=delete_token, - ledger_manifest=ledger_manifest, replay=True) + operation = ( + existing.get("operation") + if isinstance(existing.get("operation"), dict) + else {} + ) + if ( + not secrets.compare_digest( + str(operation.get("payloadDigest") or ""), payload_digest + ) + or not secrets.compare_digest( + str(operation.get("operationId") or ""), operation_id + ) + or not secrets.compare_digest( + str(existing.get("deleteTokenHash") or ""), delete_hash + ) + ): + raise HTTPException( + status_code=409, + detail="Operation identity was already used with different contribution content.", + ) + review = None + if ( + _provider_review_enabled() + and str(existing.get("state") or "") == "quarantined" + ): + try: + review = await _ensure_provider_review(existing) + except StorageWriteError as exc: + logger.error( + json.dumps( + {"event": "contribute.review_recover_fail", "code": exc.code} + ) + ) + raise HTTPException( + status_code=503, + detail="Contribution review could not be recovered.", + ) from exc + return _contribution_replay_response( + existing, + receipt_id=receipt_id, + delete_token=delete_token, + ledger_manifest=ledger_manifest, + replay=True, + review=review, + ) replay = await _replay_if_same() if replay is not None: @@ -2989,27 +3557,69 @@ async def contribute(request: Request) -> JSONResponse: return replay client_ip = _client_ip(request) - allowed, _count = await _consume_rate_limit(_contrib_rl, _contrib_rl_lock, client_ip, - limit=CONTRIBUTION_RATE_LIMIT_PER_HOUR, scope="contribution") + allowed, _count = await _consume_rate_limit( + _contrib_rl, + _contrib_rl_lock, + client_ip, + limit=CONTRIBUTION_RATE_LIMIT_PER_HOUR, + scope="contribution", + ) if not allowed: - logger.warning(json.dumps({"event": "contribute.ratelimit", "ip": _mask_ip(client_ip)})) - raise HTTPException(status_code=429, detail="Rate limit exceeded.", headers={"Retry-After": "3600"}) + logger.warning( + json.dumps({"event": "contribute.ratelimit", "ip": _mask_ip(client_ip)}) + ) + raise HTTPException( + status_code=429, + detail="Rate limit exceeded.", + headers={"Retry-After": "3600"}, + ) server_ts_ms = int(_time.time() * 1000) - normalized = [normalize_contribution_record(rec, envelope=payload, server_ts_ms=server_ts_ms, - training_status="quarantined", submission_id=receipt_id) for rec in records] - normalized = [row for row in normalized if row.get("recordType") != "conversation" or bool(row.get("messages"))] + normalized = [ + normalize_contribution_record( + rec, + envelope=payload, + server_ts_ms=server_ts_ms, + training_status="quarantined", + submission_id=receipt_id, + ) + for rec in records + ] + normalized = [ + row + for row in normalized + if row.get("recordType") != "conversation" or bool(row.get("messages")) + ] if not normalized: - raise HTTPException(status_code=422, detail="No valid contribution records were supplied.") - encoded = ("\n".join(json.dumps(r, ensure_ascii=False) for r in normalized)).encode("utf-8") + raise HTTPException( + status_code=422, detail="No valid contribution records were supplied." + ) + encoded = ("\n".join(json.dumps(r, ensure_ascii=False) for r in normalized)).encode( + "utf-8" + ) expires_at = _time.time() + CONTRIBUTION_QUARANTINE_TTL_SECONDS entry = { - "receiptId": receipt_id, "state": "quarantined", "records": normalized, - "bytes": len(encoded), "deleteTokenHash": delete_hash, - "expiresAt": expires_at, "receivedAt": _time.time(), - "dedupKeys": [str(row.get("_dedup_key") or "") for row in normalized if row.get("_dedup_key")], - "storage": {}, "withdrawalStorage": {}, "currentViewRemoval": {}, "lastError": "", - "operation": {"payloadDigest": payload_digest, "operationId": operation_id} if envelope else {}, + "receiptId": receipt_id, + "state": "quarantined", + "records": normalized, + "bytes": len(encoded), + "deleteTokenHash": delete_hash, + "expiresAt": expires_at, + "receivedAt": _time.time(), + "dedupKeys": [ + str(row.get("_dedup_key") or "") + for row in normalized + if row.get("_dedup_key") + ], + "storage": {}, + "withdrawalStorage": {}, + "currentViewRemoval": {}, + "lastError": "", + "operation": ( + {"payloadDigest": payload_digest, "operationId": operation_id} + if envelope + else {} + ), "rowCount": len(normalized), } try: @@ -3021,12 +3631,49 @@ async def contribute(request: Request) -> JSONResponse: return replay raise _contribution_ledger_http_error(exc) from exc - logger.info(json.dumps({"event": "contribute.quarantined", "rows": len(normalized), "idempotent": bool(envelope)})) - return _contribution_replay_response(entry, receipt_id=receipt_id, delete_token=delete_token, - ledger_manifest=ledger_manifest, replay=False) + review = None + if _provider_review_enabled(): + try: + review = await _ensure_provider_review(entry) + except StorageWriteError as exc: + # Leave the receipt in quarantine on ambiguous provider outcomes so + # the create-once replay can recover the deterministic native review. + # Definite failures are also retained for bounded TTL rather than + # pretending the submission never existed after consented intake. + logger.error( + json.dumps({"event": "contribute.review_open_fail", "code": exc.code}) + ) + raise HTTPException( + status_code=503, + detail="Contribution was quarantined but its provider review could not be opened. Retry the same submission.", + ) from exc + + logger.info( + json.dumps( + { + "event": "contribute.quarantined", + "rows": len(normalized), + "idempotent": bool(envelope), + "review_mode": CONTRIBUTION_REVIEW_MODE, + "review_provider": ( + getattr(review, "provider", None) if review is not None else None + ), + } + ) + ) + return _contribution_replay_response( + entry, + receipt_id=receipt_id, + delete_token=delete_token, + ledger_manifest=ledger_manifest, + replay=False, + review=review, + ) -async def _authorized_contribution_entry(receipt_id: str, request: Request) -> dict[str, Any]: +async def _authorized_contribution_entry( + receipt_id: str, request: Request +) -> dict[str, Any]: try: entry = await _CONTRIBUTION_LEDGER.get(receipt_id) except ContributionLedgerError as exc: @@ -3034,8 +3681,12 @@ async def _authorized_contribution_entry(receipt_id: str, request: Request) -> d if entry is None: raise HTTPException(status_code=404, detail="Contribution receipt not found.") supplied = request.headers.get("X-Contribution-Delete-Token", "") - if not supplied or not verify_edit_token(supplied, str(entry.get("deleteTokenHash") or "")): - raise HTTPException(status_code=403, detail="Invalid contribution management capability.") + if not supplied or not verify_edit_token( + supplied, str(entry.get("deleteTokenHash") or "") + ): + raise HTTPException( + status_code=403, detail="Invalid contribution management capability." + ) return entry @@ -3043,11 +3694,26 @@ async def _authorized_contribution_entry(receipt_id: str, request: Request) -> d async def contribution_status(receipt_id: str, request: Request) -> JSONResponse: """Return capability-protected lifecycle status without returning content.""" entry = await _authorized_contribution_entry(receipt_id, request) - return JSONResponse(_contribution_status_payload(entry), headers={"Cache-Control": "no-store"}) + review = None + if _provider_review_enabled() and str(entry.get("state") or "") == "quarantined": + try: + entry, review = await _sync_provider_review_merge(entry) + except StorageWriteError as exc: + logger.warning( + json.dumps({"event": "contribute.review_status_fail", "code": exc.code}) + ) + body = _contribution_status_payload(entry) + body["reviewMode"] = CONTRIBUTION_REVIEW_MODE + if review is not None: + body["reviewProvider"] = review.provider + body["reviewStatus"] = review.status + return JSONResponse(body, headers={"Cache-Control": "no-store"}) @app.delete("/v1/contribute/{receipt_id}") -async def delete_or_withdraw_contribution(receipt_id: str, request: Request) -> JSONResponse: +async def delete_or_withdraw_contribution( # ruff: ignore[too-many-branches] + receipt_id: str, request: Request +) -> JSONResponse: """Delete pending data or withdraw a previously promoted contribution. Pending deletion removes content from the active mutable ledger before it @@ -3060,30 +3726,60 @@ async def delete_or_withdraw_contribution(receipt_id: str, request: Request) -> entry = await _authorized_contribution_entry(receipt_id, request) state = str(entry.get("state") or "") + if state == "quarantined" and _provider_review_enabled(): + try: + entry, _review = await _sync_provider_review_merge(entry) + state = str(entry.get("state") or "") + if state == "quarantined": + close_result = await _STORAGE.close_contribution_review(receipt_id) + logger.info( + json.dumps( + {"event": "contribute.review_closed", "result": close_result} + ) + ) + except StorageWriteError as exc: + logger.error( + json.dumps({"event": "contribute.review_close_fail", "code": exc.code}) + ) + raise HTTPException( + status_code=503, + detail="Contribution review could not be closed safely.", + ) from exc + if state == "quarantined": try: deleted = await _CONTRIBUTION_LEDGER.delete_pending(receipt_id) except ContributionLedgerError as exc: raise _contribution_ledger_http_error(exc) from exc logger.info(json.dumps({"event": "contribute.pending_deleted"})) - return JSONResponse({ - "deleted": True, - **_contribution_status_payload(deleted), - }) + return JSONResponse( + { + "deleted": True, + **_contribution_status_payload(deleted), + } + ) if state == "deleted": return JSONResponse({"deleted": True, **_contribution_status_payload(entry)}) if state == "expired": raise HTTPException(status_code=410, detail="Pending contribution expired.") if state in {"promoting", "withdrawing"}: - raise HTTPException(status_code=409, detail="Contribution lifecycle operation already in progress.") + raise HTTPException( + status_code=409, + detail="Contribution lifecycle operation already in progress.", + ) if state == "withdrawn": - return JSONResponse({ - "withdrawn": True, - **_contribution_status_payload(entry), - "currentViewRemoval": entry.get("currentViewRemoval") or {}, - }) + return JSONResponse( + { + "withdrawn": True, + **_contribution_status_payload(entry), + "currentViewRemoval": entry.get("currentViewRemoval") or {}, + } + ) if state not in {"eligible", "promotion_uncertain", "withdrawal_uncertain"}: - raise HTTPException(status_code=409, detail="Contribution cannot be managed in its current state.") + raise HTTPException( + status_code=409, + detail="Contribution cannot be managed in its current state.", + ) try: claimed = await _CONTRIBUTION_LEDGER.begin_withdrawal(receipt_id) @@ -3091,9 +3787,13 @@ async def delete_or_withdraw_contribution(receipt_id: str, request: Request) -> except ContributionLedgerError as exc: raise _contribution_ledger_http_error(exc) from exc - dedup_keys = [str(v) for v in claimed.get("dedupKeys", []) if isinstance(v, str) and v] + dedup_keys = [ + str(v) for v in claimed.get("dedupKeys", []) if isinstance(v, str) and v + ] try: - promoted_at = float(claimed.get("promotedAt") or claimed.get("receivedAt") or _time.time()) + promoted_at = float( + claimed.get("promotedAt") or claimed.get("receivedAt") or _time.time() + ) withdrawal_receipt = await _persist_contribution_withdrawal( dedup_keys, commit_message=f"Withdraw reviewed contribution receipt ({len(dedup_keys)} record(s))", @@ -3101,11 +3801,19 @@ async def delete_or_withdraw_contribution(receipt_id: str, request: Request) -> path_timestamp=promoted_at, ) except StorageWriteError as exc: - await _CONTRIBUTION_LEDGER.withdrawal_failed(receipt_id, exc.code, claim_token=operation_claim) - logger.error(json.dumps({"event": "contribute.withdraw_fail", "code": exc.code})) - raise HTTPException(status_code=503, detail="Failed to persist training withdrawal.") from exc + await _CONTRIBUTION_LEDGER.withdrawal_failed( + receipt_id, exc.code, claim_token=operation_claim + ) + logger.error( + json.dumps({"event": "contribute.withdraw_fail", "code": exc.code}) + ) + raise HTTPException( + status_code=503, detail="Failed to persist training withdrawal." + ) from exc - original_storage = claimed.get("storage") if isinstance(claimed.get("storage"), dict) else {} + original_storage = ( + claimed.get("storage") if isinstance(claimed.get("storage"), dict) else {} + ) removal = await _STORAGE.remove_current_view( dict(original_storage.get("paths") or {}), record_id=str(original_storage.get("recordId") or "") or None, @@ -3121,27 +3829,44 @@ async def delete_or_withdraw_contribution(receipt_id: str, request: Request) -> except ContributionLedgerError as exc: # The authoritative training withdrawal already exists. Do not retry the # eligible write or falsely report erasure; surface control-plane failure. - logger.error(json.dumps({"event": "contribute.withdraw_ledger_fail", "code": exc.code})) - raise HTTPException(status_code=503, detail="Training withdrawal persisted but lifecycle confirmation failed.") from exc + logger.error( + json.dumps({"event": "contribute.withdraw_ledger_fail", "code": exc.code}) + ) + raise HTTPException( + status_code=503, + detail="Training withdrawal persisted but lifecycle confirmation failed.", + ) from exc logger.info(json.dumps({"event": "contribute.withdrawn", "rows": len(dedup_keys)})) - return JSONResponse({ - "withdrawn": True, - **_contribution_status_payload(withdrawn), - "currentViewRemoval": removal, - "trainingWithdrawalRecordId": withdrawal_meta.get("recordId"), - }, status_code=202) + return JSONResponse( + { + "withdrawn": True, + **_contribution_status_payload(withdrawn), + "currentViewRemoval": removal, + "trainingWithdrawalRecordId": withdrawal_meta.get("recordId"), + }, + status_code=202, + ) @app.post("/v1/contribute/{receipt_id}/promote") -async def promote_contribution(receipt_id: str, request: Request) -> JSONResponse: +async def promote_contribution( # ruff: ignore[too-many-branches] + receipt_id: str, + request: Request, +) -> JSONResponse: """Atomically claim review, then promote only once to training-eligible storage.""" auth = request.headers.get("Authorization", "") token = auth[7:] if auth.lower().startswith("bearer ") else "" - if not CONTRIBUTION_REVIEW_TOKEN or not secrets.compare_digest(token, CONTRIBUTION_REVIEW_TOKEN): - raise HTTPException(status_code=401, detail="Contribution review authorization required.") + if not CONTRIBUTION_REVIEW_TOKEN or not secrets.compare_digest( + token, CONTRIBUTION_REVIEW_TOKEN + ): + raise HTTPException( + status_code=401, detail="Contribution review authorization required." + ) if _STORAGE.primary is None: - raise HTTPException(status_code=503, detail="Training storage is not configured.") + raise HTTPException( + status_code=503, detail="Training storage is not configured." + ) try: entry = await _CONTRIBUTION_LEDGER.begin_promotion(receipt_id) operation_claim = str(entry.get("operationClaim") or "") or None @@ -3156,16 +3881,32 @@ async def promote_contribution(receipt_id: str, request: Request) -> JSONRespons promoted["trainingStatus"] = "eligible" reviewed.append(promoted) if not reviewed: - await _CONTRIBUTION_LEDGER.promotion_failed(receipt_id, "EMPTY_REVIEW", claim_token=operation_claim) - raise HTTPException(status_code=409, detail="Contribution contains no reviewable records.") + await _CONTRIBUTION_LEDGER.promotion_failed( + receipt_id, "EMPTY_REVIEW", claim_token=operation_claim + ) + raise HTTPException( + status_code=409, detail="Contribution contains no reviewable records." + ) - content = ("\n".join(json.dumps(r, ensure_ascii=False) for r in reviewed)).encode("utf-8") + content = ("\n".join(json.dumps(r, ensure_ascii=False) for r in reviewed)).encode( + "utf-8" + ) try: - receipt = await _persist_storage_record( - kind="contributions", content=content, - commit_message=f"Promote {len(reviewed)} reviewed contribution record(s)", - path_timestamp=float(entry.get("receivedAt") or _time.time()), - ) + if _provider_review_enabled(): + # The native provider review already contains these exact eligible + # bytes. Merge the PR/MR instead of creating a second direct commit. + prepared_review = await _ensure_provider_review(entry) + merged_review = await _STORAGE.merge_contribution_review(receipt_id) + if prepared_review is None: + raise StorageWriteError("REVIEW_NOT_FOUND") + receipt = replace(prepared_review, status=merged_review.status) + else: + receipt = await _persist_storage_record( + kind="contributions", + content=content, + commit_message=f"Promote {len(reviewed)} reviewed contribution record(s)", + path_timestamp=float(entry.get("receivedAt") or _time.time()), + ) except StorageWriteError as exc: if bool(getattr(exc, "transient", False)): try: @@ -3173,29 +3914,60 @@ async def promote_contribution(receipt_id: str, request: Request) -> JSONRespons receipt_id, exc.code, claim_token=operation_claim ) except ContributionLedgerError as ledger_exc: - logger.error(json.dumps({"event": "contribute.promote_uncertain_ledger_fail", "code": ledger_exc.code})) - logger.error(json.dumps({"event": "contribute.promote_outcome_uncertain", "code": exc.code})) + logger.error( + json.dumps( + { + "event": "contribute.promote_uncertain_ledger_fail", + "code": ledger_exc.code, + } + ) + ) + logger.error( + json.dumps( + {"event": "contribute.promote_outcome_uncertain", "code": exc.code} + ) + ) raise HTTPException( status_code=503, detail="Training storage outcome is uncertain; re-promotion is blocked. Use the contribution management capability to withdraw it or reconcile operationally.", ) from exc - await _CONTRIBUTION_LEDGER.promotion_failed(receipt_id, exc.code, claim_token=operation_claim) + await _CONTRIBUTION_LEDGER.promotion_failed( + receipt_id, exc.code, claim_token=operation_claim + ) logger.error(json.dumps({"event": "contribute.promote_fail", "code": exc.code})) - raise HTTPException(status_code=503, detail="Failed to store reviewed contribution.") from exc + raise HTTPException( + status_code=503, detail="Failed to store reviewed contribution." + ) from exc - storage_meta = _storage_receipt_metadata(receipt) + storage_meta = ( + receipt.storage_metadata() + if _provider_review_enabled() + else _storage_receipt_metadata(receipt) + ) try: - await _CONTRIBUTION_LEDGER.mark_promoted(receipt_id, storage=storage_meta, claim_token=operation_claim) + await _CONTRIBUTION_LEDGER.mark_promoted( + receipt_id, storage=storage_meta, claim_token=operation_claim + ) except ContributionLedgerError as exc: # Durable eligible bytes now exist but the mutable ledger could not # confirm them. Fail safe by writing withdrawal tombstones immediately; # never reopen the receipt for a second promotion race. - dedup_keys = [str(v) for v in entry.get("dedupKeys", []) if isinstance(v, str) and v] + dedup_keys = [ + str(v) for v in entry.get("dedupKeys", []) if isinstance(v, str) and v + ] compensation = "not-attempted" try: - compensation_ts = max( - [int(r.get("_ts") or 0) for r in entry.get("records", []) if isinstance(r, dict)] or [0] - ) + 1 + compensation_ts = ( + max( + [ + int(r.get("_ts") or 0) + for r in entry.get("records", []) + if isinstance(r, dict) + ] + or [0] + ) + + 1 + ) received_at = float(entry.get("receivedAt") or _time.time()) await _persist_contribution_withdrawal( dedup_keys, @@ -3210,26 +3982,39 @@ async def promote_contribution(receipt_id: str, request: Request) -> JSONRespons ) except StorageWriteError: compensation = "withdrawal-failed" - logger.error(json.dumps({ - "event": "contribute.promote_ledger_fail", - "code": exc.code, - "compensation": compensation, - })) - raise HTTPException(status_code=503, detail="Promotion could not be safely finalized.") from exc + logger.error( + json.dumps( + { + "event": "contribute.promote_ledger_fail", + "code": exc.code, + "compensation": compensation, + } + ) + ) + raise HTTPException( + status_code=503, detail="Promotion could not be safely finalized." + ) from exc logger.info(json.dumps({"event": "contribute.promoted", "rows": len(reviewed)})) - return JSONResponse({ - "promoted": True, - "status": "eligible", - "rows": len(reviewed), - "recordId": receipt.record_id, - "primary": receipt.primary, - "mirrors": receipt.mirrors, - }) + return JSONResponse( + { + "promoted": True, + "status": "eligible", + "rows": len(reviewed), + "recordId": receipt.record_id, + "primary": ( + receipt.review_url if _provider_review_enabled() else receipt.primary + ), + "mirrors": {} if _provider_review_enabled() else receipt.mirrors, + "reviewMode": CONTRIBUTION_REVIEW_MODE, + } + ) @app.post("/v1/share") -async def share(request: Request) -> JSONResponse: +async def share( # ruff: ignore[too-many-branches] + request: Request, +) -> JSONResponse: """Create a Global Share with optional create-once recovery semantics. Current browser clients create the public locator and revoke capability @@ -3252,7 +4037,9 @@ async def share(request: Request) -> JSONResponse: provided = auth[7:] if auth.lower().startswith("bearer ") else "" if not provided or not secrets.compare_digest(provided, SHARE_WRITE_TOKEN): logger.warning(json.dumps({"event": "share.auth_fail"})) - raise HTTPException(status_code=401, detail="Not authorized to create shares.") + raise HTTPException( + status_code=401, detail="Not authorized to create shares." + ) try: snapshot = canonicalize_share_snapshot(payload.get("snapshot")) @@ -3260,18 +4047,26 @@ async def share(request: Request) -> JSONResponse: except ShareValidationError as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc ttl_days = max(1, min(_safe_int(payload.get("ttlDays"), 30), 365)) - canonical_bytes = len(json.dumps(snapshot, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + canonical_bytes = len( + json.dumps(snapshot, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + ) if canonical_bytes > SHARE_MAX_BODY_BYTES: - raise HTTPException(status_code=413, detail="Canonical share payload too large.") + raise HTTPException( + status_code=413, detail="Canonical share payload too large." + ) - envelope = _operation_envelope(request, payload, "share", max_age_ms=ttl_days * 86400 * 1000) + envelope = _operation_envelope( + request, payload, "share", max_age_ms=ttl_days * 86400 * 1000 + ) if envelope: share_id, edit_hash, operation_id = envelope edit_token = "" # raw revoke capability remains browser-only on create else: share_id, edit_token, operation_id = uuid.uuid4().hex, generate_edit_token(), "" edit_hash = hash_edit_token(edit_token) - payload_digest = _canonical_payload_digest({"snapshot": snapshot, "format": fmt, "ttlDays": ttl_days}) + payload_digest = _canonical_payload_digest( + {"snapshot": snapshot, "format": fmt, "ttlDays": ttl_days} + ) base_url = _share_public_base(request) async def _replay_if_same() -> JSONResponse | None: @@ -3285,10 +4080,21 @@ async def share(request: Request) -> JSONResponse: raise _share_store_http_error(exc) from exc if existing is None: return None - if not secrets.compare_digest(str(existing.get("operation_payload_digest") or ""), payload_digest) or \ - not secrets.compare_digest(str(existing.get("operation_id") or ""), operation_id) or \ - not secrets.compare_digest(str(existing.get("edit_hash") or ""), edit_hash): - raise HTTPException(status_code=409, detail="Operation identity was already used with different Share content.") + if ( + not secrets.compare_digest( + str(existing.get("operation_payload_digest") or ""), payload_digest + ) + or not secrets.compare_digest( + str(existing.get("operation_id") or ""), operation_id + ) + or not secrets.compare_digest( + str(existing.get("edit_hash") or ""), edit_hash + ) + ): + raise HTTPException( + status_code=409, + detail="Operation identity was already used with different Share content.", + ) body = { "uuid": share_id, "url": f"{base_url}/v1/share#share={share_id}", @@ -3307,11 +4113,21 @@ async def share(request: Request) -> JSONResponse: client_ip = _client_ip(request) allowed, _count = await _consume_rate_limit( - _share_rl, _share_rl_lock, client_ip, limit=SHARE_RATE_LIMIT_PER_HOUR, scope="share" + _share_rl, + _share_rl_lock, + client_ip, + limit=SHARE_RATE_LIMIT_PER_HOUR, + scope="share", ) if not allowed: - logger.warning(json.dumps({"event": "share.ratelimit", "ip": _mask_ip(client_ip)})) - raise HTTPException(status_code=429, detail="Rate limit exceeded for Global Share writes.", headers={"Retry-After": "3600"}) + logger.warning( + json.dumps({"event": "share.ratelimit", "ip": _mask_ip(client_ip)}) + ) + raise HTTPException( + status_code=429, + detail="Rate limit exceeded for Global Share writes.", + headers={"Retry-After": "3600"}, + ) now_ts = _time.time() expires_ts = now_ts + ttl_days * 86400 @@ -3339,10 +4155,18 @@ async def share(request: Request) -> JSONResponse: return replay raise _share_store_http_error(exc) from exc - logger.info(json.dumps({ - "event": "share.create", "ip": _mask_ip(client_ip), "bytes": canonical_bytes, - "format": fmt, "ttl_days": ttl_days, "idempotent": bool(envelope), - })) + logger.info( + json.dumps( + { + "event": "share.create", + "ip": _mask_ip(client_ip), + "bytes": canonical_bytes, + "format": fmt, + "ttl_days": ttl_days, + "idempotent": bool(envelope), + } + ) + ) body = { "uuid": share_id, "url": f"{base_url}/v1/share#share={share_id}", @@ -3354,6 +4178,7 @@ async def share(request: Request) -> JSONResponse: body["editToken"] = edit_token return JSONResponse(body, headers={"Cache-Control": "no-store"}) + _SHARE_LOCATOR_BODY_BYTES = 4096 @@ -3400,7 +4225,11 @@ def _require_legacy_share_entry(entry: dict[str, Any]) -> None: def _legacy_share_headers(entry: dict[str, Any]) -> dict[str, str]: expires_ts = float(entry.get("expiresAt_ts") or 0) - sunset = _time.strftime("%a, %d %b %Y %H:%M:%S GMT", _time.gmtime(expires_ts)) if expires_ts > 0 else "" + sunset = ( + _time.strftime("%a, %d %b %Y %H:%M:%S GMT", _time.gmtime(expires_ts)) + if expires_ts > 0 + else "" + ) headers = { # RFC 9745 Structured Field Date: Run 14 deprecation effective # 2026-08-29T00:00:00Z. @@ -3425,7 +4254,9 @@ async def share_viewer() -> Response: "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "no-referrer", - "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "Permissions-Policy": ( + "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()" + ), "X-Robots-Tag": "noindex, nofollow, noarchive", "Content-Security-Policy": ( "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; " @@ -3443,7 +4274,7 @@ async def share_read_fixed(request: Request) -> JSONResponse: try: entry = await _share_lookup_live(share_id) except HTTPException as exc: - if exc.status_code == 404: + if exc.status_code == 404: # ruff: ignore[magic-value-comparison] logger.info(json.dumps({"event": "share.miss"})) raise try: @@ -3452,18 +4283,24 @@ async def share_read_fixed(request: Request) -> JSONResponse: logger.error(json.dumps({"event": "share.corrupt_entry"})) raise HTTPException(status_code=500, detail="Stored share is invalid.") from exc logger.info(json.dumps({"event": "share.read", "format": entry["format"]})) - payload: dict[str, Any] = {"format": entry["format"], "expiresAt": entry["expiresAt"]} + payload: dict[str, Any] = { + "format": entry["format"], + "expiresAt": entry["expiresAt"], + } if entry["format"] == "html": payload["snapshot"] = entry["snapshot"] else: payload["content"] = content - return JSONResponse(payload, headers={ - "Cache-Control": "private, no-store", - "Pragma": "no-cache", - "X-Content-Type-Options": "nosniff", - "Referrer-Policy": "no-referrer", - "X-Robots-Tag": "noindex, nofollow, noarchive", - }) + return JSONResponse( + payload, + headers={ + "Cache-Control": "private, no-store", + "Pragma": "no-cache", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Robots-Tag": "noindex, nofollow, noarchive", + }, + ) @app.post("/v1/share/status") @@ -3473,13 +4310,16 @@ async def share_status_fixed(request: Request) -> Response: share_id = _parse_share_locator_payload(raw) entry = await _share_lookup_live(share_id) logger.info(json.dumps({"event": "share.status", "format": entry["format"]})) - return Response(status_code=200, headers={ - "Cache-Control": "private, no-store", - "Pragma": "no-cache", - "X-Content-Type-Options": "nosniff", - "Referrer-Policy": "no-referrer", - "X-Robots-Tag": "noindex, nofollow, noarchive", - }) + return Response( + status_code=200, + headers={ + "Cache-Control": "private, no-store", + "Pragma": "no-cache", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Robots-Tag": "noindex, nofollow, noarchive", + }, + ) @app.post("/v1/share/update") @@ -3512,13 +4352,21 @@ async def share_update_fixed(request: Request) -> JSONResponse: json.dumps(snapshot, ensure_ascii=False, separators=(",", ":")).encode("utf-8") ) if canonical_bytes > SHARE_MAX_BODY_BYTES: - raise HTTPException(status_code=413, detail="Canonical share payload too large.") + raise HTTPException( + status_code=413, detail="Canonical share payload too large." + ) client_ip = _client_ip(request) allowed, _count = await _consume_rate_limit( - _share_rl, _share_rl_lock, client_ip, limit=SHARE_RATE_LIMIT_PER_HOUR, scope="share" + _share_rl, + _share_rl_lock, + client_ip, + limit=SHARE_RATE_LIMIT_PER_HOUR, + scope="share", ) if not allowed: - logger.warning(json.dumps({"event": "share.ratelimit", "ip": _mask_ip(client_ip)})) + logger.warning( + json.dumps({"event": "share.ratelimit", "ip": _mask_ip(client_ip)}) + ) raise HTTPException( status_code=429, detail="Rate limit exceeded for Global Share writes.", @@ -3540,22 +4388,30 @@ async def share_update_fixed(request: Request) -> JSONResponse: "operation_payload_digest": "", } try: - await _SHARE_STORE.replace_authorized(share_id, hash_edit_token(edit_token), next_entry) + await _SHARE_STORE.replace_authorized( + share_id, hash_edit_token(edit_token), next_entry + ) except ShareStoreError as exc: raise _share_store_http_error(exc) from exc - logger.info(json.dumps({ - "event": "share.update", - "ip": _mask_ip(client_ip), - "bytes": canonical_bytes, - "format": fmt, - "ttl_days": ttl_days, - })) + logger.info( + json.dumps( + { + "event": "share.update", + "ip": _mask_ip(client_ip), + "bytes": canonical_bytes, + "format": fmt, + "ttl_days": ttl_days, + } + ) + ) base_url = _share_public_base(request) - return JSONResponse({ - "uuid": share_id, - "url": f"{base_url}/v1/share#share={share_id}", - "expiresAt": expires_iso, - }) + return JSONResponse( + { + "uuid": share_id, + "url": f"{base_url}/v1/share#share={share_id}", + "expiresAt": expires_iso, + } + ) @app.post("/v1/share/revoke") @@ -3578,31 +4434,42 @@ async def share_revoke_fixed(request: Request) -> JSONResponse: @app.head("/v1/share/{share_id}") async def share_head(share_id: str) -> Response: - """Deprecated lifecycle probe for pre-generation Share objects only.""" + """Deprecate lifecycle probe for pre-generation Share objects only.""" if not valid_share_id(share_id): raise HTTPException(status_code=404, detail="Share not found or expired.") entry = await _share_lookup_live(share_id) _require_legacy_share_entry(entry) - logger.info(json.dumps({"event": "share.status", "format": entry["format"], "legacy_transport": True})) - return Response(status_code=200, headers={ - "Cache-Control": "private, no-store", - "Pragma": "no-cache", - "X-Content-Type-Options": "nosniff", - "Referrer-Policy": "no-referrer", - "X-Robots-Tag": "noindex, nofollow, noarchive", - **_legacy_share_headers(entry), - }) + logger.info( + json.dumps( + { + "event": "share.status", + "format": entry["format"], + "legacy_transport": True, + } + ) + ) + return Response( + status_code=200, + headers={ + "Cache-Control": "private, no-store", + "Pragma": "no-cache", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Robots-Tag": "noindex, nofollow, noarchive", + **_legacy_share_headers(entry), + }, + ) @app.get("/v1/share/{share_id}") async def share_get(share_id: str) -> Response: - """Deprecated direct renderer for pre-generation Share objects only.""" + """Deprecate direct renderer for pre-generation Share objects only.""" if not valid_share_id(share_id): raise HTTPException(status_code=404, detail="Share not found or expired.") try: entry = await _share_lookup_live(share_id) except HTTPException as exc: - if exc.status_code == 404: + if exc.status_code == 404: # ruff: ignore[magic-value-comparison] logger.info(json.dumps({"event": "share.miss"})) raise _require_legacy_share_entry(entry) @@ -3620,7 +4487,9 @@ async def share_get(share_id: str) -> Response: "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "no-referrer", - "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "Permissions-Policy": ( + "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()" + ), "X-Robots-Tag": "noindex, nofollow, noarchive", **_legacy_share_headers(entry), } @@ -3630,7 +4499,9 @@ async def share_get(share_id: str) -> Response: "base-uri 'none'; form-action 'none'; frame-ancestors 'none'" ) logger.info(json.dumps({"event": "share.read", "format": entry["format"]})) - return Response(content=content, status_code=200, media_type=mime_type, headers=headers) + return Response( + content=content, status_code=200, media_type=mime_type, headers=headers + ) @app.patch("/v1/share/{share_id}") @@ -3671,7 +4542,10 @@ async def share_delete(share_id: str, request: Request) -> JSONResponse: except ShareStoreError as exc: raise _share_store_http_error(exc) from exc logger.info(json.dumps({"event": "share.revoke", "legacy_transport": True})) - return JSONResponse({"revoked": True}, headers={"Cache-Control": "no-store", **_legacy_share_headers(entry)}) + return JSONResponse( + {"revoked": True}, + headers={"Cache-Control": "no-store", **_legacy_share_headers(entry)}, + ) @app.post("/v1/feedback") @@ -3702,17 +4576,28 @@ async def feedback(request: Request) -> JSONResponse: # of clicking a local rating button. Reject legacy/misbehaving clients that # do not carry the current explicit consent marker. This check occurs before # rate-limit/storage work so denied telemetry consumes minimal server state. - if payload.get("telemetryConsent") is not True or payload.get("telemetryConsentVersion") != FEEDBACK_TELEMETRY_CONSENT_VERSION: + if ( + payload.get("telemetryConsent") is not True + or payload.get("telemetryConsentVersion") != FEEDBACK_TELEMETRY_CONSENT_VERSION + ): logger.warning(json.dumps({"event": "feedback.consent_required"})) raise HTTPException( status_code=403, detail="Explicit feedback telemetry permission is required.", ) if payload.get("schemaVersion") != FEEDBACK_TELEMETRY_SCHEMA_VERSION: - raise HTTPException(status_code=422, detail="Unsupported feedback telemetry schema version.") + raise HTTPException( + status_code=422, detail="Unsupported feedback telemetry schema version." + ) consent_at = payload.get("telemetryConsentAt") - if not isinstance(consent_at, (int, float)) or isinstance(consent_at, bool) or consent_at <= 0: - raise HTTPException(status_code=422, detail="Feedback telemetry consent timestamp is required.") + if ( + not isinstance(consent_at, (int, float)) + or isinstance(consent_at, bool) + or consent_at <= 0 + ): + raise HTTPException( + status_code=422, detail="Feedback telemetry consent timestamp is required." + ) # ── Distinguish retraction tombstones from regular ratings ─────────────── # Retractions are system-generated housekeeping records that invalidate a @@ -3729,11 +4614,16 @@ async def feedback(request: Request) -> JSONResponse: client_ip = _client_ip(request) allowed, _count = await _consume_rate_limit( - _feedback_rl, _feedback_rl_lock, client_ip, - limit=FEEDBACK_RATE_LIMIT_PER_HOUR, scope="feedback", + _feedback_rl, + _feedback_rl_lock, + client_ip, + limit=FEEDBACK_RATE_LIMIT_PER_HOUR, + scope="feedback", ) if not allowed: - logger.warning(json.dumps({"event": "feedback.ratelimit", "ip": _mask_ip(client_ip)})) + logger.warning( + json.dumps({"event": "feedback.ratelimit", "ip": _mask_ip(client_ip)}) + ) raise HTTPException( status_code=429, detail="Rate limit exceeded for feedback submissions.", @@ -3746,9 +4636,17 @@ async def feedback(request: Request) -> JSONResponse: status_code=422, detail="Retraction records must include a non-empty prevSessionId.", ) - logger.info(json.dumps({"event": "feedback.retract", "persist": FEEDBACK_PERSIST_ENABLED})) + logger.info( + json.dumps( + {"event": "feedback.retract", "persist": FEEDBACK_PERSIST_ENABLED} + ) + ) else: - logger.info(json.dumps({"event": "feedback.receive", "persist": FEEDBACK_PERSIST_ENABLED})) + logger.info( + json.dumps( + {"event": "feedback.receive", "persist": FEEDBACK_PERSIST_ENABLED} + ) + ) # ── Optional provider-neutral record persistence ───────────────────────── # Activated only when FEEDBACK_PERSIST_ENABLED=true and a primary storage @@ -3773,16 +4671,23 @@ async def feedback(request: Request) -> JSONResponse: content=record.encode("utf-8"), commit_message=commit_msg, ) - logger.info(json.dumps({ - "event": "feedback.persist_ok", - "retract": is_retract, - "mirror_count": len(receipt.mirrors), - "mirror_degraded": sum(1 for _v in receipt.mirrors.values() if _v != "ok"), - })) + logger.info( + json.dumps( + { + "event": "feedback.persist_ok", + "retract": is_retract, + "mirror_count": len(receipt.mirrors), + "mirror_degraded": sum( + 1 for _v in receipt.mirrors.values() if _v != "ok" + ), + } + ) + ) except StorageWriteError as exc: # Never propagate: rating UX remains successful even when storage is # degraded. Log only the sanitized adapter code, never provider body. - logger.error(json.dumps({"event": "feedback.persist_fail", "code": exc.code})) - + logger.error( + json.dumps({"event": "feedback.persist_fail", "code": exc.code}) + ) return JSONResponse({"ok": True})